diff --git a/.fern/metadata.json b/.fern/metadata.json new file mode 100644 index 00000000..ef3f5299 --- /dev/null +++ b/.fern/metadata.json @@ -0,0 +1,22 @@ +{ + "cliVersion": "3.0.2", + "generatorName": "fernapi/fern-typescript-sdk", + "generatorVersion": "3.35.8", + "generatorConfig": { + "namespaceExport": "Intercom", + "allowCustomFetcher": true, + "skipResponseValidation": true, + "includeApiReference": true, + "noSerdeLayer": true, + "enableInlineTypes": true, + "inlinePathParameters": true, + "timeoutInSeconds": 20, + "packageJson": { + "license": "Apache-2.0", + "description": "Official Node bindings to the Intercom API", + "homepage": "https://github.com/intercom/intercom-node", + "bugs": "https://github.com/intercom/intercom-node/issues", + "keywords": ["intercom", "api"] + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc8979c7..6d5b7754 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,29 +8,38 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 - name: Set up node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + + - name: Install dependencies + run: pnpm install --frozen-lockfile - name: Compile - run: yarn && yarn build + run: pnpm build test: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 - name: Set up node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 + + - name: Install pnpm + uses: pnpm/action-setup@v4 - - name: Compile - run: yarn + - name: Install dependencies + run: pnpm install --frozen-lockfile - name: Test - run: yarn test + run: pnpm test env: INTERCOM_API_KEY: ${{ secrets.INTERCOM_API_KEY }} @@ -42,13 +51,15 @@ jobs: id-token: write steps: - name: Checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 - name: Set up node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 + - name: Install pnpm + uses: pnpm/action-setup@v4 - name: Install dependencies - run: yarn install + run: pnpm install - name: Build - run: yarn build + run: pnpm build - name: Publish to npm run: | diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 6db0876c..00000000 --- a/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -node_modules -src -tests -.gitignore -.github -.fernignore -.prettierrc.yml -tsconfig.json -yarn.lock \ No newline at end of file diff --git a/.prettierrc.yml b/.prettierrc.yml deleted file mode 100644 index 0c06786b..00000000 --- a/.prettierrc.yml +++ /dev/null @@ -1,2 +0,0 @@ -tabWidth: 4 -printWidth: 120 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..fe5bc2f7 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,133 @@ +# Contributing + +Thanks for your interest in contributing to this SDK! This document provides guidelines for contributing to the project. + +## Getting Started + +### Prerequisites + +- Node.js 20 or higher +- pnpm package manager + +### Installation + +Install the project dependencies: + +```bash +pnpm install +``` + +### Building + +Build the project: + +```bash +pnpm build +``` + +### Testing + +Run the test suite: + +```bash +pnpm test +``` + +Run specific test types: +- `pnpm test:unit` - Run unit tests +- `pnpm test:wire` - Run wire/integration tests + +### Linting and Formatting + +Check code style: + +```bash +pnpm run lint +pnpm run format:check +``` + +Fix code style issues: + +```bash +pnpm run lint:fix +pnpm run format:fix +``` + +Or use the combined check command: + +```bash +pnpm run check:fix +``` + +## About Generated Code + +**Important**: Most files in this SDK are automatically generated by [Fern](https://buildwithfern.com) from the API definition. Direct modifications to generated files will be overwritten the next time the SDK is generated. + +### Generated Files + +The following directories contain generated code: +- `src/api/` - API client classes and types +- `src/serialization/` - Serialization/deserialization logic +- Most TypeScript files in `src/` + +### How to Customize + +If you need to customize the SDK, you have two options: + +#### Option 1: Use `.fernignore` + +For custom code that should persist across SDK regenerations: + +1. Create a `.fernignore` file in the project root +2. Add file patterns for files you want to preserve (similar to `.gitignore` syntax) +3. Add your custom code to those files + +Files listed in `.fernignore` will not be overwritten when the SDK is regenerated. + +For more information, see the [Fern documentation on custom code](https://buildwithfern.com/learn/sdks/overview/custom-code). + +#### Option 2: Contribute to the Generator + +If you want to change how code is generated for all users of this SDK: + +1. The TypeScript SDK generator lives in the [Fern repository](https://github.com/fern-api/fern) +2. Generator code is located at `generators/typescript/sdk/` +3. Follow the [Fern contributing guidelines](https://github.com/fern-api/fern/blob/main/CONTRIBUTING.md) +4. Submit a pull request with your changes to the generator + +This approach is best for: +- Bug fixes in generated code +- New features that would benefit all users +- Improvements to code generation patterns + +## Making Changes + +### Workflow + +1. Create a new branch for your changes +2. Make your modifications +3. Run tests to ensure nothing breaks: `pnpm test` +4. Run linting and formatting: `pnpm run check:fix` +5. Build the project: `pnpm build` +6. Commit your changes with a clear commit message +7. Push your branch and create a pull request + +### Commit Messages + +Write clear, descriptive commit messages that explain what changed and why. + +### Code Style + +This project uses automated code formatting and linting. Run `pnpm run check:fix` before committing to ensure your code meets the project's style guidelines. + +## Questions or Issues? + +If you have questions or run into issues: + +1. Check the [Fern documentation](https://buildwithfern.com) +2. Search existing [GitHub issues](https://github.com/fern-api/fern/issues) +3. Open a new issue if your question hasn't been addressed + +## License + +By contributing to this project, you agree that your contributions will be licensed under the same license as the project. diff --git a/README.md b/README.md index 08d01dae..753ab107 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2Fintercom%2Fintercom-node) [![npm shield](https://img.shields.io/npm/v/intercom-client)](https://www.npmjs.com/package/intercom-client) -The Intercom TypeScript library provides convenient access to the Intercom API from TypeScript. +The Intercom TypeScript library provides convenient access to the Intercom APIs from TypeScript. ## Project Updates @@ -27,12 +27,8 @@ Instantiate and use the client with the following: import { IntercomClient } from "intercom-client"; const client = new IntercomClient({ token: "YOUR_TOKEN" }); -await client.articles.create({ - title: "Thanks for everything", - description: "Description of the Article", - body: "Body of the Article", - author_id: 1295, - state: "published", +await client.aiContent.createContentImportSource({ + url: "https://www.example.com" }); ``` @@ -58,7 +54,7 @@ will be thrown. import { IntercomError } from "intercom-client"; try { - await client.articles.create(...); + await client.aiContent.createContentImportSource(...); } catch (err) { if (err instanceof IntercomError) { console.log(err.statusCode); @@ -77,16 +73,19 @@ List endpoints are paginated. The SDK provides an iterator so that you can simpl import { IntercomClient } from "intercom-client"; const client = new IntercomClient({ token: "YOUR_TOKEN" }); -const response = await client.articles.list(); -for await (const item of response) { +const pageableResponse = await client.articles.list(); +for await (const item of pageableResponse) { console.log(item); } // Or you can manually iterate page-by-page -const page = await client.articles.list(); +let page = await client.articles.list(); while (page.hasNextPage()) { page = page.getNextPage(); } + +// You can also access the underlying response +const response = page.response; ``` ## Advanced @@ -96,13 +95,25 @@ while (page.hasNextPage()) { If you would like to send additional headers as part of the request, use the `headers` request option. ```typescript -const response = await client.articles.create(..., { +const response = await client.aiContent.createContentImportSource(..., { headers: { 'X-Custom-Header': 'custom value' } }); ``` +### Additional Query String Parameters + +If you would like to send additional query string parameters as part of the request, use the `queryParams` request option. + +```typescript +const response = await client.aiContent.createContentImportSource(..., { + queryParams: { + 'customQueryParamKey': 'custom query param value' + } +}); +``` + ### Retries The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long @@ -118,7 +129,7 @@ A request is deemed retryable when any of the following HTTP status codes is ret Use the `maxRetries` request option to configure this behavior. ```typescript -const response = await client.articles.create(..., { +const response = await client.aiContent.createContentImportSource(..., { maxRetries: 0 // override maxRetries at the request level }); ``` @@ -128,7 +139,7 @@ const response = await client.articles.create(..., { The SDK defaults to a 60 second timeout. Use the `timeoutInSeconds` option to configure this behavior. ```typescript -const response = await client.articles.create(..., { +const response = await client.aiContent.createContentImportSource(..., { timeoutInSeconds: 30 // override timeout to 30s }); ``` @@ -139,7 +150,7 @@ The SDK allows users to abort requests at any point by passing in an abort signa ```typescript const controller = new AbortController(); -const response = await client.articles.create(..., { +const response = await client.aiContent.createContentImportSource(..., { abortSignal: controller.signal }); controller.abort(); // aborts the request @@ -151,16 +162,81 @@ The SDK provides access to raw response data, including headers, through the `.w The `.withRawResponse()` method returns a promise that results to an object with a `data` and a `rawResponse` property. ```typescript -const { data, rawResponse } = await client.articles.create(...).withRawResponse(); +const { data, rawResponse } = await client.aiContent.createContentImportSource(...).withRawResponse(); console.log(data); console.log(rawResponse.headers['X-My-Header']); ``` +### Logging + +The SDK supports logging. You can configure the logger by passing in a `logging` object to the client options. + +```typescript +import { IntercomClient, logging } from "intercom-client"; + +const client = new IntercomClient({ + ... + logging: { + level: logging.LogLevel.Debug, // defaults to logging.LogLevel.Info + logger: new logging.ConsoleLogger(), // defaults to ConsoleLogger + silent: false, // defaults to true, set to false to enable logging + } +}); +``` +The `logging` object can have the following properties: +- `level`: The log level to use. Defaults to `logging.LogLevel.Info`. +- `logger`: The logger to use. Defaults to a `logging.ConsoleLogger`. +- `silent`: Whether to silence the logger. Defaults to `true`. + +The `level` property can be one of the following values: +- `logging.LogLevel.Debug` +- `logging.LogLevel.Info` +- `logging.LogLevel.Warn` +- `logging.LogLevel.Error` + +To provide a custom logger, you can pass in an object that implements the `logging.ILogger` interface. + +
+Custom logger examples + +Here's an example using the popular `winston` logging library. +```ts +import winston from 'winston'; + +const winstonLogger = winston.createLogger({...}); + +const logger: logging.ILogger = { + debug: (msg, ...args) => winstonLogger.debug(msg, ...args), + info: (msg, ...args) => winstonLogger.info(msg, ...args), + warn: (msg, ...args) => winstonLogger.warn(msg, ...args), + error: (msg, ...args) => winstonLogger.error(msg, ...args), +}; +``` + +Here's an example using the popular `pino` logging library. + +```ts +import pino from 'pino'; + +const pinoLogger = pino({...}); + +const logger: logging.ILogger = { + debug: (msg, ...args) => pinoLogger.debug(args, msg), + info: (msg, ...args) => pinoLogger.info(args, msg), + warn: (msg, ...args) => pinoLogger.warn(args, msg), + error: (msg, ...args) => pinoLogger.error(args, msg), +}; +``` +
+ + ### Runtime Compatibility -The SDK defaults to `node-fetch` but will use the global fetch client if present. The SDK works in the following -runtimes: + +The SDK works in the following runtimes: + + - Node.js 18+ - Vercel @@ -191,14 +267,4 @@ otherwise they would be overwritten upon the next generated release. Feel free t a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us! -On the other hand, contributions to the README are always very welcome! - -## Contributing - -While we value open-source contributions to this SDK, this library is generated programmatically. -Additions made directly to this library would have to be moved over to our generation code, -otherwise they would be overwritten upon the next generated release. Feel free to open a PR as -a proof of concept, but know that we will not be able to merge it as-is. We suggest opening -an issue first to discuss with us! - -On the other hand, contributions to the README are always very welcome! +On the other hand, contributions to the README are always very welcome! \ No newline at end of file diff --git a/biome.json b/biome.json new file mode 100644 index 00000000..a777468e --- /dev/null +++ b/biome.json @@ -0,0 +1,74 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.3.1/schema.json", + "root": true, + "vcs": { + "enabled": false + }, + "files": { + "ignoreUnknown": true, + "includes": [ + "**", + "!!dist", + "!!**/dist", + "!!lib", + "!!**/lib", + "!!_tmp_*", + "!!**/_tmp_*", + "!!*.tmp", + "!!**/*.tmp", + "!!.tmp/", + "!!**/.tmp/", + "!!*.log", + "!!**/*.log", + "!!**/.DS_Store", + "!!**/Thumbs.db" + ] + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 4, + "lineWidth": 120 + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + }, + "assist": { + "enabled": true, + "actions": { + "source": { + "organizeImports": "on" + } + } + }, + "linter": { + "rules": { + "style": { + "useNodejsImportProtocol": "off" + }, + "suspicious": { + "noAssignInExpressions": "warn", + "noUselessEscapeInString": { + "level": "warn", + "fix": "none", + "options": {} + }, + "noThenProperty": "warn", + "useIterableCallbackReturn": "warn", + "noShadowRestrictedNames": "warn", + "noTsIgnore": { + "level": "warn", + "fix": "none", + "options": {} + }, + "noConfusingVoidType": { + "level": "warn", + "fix": "none", + "options": {} + } + } + } + } +} diff --git a/jest.config.mjs b/jest.config.mjs deleted file mode 100644 index c7248211..00000000 --- a/jest.config.mjs +++ /dev/null @@ -1,8 +0,0 @@ -/** @type {import('jest').Config} */ -export default { - preset: "ts-jest", - testEnvironment: "node", - moduleNameMapper: { - "(.+)\.js$": "$1", - }, -}; diff --git a/package.json b/package.json index 00b818fa..5d739ad4 100644 --- a/package.json +++ b/package.json @@ -1,46 +1,68 @@ { "name": "intercom-client", - "version": "6.4.0", + "version": "7.0.0", "private": false, - "repository": "https://github.com/intercom/intercom-node", - "main": "./index.js", - "types": "./index.d.ts", - "scripts": { - "format": "prettier . --write --ignore-unknown", - "build": "tsc", - "prepack": "cp -rv dist/. .", - "test": "jest" + "repository": "github:intercom/intercom-node", + "type": "commonjs", + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.mjs", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "types": "./dist/cjs/index.d.ts", + "import": { + "types": "./dist/esm/index.d.mts", + "default": "./dist/esm/index.mjs" + }, + "require": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/cjs/index.js" + }, + "default": "./dist/cjs/index.js" + }, + "./package.json": "./package.json" }, - "dependencies": { - "url-join": "4.0.1", - "form-data": "^4.0.0", - "formdata-node": "^6.0.3", - "node-fetch": "^2.7.0", - "qs": "^6.13.1", - "readable-stream": "^4.5.2", - "js-base64": "3.7.7" + "files": [ + "dist", + "reference.md", + "README.md", + "LICENSE" + ], + "scripts": { + "format": "biome format --write --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "format:check": "biome format --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "lint": "biome lint --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "lint:fix": "biome lint --fix --unsafe --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "check": "biome check --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "check:fix": "biome check --fix --unsafe --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none", + "build": "pnpm build:cjs && pnpm build:esm", + "build:cjs": "tsc --project ./tsconfig.cjs.json", + "build:esm": "tsc --project ./tsconfig.esm.json && node scripts/rename-to-esm-files.js dist/esm", + "test": "vitest", + "test:unit": "vitest --project unit", + "test:wire": "vitest --project wire" }, + "dependencies": {}, "devDependencies": { - "@types/url-join": "4.0.1", - "@types/qs": "^6.9.17", - "@types/node-fetch": "^2.6.12", - "@types/readable-stream": "^4.0.18", "webpack": "^5.97.1", "ts-loader": "^9.5.1", - "jest": "^29.7.0", - "@types/jest": "^29.5.14", - "ts-jest": "^29.1.1", - "jest-environment-jsdom": "^29.7.0", + "vitest": "^3.2.4", + "msw": "2.11.2", "@types/node": "^18.19.70", - "prettier": "^3.4.2", - "typescript": "~5.7.2" + "typescript": "~5.7.2", + "@biomejs/biome": "2.3.1" }, "browser": { "fs": false, "os": false, - "path": false + "path": false, + "stream": false + }, + "packageManager": "pnpm@10.20.0", + "engines": { + "node": ">=18.0.0" }, - "packageManager": "yarn@1.22.22", + "sideEffects": false, "license": "Apache-2.0", "description": "Official Node bindings to the Intercom API", "homepage": "https://github.com/intercom/intercom-node", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 00000000..7a489b0d --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,2132 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@biomejs/biome': + specifier: 2.3.1 + version: 2.3.1 + '@types/node': + specifier: ^18.19.70 + version: 18.19.130 + msw: + specifier: 2.11.2 + version: 2.11.2(@types/node@18.19.130)(typescript@5.7.3) + ts-loader: + specifier: ^9.5.1 + version: 9.5.4(typescript@5.7.3)(webpack@5.103.0) + typescript: + specifier: ~5.7.2 + version: 5.7.3 + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/node@18.19.130)(msw@2.11.2(@types/node@18.19.130)(typescript@5.7.3))(terser@5.44.1) + webpack: + specifier: ^5.97.1 + version: 5.103.0 + +packages: + + '@biomejs/biome@2.3.1': + resolution: {integrity: sha512-A29evf1R72V5bo4o2EPxYMm5mtyGvzp2g+biZvRFx29nWebGyyeOSsDWGx3tuNNMFRepGwxmA9ZQ15mzfabK2w==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-darwin-arm64@2.3.1': + resolution: {integrity: sha512-ombSf3MnTUueiYGN1SeI9tBCsDUhpWzOwS63Dove42osNh0PfE1cUtHFx6eZ1+MYCCLwXzlFlYFdrJ+U7h6LcA==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.3.1': + resolution: {integrity: sha512-pcOfwyoQkrkbGvXxRvZNe5qgD797IowpJPovPX5biPk2FwMEV+INZqfCaz4G5bVq9hYnjwhRMamg11U4QsRXrQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@2.3.1': + resolution: {integrity: sha512-+DZYv8l7FlUtTrWs1Tdt1KcNCAmRO87PyOnxKGunbWm5HKg1oZBSbIIPkjrCtDZaeqSG1DiGx7qF+CPsquQRcg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + + '@biomejs/cli-linux-arm64@2.3.1': + resolution: {integrity: sha512-td5O8pFIgLs8H1sAZsD6v+5quODihyEw4nv2R8z7swUfIK1FKk+15e4eiYVLcAE4jUqngvh4j3JCNgg0Y4o4IQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + + '@biomejs/cli-linux-x64-musl@2.3.1': + resolution: {integrity: sha512-Y3Ob4nqgv38Mh+6EGHltuN+Cq8aj/gyMTJYzkFZV2AEj+9XzoXB9VNljz9pjfFNHUxvLEV4b55VWyxozQTBaUQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + + '@biomejs/cli-linux-x64@2.3.1': + resolution: {integrity: sha512-PYWgEO7up7XYwSAArOpzsVCiqxBCXy53gsReAb1kKYIyXaoAlhBaBMvxR/k2Rm9aTuZ662locXUmPk/Aj+Xu+Q==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + + '@biomejs/cli-win32-arm64@2.3.1': + resolution: {integrity: sha512-RHIG/zgo+69idUqVvV3n8+j58dKYABRpMyDmfWu2TITC+jwGPiEaT0Q3RKD+kQHiS80mpBrST0iUGeEXT0bU9A==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@2.3.1': + resolution: {integrity: sha512-izl30JJ5Dp10mi90Eko47zhxE6pYyWPcnX1NQxKpL/yMhXxf95oLTzfpu4q+MDBh/gemNqyJEwjBpe0MT5iWPA==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + + '@bundled-es-modules/cookie@2.0.1': + resolution: {integrity: sha512-8o+5fRPLNbjbdGRRmJj3h6Hh1AQJf2dk3qQ/5ZFb+PXkRNiSoMGGUKlsgLfrxneb72axVJyIYji64E2+nNfYyw==} + + '@bundled-es-modules/statuses@1.0.1': + resolution: {integrity: sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg==} + + '@esbuild/aix-ppc64@0.25.12': + resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.25.12': + resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.25.12': + resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.25.12': + resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.25.12': + resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.25.12': + resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.25.12': + resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.25.12': + resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.25.12': + resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.25.12': + resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.25.12': + resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.25.12': + resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.25.12': + resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.25.12': + resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.25.12': + resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.25.12': + resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.25.12': + resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.25.12': + resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.25.12': + resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.25.12': + resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.25.12': + resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.25.12': + resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.25.12': + resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.25.12': + resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.25.12': + resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.25.12': + resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@inquirer/ansi@1.0.2': + resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==} + engines: {node: '>=18'} + + '@inquirer/confirm@5.1.21': + resolution: {integrity: sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==} + engines: {node: '>=18'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/core@10.3.2': + resolution: {integrity: sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==} + engines: {node: '>=18'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/figures@1.0.15': + resolution: {integrity: sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==} + engines: {node: '>=18'} + + '@inquirer/type@3.0.10': + resolution: {integrity: sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==} + engines: {node: '>=18'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/source-map@0.3.11': + resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@mswjs/interceptors@0.39.8': + resolution: {integrity: sha512-2+BzZbjRO7Ct61k8fMNHEtoKjeWI9pIlHFTqBwZ5icHpqszIgEZbjb1MW5Z0+bITTCTl3gk4PDBxs9tA/csXvA==} + engines: {node: '>=18'} + + '@open-draft/deferred-promise@2.2.0': + resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==} + + '@open-draft/logger@0.3.0': + resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==} + + '@open-draft/until@2.1.0': + resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==} + + '@rollup/rollup-android-arm-eabi@4.53.3': + resolution: {integrity: sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.53.3': + resolution: {integrity: sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.53.3': + resolution: {integrity: sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.53.3': + resolution: {integrity: sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.53.3': + resolution: {integrity: sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.53.3': + resolution: {integrity: sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.53.3': + resolution: {integrity: sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.53.3': + resolution: {integrity: sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.53.3': + resolution: {integrity: sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.53.3': + resolution: {integrity: sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.53.3': + resolution: {integrity: sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.53.3': + resolution: {integrity: sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.53.3': + resolution: {integrity: sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.53.3': + resolution: {integrity: sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.53.3': + resolution: {integrity: sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.53.3': + resolution: {integrity: sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.53.3': + resolution: {integrity: sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openharmony-arm64@4.53.3': + resolution: {integrity: sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.53.3': + resolution: {integrity: sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.53.3': + resolution: {integrity: sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.53.3': + resolution: {integrity: sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.53.3': + resolution: {integrity: sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==} + cpu: [x64] + os: [win32] + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/cookie@0.6.0': + resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/eslint-scope@3.7.7': + resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==} + + '@types/eslint@9.6.1': + resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==} + + '@types/estree@1.0.8': + resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/node@18.19.130': + resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==} + + '@types/statuses@2.0.6': + resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==} + + '@vitest/expect@3.2.4': + resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==} + + '@vitest/mocker@3.2.4': + resolution: {integrity: sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.4': + resolution: {integrity: sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==} + + '@vitest/runner@3.2.4': + resolution: {integrity: sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==} + + '@vitest/snapshot@3.2.4': + resolution: {integrity: sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==} + + '@vitest/spy@3.2.4': + resolution: {integrity: sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==} + + '@vitest/utils@3.2.4': + resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==} + + '@webassemblyjs/ast@1.14.1': + resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==} + + '@webassemblyjs/floating-point-hex-parser@1.13.2': + resolution: {integrity: sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==} + + '@webassemblyjs/helper-api-error@1.13.2': + resolution: {integrity: sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==} + + '@webassemblyjs/helper-buffer@1.14.1': + resolution: {integrity: sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==} + + '@webassemblyjs/helper-numbers@1.13.2': + resolution: {integrity: sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==} + + '@webassemblyjs/helper-wasm-bytecode@1.13.2': + resolution: {integrity: sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==} + + '@webassemblyjs/helper-wasm-section@1.14.1': + resolution: {integrity: sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==} + + '@webassemblyjs/ieee754@1.13.2': + resolution: {integrity: sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==} + + '@webassemblyjs/leb128@1.13.2': + resolution: {integrity: sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==} + + '@webassemblyjs/utf8@1.13.2': + resolution: {integrity: sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==} + + '@webassemblyjs/wasm-edit@1.14.1': + resolution: {integrity: sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==} + + '@webassemblyjs/wasm-gen@1.14.1': + resolution: {integrity: sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==} + + '@webassemblyjs/wasm-opt@1.14.1': + resolution: {integrity: sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==} + + '@webassemblyjs/wasm-parser@1.14.1': + resolution: {integrity: sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==} + + '@webassemblyjs/wast-printer@1.14.1': + resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==} + + '@xtuc/ieee754@1.2.0': + resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} + + '@xtuc/long@4.2.2': + resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==} + + acorn-import-phases@1.0.4: + resolution: {integrity: sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==} + engines: {node: '>=10.13.0'} + peerDependencies: + acorn: ^8.14.0 + + acorn@8.15.0: + resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv-keywords@5.1.0: + resolution: {integrity: sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==} + peerDependencies: + ajv: ^8.8.2 + + ajv@8.17.1: + resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + baseline-browser-mapping@2.8.32: + resolution: {integrity: sha512-OPz5aBThlyLFgxyhdwf/s2+8ab3OvT7AdTNvKHBwpXomIYeXqpUUuT8LrdtxZSsWJ4R4CU1un4XGh5Ez3nlTpw==} + hasBin: true + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.28.0: + resolution: {integrity: sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + caniuse-lite@1.0.30001757: + resolution: {integrity: sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + check-error@2.1.1: + resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==} + engines: {node: '>= 16'} + + chrome-trace-event@1.0.4: + resolution: {integrity: sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==} + engines: {node: '>=6.0'} + + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + commander@2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + electron-to-chromium@1.5.263: + resolution: {integrity: sha512-DrqJ11Knd+lo+dv+lltvfMDLU27g14LMdH2b0O3Pio4uk0x+z7OR+JrmyacTPN2M8w3BrZ7/RTwG3R9B7irPlg==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + enhanced-resolve@5.18.3: + resolution: {integrity: sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==} + engines: {node: '>=10.13.0'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.25.12: + resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + eslint-scope@5.1.1: + resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} + engines: {node: '>=8.0.0'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@4.3.0: + resolution: {integrity: sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + events@3.3.0: + resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} + engines: {node: '>=0.8.x'} + + expect-type@1.2.2: + resolution: {integrity: sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==} + engines: {node: '>=12.0.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-uri@3.1.0: + resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + glob-to-regexp@0.4.1: + resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + graphql@16.12.0: + resolution: {integrity: sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ==} + engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + headers-polyfill@4.0.3: + resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-node-process@1.2.0: + resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + jest-worker@27.5.1: + resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==} + engines: {node: '>= 10.13.0'} + + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + json-parse-even-better-errors@2.3.1: + resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + loader-runner@4.3.1: + resolution: {integrity: sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==} + engines: {node: '>=6.11.5'} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + merge-stream@2.0.0: + resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + msw@2.11.2: + resolution: {integrity: sha512-MI54hLCsrMwiflkcqlgYYNJJddY5/+S0SnONvhv1owOplvqohKSQyGejpNdUGyCwgs4IH7PqaNbPw/sKOEze9Q==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + typescript: '>= 4.8.x' + peerDependenciesMeta: + typescript: + optional: true + + mute-stream@2.0.0: + resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==} + engines: {node: ^18.17.0 || >=20.5.0} + + nanoid@3.3.11: + resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + neo-async@2.6.2: + resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} + + node-releases@2.0.27: + resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==} + + outvariant@1.4.3: + resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==} + + path-to-regexp@6.3.0: + resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.1: + resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} + engines: {node: '>=8.6'} + + picomatch@4.0.3: + resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==} + engines: {node: '>=12'} + + postcss@8.5.6: + resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} + engines: {node: ^10 || ^12 || >=14} + + randombytes@2.1.0: + resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} + + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + rettime@0.7.0: + resolution: {integrity: sha512-LPRKoHnLKd/r3dVxcwO7vhCW+orkOGj9ViueosEBK6ie89CijnfRlhaDhHq/3Hxu4CkWQtxwlBG0mzTQY6uQjw==} + + rollup@4.53.3: + resolution: {integrity: sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + schema-utils@4.3.3: + resolution: {integrity: sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==} + engines: {node: '>= 10.13.0'} + + semver@7.7.3: + resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==} + engines: {node: '>=10'} + hasBin: true + + serialize-javascript@6.0.2: + resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + strict-event-emitter@0.5.1: + resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-literal@3.1.0: + resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-color@8.1.1: + resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} + engines: {node: '>=10'} + + tapable@2.3.0: + resolution: {integrity: sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==} + engines: {node: '>=6'} + + terser-webpack-plugin@5.3.14: + resolution: {integrity: sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==} + engines: {node: '>= 10.13.0'} + peerDependencies: + '@swc/core': '*' + esbuild: '*' + uglify-js: '*' + webpack: ^5.1.0 + peerDependenciesMeta: + '@swc/core': + optional: true + esbuild: + optional: true + uglify-js: + optional: true + + terser@5.44.1: + resolution: {integrity: sha512-t/R3R/n0MSwnnazuPpPNVO60LX0SKL45pyl9YlvxIdkH0Of7D5qM2EVe+yASRIlY5pZ73nclYJfNANGWPwFDZw==} + engines: {node: '>=10'} + hasBin: true + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.15: + resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.4: + resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==} + engines: {node: '>=14.0.0'} + + tldts-core@7.0.19: + resolution: {integrity: sha512-lJX2dEWx0SGH4O6p+7FPwYmJ/bu1JbcGJ8RLaG9b7liIgZ85itUVEPbMtWRVrde/0fnDPEPHW10ZsKW3kVsE9A==} + + tldts@7.0.19: + resolution: {integrity: sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==} + hasBin: true + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tough-cookie@6.0.0: + resolution: {integrity: sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==} + engines: {node: '>=16'} + + ts-loader@9.5.4: + resolution: {integrity: sha512-nCz0rEwunlTZiy6rXFByQU1kVVpCIgUpc/psFiKVrUwrizdnIbRFu8w7bxhUF0X613DYwT4XzrZHpVyMe758hQ==} + engines: {node: '>=12.0.0'} + peerDependencies: + typescript: '*' + webpack: ^5.0.0 + + type-fest@4.41.0: + resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==} + engines: {node: '>=16'} + + typescript@5.7.3: + resolution: {integrity: sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@5.26.5: + resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} + + update-browserslist-db@1.1.4: + resolution: {integrity: sha512-q0SPT4xyU84saUX+tomz1WLkxUbuaJnR1xWt17M7fJtEJigJeWUNGUqrauFXsHnqev9y9JTRGwk13tFBuKby4A==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + + vite@7.2.6: + resolution: {integrity: sha512-tI2l/nFHC5rLh7+5+o7QjKjSR04ivXDF4jcgV0f/bTQ+OJiITy5S6gaynVsEM+7RqzufMnVbIon6Sr5x1SDYaQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@3.2.4: + resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.4 + '@vitest/ui': 3.2.4 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + watchpack@2.4.4: + resolution: {integrity: sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA==} + engines: {node: '>=10.13.0'} + + webpack-sources@3.3.3: + resolution: {integrity: sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg==} + engines: {node: '>=10.13.0'} + + webpack@5.103.0: + resolution: {integrity: sha512-HU1JOuV1OavsZ+mfigY0j8d1TgQgbZ6M+J75zDkpEAwYeXjWSqrGJtgnPblJjd/mAyTNQ7ygw0MiKOn6etz8yw==} + engines: {node: '>=10.13.0'} + hasBin: true + peerDependencies: + webpack-cli: '*' + peerDependenciesMeta: + webpack-cli: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wrap-ansi@6.2.0: + resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} + engines: {node: '>=8'} + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.2: + resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} + engines: {node: '>=12'} + + yoctocolors-cjs@2.1.3: + resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==} + engines: {node: '>=18'} + +snapshots: + + '@biomejs/biome@2.3.1': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 2.3.1 + '@biomejs/cli-darwin-x64': 2.3.1 + '@biomejs/cli-linux-arm64': 2.3.1 + '@biomejs/cli-linux-arm64-musl': 2.3.1 + '@biomejs/cli-linux-x64': 2.3.1 + '@biomejs/cli-linux-x64-musl': 2.3.1 + '@biomejs/cli-win32-arm64': 2.3.1 + '@biomejs/cli-win32-x64': 2.3.1 + + '@biomejs/cli-darwin-arm64@2.3.1': + optional: true + + '@biomejs/cli-darwin-x64@2.3.1': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.3.1': + optional: true + + '@biomejs/cli-linux-arm64@2.3.1': + optional: true + + '@biomejs/cli-linux-x64-musl@2.3.1': + optional: true + + '@biomejs/cli-linux-x64@2.3.1': + optional: true + + '@biomejs/cli-win32-arm64@2.3.1': + optional: true + + '@biomejs/cli-win32-x64@2.3.1': + optional: true + + '@bundled-es-modules/cookie@2.0.1': + dependencies: + cookie: 0.7.2 + + '@bundled-es-modules/statuses@1.0.1': + dependencies: + statuses: 2.0.2 + + '@esbuild/aix-ppc64@0.25.12': + optional: true + + '@esbuild/android-arm64@0.25.12': + optional: true + + '@esbuild/android-arm@0.25.12': + optional: true + + '@esbuild/android-x64@0.25.12': + optional: true + + '@esbuild/darwin-arm64@0.25.12': + optional: true + + '@esbuild/darwin-x64@0.25.12': + optional: true + + '@esbuild/freebsd-arm64@0.25.12': + optional: true + + '@esbuild/freebsd-x64@0.25.12': + optional: true + + '@esbuild/linux-arm64@0.25.12': + optional: true + + '@esbuild/linux-arm@0.25.12': + optional: true + + '@esbuild/linux-ia32@0.25.12': + optional: true + + '@esbuild/linux-loong64@0.25.12': + optional: true + + '@esbuild/linux-mips64el@0.25.12': + optional: true + + '@esbuild/linux-ppc64@0.25.12': + optional: true + + '@esbuild/linux-riscv64@0.25.12': + optional: true + + '@esbuild/linux-s390x@0.25.12': + optional: true + + '@esbuild/linux-x64@0.25.12': + optional: true + + '@esbuild/netbsd-arm64@0.25.12': + optional: true + + '@esbuild/netbsd-x64@0.25.12': + optional: true + + '@esbuild/openbsd-arm64@0.25.12': + optional: true + + '@esbuild/openbsd-x64@0.25.12': + optional: true + + '@esbuild/openharmony-arm64@0.25.12': + optional: true + + '@esbuild/sunos-x64@0.25.12': + optional: true + + '@esbuild/win32-arm64@0.25.12': + optional: true + + '@esbuild/win32-ia32@0.25.12': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true + + '@inquirer/ansi@1.0.2': {} + + '@inquirer/confirm@5.1.21(@types/node@18.19.130)': + dependencies: + '@inquirer/core': 10.3.2(@types/node@18.19.130) + '@inquirer/type': 3.0.10(@types/node@18.19.130) + optionalDependencies: + '@types/node': 18.19.130 + + '@inquirer/core@10.3.2(@types/node@18.19.130)': + dependencies: + '@inquirer/ansi': 1.0.2 + '@inquirer/figures': 1.0.15 + '@inquirer/type': 3.0.10(@types/node@18.19.130) + cli-width: 4.1.0 + mute-stream: 2.0.0 + signal-exit: 4.1.0 + wrap-ansi: 6.2.0 + yoctocolors-cjs: 2.1.3 + optionalDependencies: + '@types/node': 18.19.130 + + '@inquirer/figures@1.0.15': {} + + '@inquirer/type@3.0.10(@types/node@18.19.130)': + optionalDependencies: + '@types/node': 18.19.130 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/source-map@0.3.11': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@mswjs/interceptors@0.39.8': + dependencies: + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/logger': 0.3.0 + '@open-draft/until': 2.1.0 + is-node-process: 1.2.0 + outvariant: 1.4.3 + strict-event-emitter: 0.5.1 + + '@open-draft/deferred-promise@2.2.0': {} + + '@open-draft/logger@0.3.0': + dependencies: + is-node-process: 1.2.0 + outvariant: 1.4.3 + + '@open-draft/until@2.1.0': {} + + '@rollup/rollup-android-arm-eabi@4.53.3': + optional: true + + '@rollup/rollup-android-arm64@4.53.3': + optional: true + + '@rollup/rollup-darwin-arm64@4.53.3': + optional: true + + '@rollup/rollup-darwin-x64@4.53.3': + optional: true + + '@rollup/rollup-freebsd-arm64@4.53.3': + optional: true + + '@rollup/rollup-freebsd-x64@4.53.3': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.53.3': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.53.3': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.53.3': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.53.3': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.53.3': + optional: true + + '@rollup/rollup-linux-x64-musl@4.53.3': + optional: true + + '@rollup/rollup-openharmony-arm64@4.53.3': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.53.3': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.53.3': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.53.3': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.53.3': + optional: true + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/cookie@0.6.0': {} + + '@types/deep-eql@4.0.2': {} + + '@types/eslint-scope@3.7.7': + dependencies: + '@types/eslint': 9.6.1 + '@types/estree': 1.0.8 + + '@types/eslint@9.6.1': + dependencies: + '@types/estree': 1.0.8 + '@types/json-schema': 7.0.15 + + '@types/estree@1.0.8': {} + + '@types/json-schema@7.0.15': {} + + '@types/node@18.19.130': + dependencies: + undici-types: 5.26.5 + + '@types/statuses@2.0.6': {} + + '@vitest/expect@3.2.4': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.4 + '@vitest/utils': 3.2.4 + chai: 5.3.3 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.4(msw@2.11.2(@types/node@18.19.130)(typescript@5.7.3))(vite@7.2.6(@types/node@18.19.130)(terser@5.44.1))': + dependencies: + '@vitest/spy': 3.2.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + msw: 2.11.2(@types/node@18.19.130)(typescript@5.7.3) + vite: 7.2.6(@types/node@18.19.130)(terser@5.44.1) + + '@vitest/pretty-format@3.2.4': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.4': + dependencies: + '@vitest/utils': 3.2.4 + pathe: 2.0.3 + strip-literal: 3.1.0 + + '@vitest/snapshot@3.2.4': + dependencies: + '@vitest/pretty-format': 3.2.4 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.4': + dependencies: + tinyspy: 4.0.4 + + '@vitest/utils@3.2.4': + dependencies: + '@vitest/pretty-format': 3.2.4 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + + '@webassemblyjs/ast@1.14.1': + dependencies: + '@webassemblyjs/helper-numbers': 1.13.2 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + + '@webassemblyjs/floating-point-hex-parser@1.13.2': {} + + '@webassemblyjs/helper-api-error@1.13.2': {} + + '@webassemblyjs/helper-buffer@1.14.1': {} + + '@webassemblyjs/helper-numbers@1.13.2': + dependencies: + '@webassemblyjs/floating-point-hex-parser': 1.13.2 + '@webassemblyjs/helper-api-error': 1.13.2 + '@xtuc/long': 4.2.2 + + '@webassemblyjs/helper-wasm-bytecode@1.13.2': {} + + '@webassemblyjs/helper-wasm-section@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/wasm-gen': 1.14.1 + + '@webassemblyjs/ieee754@1.13.2': + dependencies: + '@xtuc/ieee754': 1.2.0 + + '@webassemblyjs/leb128@1.13.2': + dependencies: + '@xtuc/long': 4.2.2 + + '@webassemblyjs/utf8@1.13.2': {} + + '@webassemblyjs/wasm-edit@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/helper-wasm-section': 1.14.1 + '@webassemblyjs/wasm-gen': 1.14.1 + '@webassemblyjs/wasm-opt': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + '@webassemblyjs/wast-printer': 1.14.1 + + '@webassemblyjs/wasm-gen@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/ieee754': 1.13.2 + '@webassemblyjs/leb128': 1.13.2 + '@webassemblyjs/utf8': 1.13.2 + + '@webassemblyjs/wasm-opt@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/wasm-gen': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + + '@webassemblyjs/wasm-parser@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-api-error': 1.13.2 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/ieee754': 1.13.2 + '@webassemblyjs/leb128': 1.13.2 + '@webassemblyjs/utf8': 1.13.2 + + '@webassemblyjs/wast-printer@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@xtuc/long': 4.2.2 + + '@xtuc/ieee754@1.2.0': {} + + '@xtuc/long@4.2.2': {} + + acorn-import-phases@1.0.4(acorn@8.15.0): + dependencies: + acorn: 8.15.0 + + acorn@8.15.0: {} + + ajv-formats@2.1.1(ajv@8.17.1): + optionalDependencies: + ajv: 8.17.1 + + ajv-keywords@5.1.0(ajv@8.17.1): + dependencies: + ajv: 8.17.1 + fast-deep-equal: 3.1.3 + + ajv@8.17.1: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.0 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + assertion-error@2.0.1: {} + + baseline-browser-mapping@2.8.32: {} + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.28.0: + dependencies: + baseline-browser-mapping: 2.8.32 + caniuse-lite: 1.0.30001757 + electron-to-chromium: 1.5.263 + node-releases: 2.0.27 + update-browserslist-db: 1.1.4(browserslist@4.28.0) + + buffer-from@1.1.2: {} + + cac@6.7.14: {} + + caniuse-lite@1.0.30001757: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.1 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + check-error@2.1.1: {} + + chrome-trace-event@1.0.4: {} + + cli-width@4.1.0: {} + + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + commander@2.20.3: {} + + cookie@0.7.2: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-eql@5.0.2: {} + + electron-to-chromium@1.5.263: {} + + emoji-regex@8.0.0: {} + + enhanced-resolve@5.18.3: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.0 + + es-module-lexer@1.7.0: {} + + esbuild@0.25.12: + optionalDependencies: + '@esbuild/aix-ppc64': 0.25.12 + '@esbuild/android-arm': 0.25.12 + '@esbuild/android-arm64': 0.25.12 + '@esbuild/android-x64': 0.25.12 + '@esbuild/darwin-arm64': 0.25.12 + '@esbuild/darwin-x64': 0.25.12 + '@esbuild/freebsd-arm64': 0.25.12 + '@esbuild/freebsd-x64': 0.25.12 + '@esbuild/linux-arm': 0.25.12 + '@esbuild/linux-arm64': 0.25.12 + '@esbuild/linux-ia32': 0.25.12 + '@esbuild/linux-loong64': 0.25.12 + '@esbuild/linux-mips64el': 0.25.12 + '@esbuild/linux-ppc64': 0.25.12 + '@esbuild/linux-riscv64': 0.25.12 + '@esbuild/linux-s390x': 0.25.12 + '@esbuild/linux-x64': 0.25.12 + '@esbuild/netbsd-arm64': 0.25.12 + '@esbuild/netbsd-x64': 0.25.12 + '@esbuild/openbsd-arm64': 0.25.12 + '@esbuild/openbsd-x64': 0.25.12 + '@esbuild/openharmony-arm64': 0.25.12 + '@esbuild/sunos-x64': 0.25.12 + '@esbuild/win32-arm64': 0.25.12 + '@esbuild/win32-ia32': 0.25.12 + '@esbuild/win32-x64': 0.25.12 + + escalade@3.2.0: {} + + eslint-scope@5.1.1: + dependencies: + esrecurse: 4.3.0 + estraverse: 4.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@4.3.0: {} + + estraverse@5.3.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.8 + + events@3.3.0: {} + + expect-type@1.2.2: {} + + fast-deep-equal@3.1.3: {} + + fast-uri@3.1.0: {} + + fdir@6.5.0(picomatch@4.0.3): + optionalDependencies: + picomatch: 4.0.3 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + fsevents@2.3.3: + optional: true + + get-caller-file@2.0.5: {} + + glob-to-regexp@0.4.1: {} + + graceful-fs@4.2.11: {} + + graphql@16.12.0: {} + + has-flag@4.0.0: {} + + headers-polyfill@4.0.3: {} + + is-fullwidth-code-point@3.0.0: {} + + is-node-process@1.2.0: {} + + is-number@7.0.0: {} + + jest-worker@27.5.1: + dependencies: + '@types/node': 18.19.130 + merge-stream: 2.0.0 + supports-color: 8.1.1 + + js-tokens@9.0.1: {} + + json-parse-even-better-errors@2.3.1: {} + + json-schema-traverse@1.0.0: {} + + loader-runner@4.3.1: {} + + loupe@3.2.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + merge-stream@2.0.0: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.1 + + mime-db@1.52.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + ms@2.1.3: {} + + msw@2.11.2(@types/node@18.19.130)(typescript@5.7.3): + dependencies: + '@bundled-es-modules/cookie': 2.0.1 + '@bundled-es-modules/statuses': 1.0.1 + '@inquirer/confirm': 5.1.21(@types/node@18.19.130) + '@mswjs/interceptors': 0.39.8 + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/until': 2.1.0 + '@types/cookie': 0.6.0 + '@types/statuses': 2.0.6 + graphql: 16.12.0 + headers-polyfill: 4.0.3 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + picocolors: 1.1.1 + rettime: 0.7.0 + strict-event-emitter: 0.5.1 + tough-cookie: 6.0.0 + type-fest: 4.41.0 + yargs: 17.7.2 + optionalDependencies: + typescript: 5.7.3 + transitivePeerDependencies: + - '@types/node' + + mute-stream@2.0.0: {} + + nanoid@3.3.11: {} + + neo-async@2.6.2: {} + + node-releases@2.0.27: {} + + outvariant@1.4.3: {} + + path-to-regexp@6.3.0: {} + + pathe@2.0.3: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + picomatch@2.3.1: {} + + picomatch@4.0.3: {} + + postcss@8.5.6: + dependencies: + nanoid: 3.3.11 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + randombytes@2.1.0: + dependencies: + safe-buffer: 5.2.1 + + require-directory@2.1.1: {} + + require-from-string@2.0.2: {} + + rettime@0.7.0: {} + + rollup@4.53.3: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.53.3 + '@rollup/rollup-android-arm64': 4.53.3 + '@rollup/rollup-darwin-arm64': 4.53.3 + '@rollup/rollup-darwin-x64': 4.53.3 + '@rollup/rollup-freebsd-arm64': 4.53.3 + '@rollup/rollup-freebsd-x64': 4.53.3 + '@rollup/rollup-linux-arm-gnueabihf': 4.53.3 + '@rollup/rollup-linux-arm-musleabihf': 4.53.3 + '@rollup/rollup-linux-arm64-gnu': 4.53.3 + '@rollup/rollup-linux-arm64-musl': 4.53.3 + '@rollup/rollup-linux-loong64-gnu': 4.53.3 + '@rollup/rollup-linux-ppc64-gnu': 4.53.3 + '@rollup/rollup-linux-riscv64-gnu': 4.53.3 + '@rollup/rollup-linux-riscv64-musl': 4.53.3 + '@rollup/rollup-linux-s390x-gnu': 4.53.3 + '@rollup/rollup-linux-x64-gnu': 4.53.3 + '@rollup/rollup-linux-x64-musl': 4.53.3 + '@rollup/rollup-openharmony-arm64': 4.53.3 + '@rollup/rollup-win32-arm64-msvc': 4.53.3 + '@rollup/rollup-win32-ia32-msvc': 4.53.3 + '@rollup/rollup-win32-x64-gnu': 4.53.3 + '@rollup/rollup-win32-x64-msvc': 4.53.3 + fsevents: 2.3.3 + + safe-buffer@5.2.1: {} + + schema-utils@4.3.3: + dependencies: + '@types/json-schema': 7.0.15 + ajv: 8.17.1 + ajv-formats: 2.1.1(ajv@8.17.1) + ajv-keywords: 5.1.0(ajv@8.17.1) + + semver@7.7.3: {} + + serialize-javascript@6.0.2: + dependencies: + randombytes: 2.1.0 + + siginfo@2.0.0: {} + + signal-exit@4.1.0: {} + + source-map-js@1.2.1: {} + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + source-map@0.7.6: {} + + stackback@0.0.2: {} + + statuses@2.0.2: {} + + std-env@3.10.0: {} + + strict-event-emitter@0.5.1: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-literal@3.1.0: + dependencies: + js-tokens: 9.0.1 + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-color@8.1.1: + dependencies: + has-flag: 4.0.0 + + tapable@2.3.0: {} + + terser-webpack-plugin@5.3.14(webpack@5.103.0): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + jest-worker: 27.5.1 + schema-utils: 4.3.3 + serialize-javascript: 6.0.2 + terser: 5.44.1 + webpack: 5.103.0 + + terser@5.44.1: + dependencies: + '@jridgewell/source-map': 0.3.11 + acorn: 8.15.0 + commander: 2.20.3 + source-map-support: 0.5.21 + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyglobby@0.2.15: + dependencies: + fdir: 6.5.0(picomatch@4.0.3) + picomatch: 4.0.3 + + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.4: {} + + tldts-core@7.0.19: {} + + tldts@7.0.19: + dependencies: + tldts-core: 7.0.19 + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tough-cookie@6.0.0: + dependencies: + tldts: 7.0.19 + + ts-loader@9.5.4(typescript@5.7.3)(webpack@5.103.0): + dependencies: + chalk: 4.1.2 + enhanced-resolve: 5.18.3 + micromatch: 4.0.8 + semver: 7.7.3 + source-map: 0.7.6 + typescript: 5.7.3 + webpack: 5.103.0 + + type-fest@4.41.0: {} + + typescript@5.7.3: {} + + undici-types@5.26.5: {} + + update-browserslist-db@1.1.4(browserslist@4.28.0): + dependencies: + browserslist: 4.28.0 + escalade: 3.2.0 + picocolors: 1.1.1 + + vite-node@3.2.4(@types/node@18.19.130)(terser@5.44.1): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 7.2.6(@types/node@18.19.130)(terser@5.44.1) + transitivePeerDependencies: + - '@types/node' + - jiti + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vite@7.2.6(@types/node@18.19.130)(terser@5.44.1): + dependencies: + esbuild: 0.25.12 + fdir: 6.5.0(picomatch@4.0.3) + picomatch: 4.0.3 + postcss: 8.5.6 + rollup: 4.53.3 + tinyglobby: 0.2.15 + optionalDependencies: + '@types/node': 18.19.130 + fsevents: 2.3.3 + terser: 5.44.1 + + vitest@3.2.4(@types/node@18.19.130)(msw@2.11.2(@types/node@18.19.130)(typescript@5.7.3))(terser@5.44.1): + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.4 + '@vitest/mocker': 3.2.4(msw@2.11.2(@types/node@18.19.130)(typescript@5.7.3))(vite@7.2.6(@types/node@18.19.130)(terser@5.44.1)) + '@vitest/pretty-format': 3.2.4 + '@vitest/runner': 3.2.4 + '@vitest/snapshot': 3.2.4 + '@vitest/spy': 3.2.4 + '@vitest/utils': 3.2.4 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.2.2 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.3 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.15 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 7.2.6(@types/node@18.19.130)(terser@5.44.1) + vite-node: 3.2.4(@types/node@18.19.130)(terser@5.44.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 18.19.130 + transitivePeerDependencies: + - jiti + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + watchpack@2.4.4: + dependencies: + glob-to-regexp: 0.4.1 + graceful-fs: 4.2.11 + + webpack-sources@3.3.3: {} + + webpack@5.103.0: + dependencies: + '@types/eslint-scope': 3.7.7 + '@types/estree': 1.0.8 + '@types/json-schema': 7.0.15 + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/wasm-edit': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + acorn: 8.15.0 + acorn-import-phases: 1.0.4(acorn@8.15.0) + browserslist: 4.28.0 + chrome-trace-event: 1.0.4 + enhanced-resolve: 5.18.3 + es-module-lexer: 1.7.0 + eslint-scope: 5.1.1 + events: 3.3.0 + glob-to-regexp: 0.4.1 + graceful-fs: 4.2.11 + json-parse-even-better-errors: 2.3.1 + loader-runner: 4.3.1 + mime-types: 2.1.35 + neo-async: 2.6.2 + schema-utils: 4.3.3 + tapable: 2.3.0 + terser-webpack-plugin: 5.3.14(webpack@5.103.0) + watchpack: 2.4.4 + webpack-sources: 3.3.3 + transitivePeerDependencies: + - '@swc/core' + - esbuild + - uglify-js + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wrap-ansi@6.2.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + y18n@5.0.8: {} + + yargs-parser@21.1.1: {} + + yargs@17.7.2: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + + yoctocolors-cjs@2.1.3: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 00000000..6e4c3951 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1 @@ +packages: ['.'] \ No newline at end of file diff --git a/reference.md b/reference.md index df65e9f7..5b2306ab 100644 --- a/reference.md +++ b/reference.md @@ -1,8 +1,6 @@ # Reference - ## Admins - -
client.admins.identify() -> Intercom.AdminWithApp +
client.admins.identify() -> Intercom.AdminWithApp | undefined
@@ -14,12 +12,12 @@
+ You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). > 🚧 Single Sign On > > If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk. -
@@ -35,8 +33,8 @@ You can view the currently authorised admin along with the embedded app object ( ```typescript await client.admins.identify(); -``` +```
@@ -50,18 +48,19 @@ await client.admins.identify();
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-
client.admins.away({ ...params }) -> Intercom.Admin +
client.admins.away({ ...params }) -> Intercom.Admin | undefined
@@ -74,7 +73,6 @@ await client.admins.identify();
You can set an Admin as away for the Inbox. -
@@ -90,12 +88,13 @@ You can set an Admin as away for the Inbox. ```typescript await client.admins.away({ - admin_id: "admin_id", + admin_id: 1, away_mode_enabled: true, away_mode_reassign: true, + away_status_reason_id: 12345 }); -``` +``` @@ -109,21 +108,22 @@ await client.admins.away({
-**request:** `Intercom.ConfigureAwayAdminRequest` - +**request:** `Intercom.ConfigureAwayAdminRequest` +
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
@@ -141,7 +141,6 @@ await client.admins.away({
You can get a log of activities by all admins in an app. -
@@ -158,10 +157,10 @@ You can get a log of activities by all admins in an app. ```typescript await client.admins.listAllActivityLogs({ created_at_after: "1677253093", - created_at_before: "1677861493", + created_at_before: "1677861493" }); -``` +``` @@ -175,21 +174,22 @@ await client.admins.listAllActivityLogs({
-**request:** `Intercom.ListAllActivityLogsRequest` - +**request:** `Intercom.ListAllActivityLogsRequest` +
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
@@ -207,7 +207,6 @@ await client.admins.listAllActivityLogs({
You can fetch a list of admins for a given workspace. -
@@ -223,8 +222,8 @@ You can fetch a list of admins for a given workspace. ```typescript await client.admins.list(); -``` +``` @@ -238,18 +237,19 @@ await client.admins.list();
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-
client.admins.find({ ...params }) -> Intercom.Admin +
client.admins.find({ ...params }) -> Intercom.Admin | undefined
@@ -262,7 +262,6 @@ await client.admins.list();
You can retrieve the details of a single admin. -
@@ -278,10 +277,10 @@ You can retrieve the details of a single admin. ```typescript await client.admins.find({ - admin_id: "123", + admin_id: 1 }); -``` +``` @@ -295,28 +294,28 @@ await client.admins.find({
-**request:** `Intercom.FindAdminRequest` - +**request:** `Intercom.FindAdminRequest` +
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-## Articles - -
client.articles.list({ ...params }) -> core.Page +## AI Content +
client.aiContent.listContentImportSources() -> Intercom.ContentImportSourcesList
@@ -328,12 +327,7 @@ await client.admins.find({
-You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. - -> 📘 How are the articles sorted and ordered? -> -> Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first. - +You can retrieve a list of all content import sources for a workspace.
@@ -348,18 +342,9 @@ You can fetch a list of all articles by making a GET request to `https://api.int
```typescript -const response = await client.articles.list(); -for await (const item of response) { - console.log(item); -} +await client.aiContent.listContentImportSources(); -// Or you can manually iterate page-by-page -const page = await client.articles.list(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -373,26 +358,19 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListArticlesRequest` - -
-
- -
-
- -**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.articles.create({ ...params }) -> Intercom.Article +
client.aiContent.createContentImportSource({ ...params }) -> Intercom.ContentImportSource
@@ -404,8 +382,7 @@ while (page.hasNextPage()) {
-You can create a new article by making a POST request to `https://api.intercom.io/articles`. - +You can create a new content import source by sending a POST request to this endpoint.
@@ -420,27 +397,11 @@ You can create a new article by making a POST request to `https://api.intercom.i
```typescript -await client.articles.create({ - title: "Thanks for everything", - description: "Description of the Article", - body: "Body of the Article", - author_id: 991267407, - state: "published", - parent_id: 145, - parent_type: "collection", - translated_content: { - fr: { - type: "article_content", - title: "Merci pour tout", - description: "Description de l'article", - body: "Corps de l'article", - author_id: 991267407, - state: "published", - }, - }, +await client.aiContent.createContentImportSource({ + url: "https://www.example.com" }); -``` +```
@@ -454,44 +415,30 @@ await client.articles.create({
-**request:** `Intercom.CreateArticleRequest` - +**request:** `Intercom.CreateContentImportSourceRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.articles.find({ ...params }) -> Intercom.Article -
-
- -#### 📝 Description - -
-
- +
client.aiContent.getContentImportSource({ ...params }) -> Intercom.ContentImportSource
-You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`. - -
-
-
-
- #### 🔌 Usage
@@ -501,11 +448,11 @@ You can fetch the details of a single article by making a GET request to `https:
```typescript -await client.articles.find({ - article_id: "123", +await client.aiContent.getContentImportSource({ + source_id: "source_id" }); -``` +```
@@ -519,26 +466,27 @@ await client.articles.find({
-**request:** `Intercom.FindArticleRequest` - +**request:** `Intercom.GetContentImportSourceRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.articles.update({ ...params }) -> Intercom.Article +
client.aiContent.updateContentImportSource({ ...params }) -> Intercom.ContentImportSource
@@ -550,8 +498,7 @@ await client.articles.find({
-You can update the details of a single article by making a PUT request to `https://api.intercom.io/articles/`. - +You can update an existing content import source.
@@ -566,13 +513,13 @@ You can update the details of a single article by making a PUT request to `https
```typescript -await client.articles.update({ - article_id: "123", - title: "Christmas is here!", - body: "

New gifts in store for the jolly season

", +await client.aiContent.updateContentImportSource({ + source_id: "source_id", + sync_behavior: "api", + url: "https://www.example.com" }); -``` +```
@@ -586,26 +533,27 @@ await client.articles.update({
-**request:** `Intercom.UpdateArticleRequest` - +**request:** `Intercom.UpdateContentImportSourceRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.articles.delete({ ...params }) -> Intercom.DeletedArticleObject +
client.aiContent.deleteContentImportSource({ ...params }) -> void
@@ -617,8 +565,7 @@ await client.articles.update({
-You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`. - +You can delete a content import source by making a DELETE request this endpoint. This will also delete all external pages that were imported from this source.
@@ -633,11 +580,11 @@ You can delete a single article by making a DELETE request to `https://api.inter
```typescript -await client.articles.delete({ - article_id: "123", +await client.aiContent.deleteContentImportSource({ + source_id: "source_id" }); -``` +```
@@ -651,26 +598,27 @@ await client.articles.delete({
-**request:** `Intercom.DeleteArticleRequest` - +**request:** `Intercom.DeleteContentImportSourceRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.articles.search({ ...params }) -> Intercom.SearchArticlesResponse +
client.aiContent.listExternalPages() -> Intercom.ExternalPagesList
@@ -682,8 +630,7 @@ await client.articles.delete({
-You can search for articles by making a GET request to `https://api.intercom.io/articles/search`. - +You can retrieve a list of all external pages for a workspace.
@@ -698,12 +645,9 @@ You can search for articles by making a GET request to `https://api.intercom.io/
```typescript -await client.articles.search({ - phrase: "Getting started", - state: "published", -}); -``` +await client.aiContent.listExternalPages(); +```
@@ -717,28 +661,19 @@ await client.articles.search({
-**request:** `Intercom.SearchArticlesRequest` - -
-
- -
-
- -**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-## HelpCenters - -
client.helpCenters.find({ ...params }) -> Intercom.HelpCenter +
client.aiContent.createExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -750,8 +685,7 @@ await client.articles.search({
-You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`. - +You can create a new external page by sending a POST request to this endpoint. If an external page already exists with the specified source_id and external_id, it will be updated instead.
@@ -766,11 +700,15 @@ You can fetch the details of a single Help Center by making a GET request to `ht
```typescript -await client.helpCenters.find({ - help_center_id: "123", +await client.aiContent.createExternalPage({ + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 44, + external_id: "abc1234" }); -``` +```
@@ -784,26 +722,27 @@ await client.helpCenters.find({
-**request:** `Intercom.FindHelpCenterRequest` - +**request:** `Intercom.CreateExternalPageRequest` +
-**requestOptions:** `HelpCenters.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.helpCenters.list({ ...params }) -> core.Page +
client.aiContent.getExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -815,8 +754,7 @@ await client.helpCenters.find({
-You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`. - +You can retrieve an external page.
@@ -831,18 +769,11 @@ You can list all Help Centers by making a GET request to `https://api.intercom.i
```typescript -const response = await client.helpCenters.list(); -for await (const item of response) { - console.log(item); -} +await client.aiContent.getExternalPage({ + page_id: "page_id" +}); -// Or you can manually iterate page-by-page -const page = await client.helpCenters.list(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -856,28 +787,27 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListHelpCentersRequest` - +**request:** `Intercom.GetExternalPageRequest` +
-**requestOptions:** `HelpCenters.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-## Companies - -
client.companies.retrieve({ ...params }) -> Intercom.CompaniesRetrieveResponse +
client.aiContent.updateExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -889,18 +819,7 @@ while (page.hasNextPage()) {
-You can fetch a single company by passing in `company_id` or `name`. - -`https://api.intercom.io/companies?name={name}` - -`https://api.intercom.io/companies?company_id={company_id}` - -You can fetch all companies and filter by `segment_id` or `tag_id` as a query parameter. - -`https://api.intercom.io/companies?tag_id={tag_id}` - -`https://api.intercom.io/companies?segment_id={segment_id}` - +You can update an existing external page (if it was created via the API).
@@ -915,14 +834,16 @@ You can fetch all companies and filter by `segment_id` or `tag_id` as a query pa
```typescript -await client.companies.retrieve({ - name: "my company", - company_id: "12345", - tag_id: "678910", - segment_id: "98765", +await client.aiContent.updateExternalPage({ + page_id: "page_id", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 47, + external_id: "5678" }); -``` +```
@@ -936,26 +857,27 @@ await client.companies.retrieve({
-**request:** `Intercom.RetrieveCompanyRequest` - +**request:** `Intercom.UpdateExternalPageRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.companies.createOrUpdate({ ...params }) -> Intercom.Company +
client.aiContent.deleteExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -967,16 +889,7 @@ await client.companies.retrieve({
-You can create or update a company. - -Companies will be only visible in Intercom when there is at least one associated user. - -Companies are looked up via `company_id` in a `POST` request, if not found via `company_id`, the new company will be created, if found, that company will be updated. - -{% admonition type="warning" name="Using `company_id`" %} -You can set a unique `company_id` value when creating a company. However, it is not possible to update `company_id`. Be sure to set a unique value once upon creation of the company. -{% /admonition %} - +Sending a DELETE request for an external page will remove it from the content library UI and from being used for AI answers.
@@ -991,13 +904,11 @@ You can set a unique `company_id` value when creating a company. However, it is
```typescript -await client.companies.createOrUpdate({ - name: "my company", - company_id: "company_remote_id", - remote_created_at: 1374138000, +await client.aiContent.deleteExternalPage({ + page_id: "page_id" }); -``` +```
@@ -1011,26 +922,28 @@ await client.companies.createOrUpdate({
-**request:** `Intercom.CreateOrUpdateCompanyRequest` - +**request:** `Intercom.DeleteExternalPageRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.companies.find({ ...params }) -> Intercom.Company +## Articles +
client.articles.list({ ...params }) -> core.Page
@@ -1042,8 +955,11 @@ await client.companies.createOrUpdate({
-You can fetch a single company. +You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. +> 📘 How are the articles sorted and ordered? +> +> Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.
@@ -1058,11 +974,21 @@ You can fetch a single company.
```typescript -await client.companies.find({ - company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", -}); -``` +const pageableResponse = await client.articles.list(); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.articles.list(); +while (page.hasNextPage()) { + page = page.getNextPage(); +} +// You can also access the underlying response +const response = page.response; + +```
@@ -1076,26 +1002,27 @@ await client.companies.find({
-**request:** `Intercom.FindCompanyRequest` - +**request:** `Intercom.ListArticlesRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.update({ ...params }) -> Intercom.Company +
client.articles.create({ ...params }) -> Intercom.Article
@@ -1107,12 +1034,7 @@ await client.companies.find({
-You can update a single company using the Intercom provisioned `id`. - -{% admonition type="warning" name="Using `company_id`" %} -When updating a company it is not possible to update `company_id`. This can only be set once upon creation of the company. -{% /admonition %} - +You can create a new article by making a POST request to `https://api.intercom.io/articles`.
@@ -1127,15 +1049,30 @@ When updating a company it is not possible to update `company_id`. This can only
```typescript -await client.companies.update({ - company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", -}); -``` - -
-
- - +await client.articles.create({ + title: "Thanks for everything", + description: "Description of the Article", + body: "Body of the Article", + author_id: 991267497, + state: "published", + parent_id: 145, + parent_type: "collection", + translated_content: { + fr: { + title: "Merci pour tout", + description: "Description de l'article", + body: "Corps de l'article", + author_id: 991267497, + state: "published" + } + } +}); + +``` + + + + #### ⚙️ Parameters @@ -1145,26 +1082,27 @@ await client.companies.update({
-**request:** `Intercom.UpdateCompanyRequest` - +**request:** `Intercom.CreateArticleRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.delete({ ...params }) -> Intercom.DeletedCompanyObject +
client.articles.find({ ...params }) -> Intercom.Article
@@ -1176,8 +1114,7 @@ await client.companies.update({
-You can delete a single company. - +You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`.
@@ -1192,11 +1129,11 @@ You can delete a single company.
```typescript -await client.companies.delete({ - company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.articles.find({ + article_id: 1 }); -``` +```
@@ -1210,26 +1147,27 @@ await client.companies.delete({
-**request:** `Intercom.DeleteCompanyRequest` - +**request:** `Intercom.FindArticleRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.listAttachedContacts({ ...params }) -> Intercom.CompanyAttachedContacts +
client.articles.update({ ...params }) -> Intercom.Article
@@ -1241,8 +1179,7 @@ await client.companies.delete({
-You can fetch a list of all contacts that belong to a company. - +You can update the details of a single article by making a PUT request to `https://api.intercom.io/articles/`.
@@ -1257,11 +1194,13 @@ You can fetch a list of all contacts that belong to a company.
```typescript -await client.companies.listAttachedContacts({ - company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.articles.update({ + article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

" }); -``` +```
@@ -1275,26 +1214,27 @@ await client.companies.listAttachedContacts({
-**request:** `Intercom.ListAttachedContactsRequest` - +**request:** `Intercom.UpdateArticleRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.listAttachedSegments({ ...params }) -> Intercom.CompanyAttachedSegments +
client.articles.delete({ ...params }) -> Intercom.DeletedArticleObject
@@ -1306,8 +1246,7 @@ await client.companies.listAttachedContacts({
-You can fetch a list of all segments that belong to a company. - +You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`.
@@ -1322,11 +1261,11 @@ You can fetch a list of all segments that belong to a company.
```typescript -await client.companies.listAttachedSegments({ - company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.articles.delete({ + article_id: 1 }); -``` +```
@@ -1340,26 +1279,27 @@ await client.companies.listAttachedSegments({
-**request:** `Intercom.ListSegmentsAttachedToCompanyRequest` - +**request:** `Intercom.DeleteArticleRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.list({ ...params }) -> core.Page +
client.articles.search({ ...params }) -> Intercom.ArticleSearchResponse
@@ -1371,16 +1311,7 @@ await client.companies.listAttachedSegments({
-You can list companies. The company list is sorted by the `last_request_at` field and by default is ordered descending, most recently requested first. - -Note that the API does not include companies who have no associated users in list responses. - -When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the [Scroll API](https://developers.intercom.com/reference#iterating-over-all-companies). -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} - +You can search for articles by making a GET request to `https://api.intercom.io/articles/search`.
@@ -1395,22 +1326,14 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -const response = await client.companies.list({ - order: "desc", +await client.articles.search({ + phrase: "Getting started", + state: "published", + help_center_id: 1, + highlight: true }); -for await (const item of response) { - console.log(item); -} -// Or you can manually iterate page-by-page -const page = await client.companies.list({ - order: "desc", -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -1424,26 +1347,28 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListCompaniesRequest` - +**request:** `Intercom.SearchArticlesRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.companies.scroll({ ...params }) -> core.Page +## Away Status Reasons +
client.awayStatusReasons.listAwayStatusReasons() -> Intercom.AwayStatusReason[]
@@ -1455,22 +1380,7 @@ while (page.hasNextPage()) {
- The `list all companies` functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. - -- Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app. -- If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail -- If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire - -{% admonition type="info" name="Scroll Parameter" %} -You can get the first page of companies by simply sending a GET request to the scroll endpoint. -For subsequent requests you will need to use the scroll parameter from the response. -{% /admonition %} -{% admonition type="danger" name="Scroll network timeouts" %} -Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: -"Request failed due to an internal network error. Please restart the scroll operation." -If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. -{% /admonition %} - +Returns a list of all away status reasons configured for the workspace, including deleted ones.
@@ -1485,18 +1395,9 @@ If this happens, you will need to restart your scroll query: It is not possible
```typescript -const response = await client.companies.scroll(); -for await (const item of response) { - console.log(item); -} +await client.awayStatusReasons.listAwayStatusReasons(); -// Or you can manually iterate page-by-page -const page = await client.companies.scroll(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -1510,44 +1411,23 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ScrollCompaniesRequest` - -
-
- -
-
- -**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `AwayStatusReasonsClient.RequestOptions` +
+
-
client.companies.attachContact({ ...params }) -> Intercom.Company -
-
- -#### 📝 Description - +## Export +
client.export.enqueueANewReportingDataExportJob({ ...params }) -> Intercom.PostExportReportingDataEnqueueResponse
-
-
- -You can attach a company to a single contact. - -
-
-
-
- #### 🔌 Usage
@@ -1557,12 +1437,14 @@ You can attach a company to a single contact.
```typescript -await client.companies.attachContact({ - contact_id: "contact_id", - id: "667d608d8a68186f43bafd70", +await client.export.enqueueANewReportingDataExportJob({ + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000 }); -``` +```
@@ -1576,30 +1458,31 @@ await client.companies.attachContact({
-**request:** `Intercom.AttachContactToCompanyRequest` - +**request:** `Intercom.PostExportReportingDataEnqueueRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ExportClient.RequestOptions` +
+
-
client.companies.detachContact({ ...params }) -> Intercom.Company +
client.export.listAvailableDatasetsAndAttributes() -> Intercom.GetExportReportingDataGetDatasetsResponse
-#### 📝 Description +#### 🔌 Usage
@@ -1607,12 +1490,39 @@ await client.companies.attachContact({
-You can detach a company from a single contact. +```typescript +await client.export.listAvailableDatasetsAndAttributes(); +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**requestOptions:** `ExportClient.RequestOptions` + +
+
+ +
+
+ +## Data Export +
client.dataExport.exportReportingData({ ...params }) -> Intercom.DataExportExportReportingDataResponse +
+
#### 🔌 Usage @@ -1623,12 +1533,13 @@ You can detach a company from a single contact.
```typescript -await client.companies.detachContact({ - contact_id: "58a430d35458202d41b1e65b", - company_id: "58a430d35458202d41b1e65b", +await client.dataExport.exportReportingData({ + job_identifier: "job_identifier", + app_id: "app_id", + client_id: "client_id" }); -``` +```
@@ -1642,28 +1553,27 @@ await client.companies.detachContact({
-**request:** `Intercom.DetachContactFromCompanyRequest` - +**request:** `Intercom.ExportReportingDataRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-## Contacts - -
client.contacts.listAttachedCompanies({ ...params }) -> core.Page +
client.dataExport.downloadReportingDataExport({ ...params }) -> void
@@ -1675,8 +1585,11 @@ await client.companies.detachContact({
-You can fetch a list of companies that are associated to a contact. +Download the data from a completed reporting data export job. +> Octet header required +> +> You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.
@@ -1691,22 +1604,12 @@ You can fetch a list of companies that are associated to a contact.
```typescript -const response = await client.contacts.listAttachedCompanies({ - contact_id: "63a07ddf05a32042dffac965", +await client.dataExport.downloadReportingDataExport({ + job_identifier: "job_identifier", + app_id: "app_id" }); -for await (const item of response) { - console.log(item); -} -// Or you can manually iterate page-by-page -const page = await client.contacts.listAttachedCompanies({ - contact_id: "63a07ddf05a32042dffac965", -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -1720,26 +1623,27 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListAttachedCompaniesRequest` - +**request:** `Intercom.DownloadReportingDataExportRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.contacts.listAttachedSegments({ ...params }) -> Intercom.ContactSegments +
client.dataExport.create({ ...params }) -> Intercom.DataExport
@@ -1751,8 +1655,21 @@ while (page.hasNextPage()) {
-You can fetch a list of segments that are associated to a contact. +To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. + +The only parameters you need to provide are the range of dates that you want exported. +>🚧 Limit of one active job +> +> You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job. + +>❗️ Updated_at not included +> +> It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job. + +>📘 Date ranges are inclusive +> +> Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.
@@ -1767,11 +1684,12 @@ You can fetch a list of segments that are associated to a contact.
```typescript -await client.contacts.listAttachedSegments({ - contact_id: "63a07ddf05a32042dffac965", +await client.dataExport.create({ + created_at_after: 1734519776, + created_at_before: 1734537776 }); -``` +```
@@ -1785,26 +1703,27 @@ await client.contacts.listAttachedSegments({
-**request:** `Intercom.ListSegmentsAttachedToContactRequest` - +**request:** `Intercom.CreateDataExportRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.contacts.listAttachedSubscriptions({ ...params }) -> Intercom.SubscriptionTypeList +
client.dataExport.find({ ...params }) -> Intercom.DataExport
@@ -1816,14 +1735,11 @@ await client.contacts.listAttachedSegments({
-You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. -This will return a list of Subscription Type objects that the contact is associated with. - -The data property will show a combined list of: - -1.Opt-out subscription types that the user has opted-out from. -2.Opt-in subscription types that the user has opted-in to receiving. +You can view the status of your job by sending a `GET` request to the URL +`https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. +> 🚧 Jobs expire after two days +> All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.
@@ -1838,11 +1754,11 @@ The data property will show a combined list of:
```typescript -await client.contacts.listAttachedSubscriptions({ - contact_id: "63a07ddf05a32042dffac965", +await client.dataExport.find({ + job_identifier: "job_identifier" }); -``` +```
@@ -1856,26 +1772,27 @@ await client.contacts.listAttachedSubscriptions({
-**request:** `Intercom.ListAttachedSubscriptionsRequest` - +**request:** `Intercom.FindDataExportRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.contacts.attachSubscription({ ...params }) -> Intercom.SubscriptionType +
client.dataExport.cancel({ ...params }) -> Intercom.DataExport
@@ -1887,14 +1804,7 @@ await client.contacts.listAttachedSubscriptions({
-You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: - -1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type. - -2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type. - -This will return a subscription type model for the subscription type that was added to the contact. - +You can cancel your job
@@ -1909,13 +1819,11 @@ This will return a subscription type model for the subscription type that was ad
```typescript -await client.contacts.attachSubscription({ - contact_id: "63a07ddf05a32042dffac965", - id: "37846", - consent_type: "opt_in", +await client.dataExport.cancel({ + job_identifier: "job_identifier" }); -``` +```
@@ -1929,26 +1837,27 @@ await client.contacts.attachSubscription({
-**request:** `Intercom.AttachSubscriptionToContactRequest` - +**request:** `Intercom.CancelDataExportRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.contacts.detachSubscription({ ...params }) -> Intercom.SubscriptionType +
client.dataExport.download({ ...params }) -> void
@@ -1960,8 +1869,13 @@ await client.contacts.attachSubscription({
-You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. +When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + +Your exported message data will be streamed continuously back down to you in a gzipped CSV format. +> 📘 Octet header required +> +> You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.
@@ -1976,12 +1890,11 @@ You can remove a specific subscription from a contact. This will return a subscr
```typescript -await client.contacts.detachSubscription({ - contact_id: "63a07ddf05a32042dffac965", - subscription_id: "37846", +await client.dataExport.download({ + job_identifier: "job_identifier" }); -``` +```
@@ -1995,26 +1908,28 @@ await client.contacts.detachSubscription({
-**request:** `Intercom.DetachSubscriptionFromContactRequest` - +**request:** `Intercom.DownloadDataExportRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.contacts.listAttachedTags({ ...params }) -> Intercom.TagList +## HelpCenters +
client.helpCenters.find({ ...params }) -> Intercom.HelpCenter
@@ -2026,8 +1941,7 @@ await client.contacts.detachSubscription({
-You can fetch a list of all tags that are attached to a specific contact. - +You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`.
@@ -2042,11 +1956,11 @@ You can fetch a list of all tags that are attached to a specific contact.
```typescript -await client.contacts.listAttachedTags({ - contact_id: "63a07ddf05a32042dffac965", +await client.helpCenters.find({ + help_center_id: 1 }); -``` +```
@@ -2060,26 +1974,27 @@ await client.contacts.listAttachedTags({
-**request:** `Intercom.ListTagsAttachedToContactRequest` - +**request:** `Intercom.FindHelpCenterRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `HelpCentersClient.RequestOptions` +
+
-
client.contacts.find({ ...params }) -> Intercom.Contact +
client.helpCenters.list({ ...params }) -> core.Page
@@ -2091,8 +2006,7 @@ await client.contacts.listAttachedTags({
-You can fetch the details of a single contact. - +You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`.
@@ -2107,11 +2021,21 @@ You can fetch the details of a single contact.
```typescript -await client.contacts.find({ - contact_id: "63a07ddf05a32042dffac965", -}); -``` +const pageableResponse = await client.helpCenters.list(); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.helpCenters.list(); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; +```
@@ -2125,26 +2049,28 @@ await client.contacts.find({
-**request:** `Intercom.FindContactRequest` - +**request:** `Intercom.ListHelpCentersRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `HelpCentersClient.RequestOptions` +
+
-
client.contacts.update({ ...params }) -> Intercom.Contact +## Internal Articles +
client.internalArticles.listInternalArticles() -> Intercom.InternalArticleList
@@ -2156,8 +2082,7 @@ await client.contacts.find({
-You can update an existing contact (ie. user or lead). - +You can fetch a list of all internal articles by making a GET request to `https://api.intercom.io/internal_articles`.
@@ -2172,13 +2097,9 @@ You can update an existing contact (ie. user or lead).
```typescript -await client.contacts.update({ - contact_id: "63a07ddf05a32042dffac965", - email: "joebloggs@intercom.io", - name: "joe bloggs", -}); -``` +await client.internalArticles.listInternalArticles(); +```
@@ -2192,26 +2113,19 @@ await client.contacts.update({
-**request:** `Intercom.UpdateContactRequest` - -
-
- -
-
- -**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.delete({ ...params }) -> Intercom.ContactDeleted +
client.internalArticles.createInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -2223,8 +2137,7 @@ await client.contacts.update({
-You can delete a single contact. - +You can create a new internal article by making a POST request to `https://api.intercom.io/internal_articles`.
@@ -2239,11 +2152,14 @@ You can delete a single contact.
```typescript -await client.contacts.delete({ - contact_id: "contact_id", +await client.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252 }); -``` +```
@@ -2257,26 +2173,27 @@ await client.contacts.delete({
-**request:** `Intercom.DeleteContactRequest` - +**request:** `Intercom.CreateInternalArticleRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.mergeLeadInUser({ ...params }) -> Intercom.Contact +
client.internalArticles.retrieveInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -2288,8 +2205,7 @@ await client.contacts.delete({
-You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`. - +You can fetch the details of a single internal article by making a GET request to `https://api.intercom.io/internal_articles/`.
@@ -2304,12 +2220,11 @@ You can merge a contact with a `role` of `lead` into a contact with a `role` of
```typescript -await client.contacts.mergeLeadInUser({ - from: "667d60ac8a68186f43bafdbb", - into: "667d60ac8a68186f43bafdbc", +await client.internalArticles.retrieveInternalArticle({ + internal_article_id: 1 }); -``` +```
@@ -2323,26 +2238,27 @@ await client.contacts.mergeLeadInUser({
-**request:** `Intercom.MergeContactsRequest` - +**request:** `Intercom.RetrieveInternalArticleRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.search({ ...params }) -> core.Page +
client.internalArticles.updateInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -2354,108 +2270,7 @@ await client.contacts.mergeLeadInUser({
-You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. - -To search for contacts, you need to send a `POST` request to `https://api.intercom.io/contacts/search`. - -This will accept a query object in the body which will define your filters in order to search for contacts. - -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `50` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} - -### Contact Creation Delay - -If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters. - -### Nesting & Limitations - -You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiple's there can be: - -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group - -### Searching for Timestamp Fields - -All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. -For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. -If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). -This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly. - -### Accepted Fields - -Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). - -| Field | Type | -| ---------------------------------- | ------------------------------ | -| id | String | -| role | String
Accepts user or lead | -| name | String | -| avatar | String | -| owner_id | Integer | -| email | String | -| email_domain | String | -| phone | String | -| external_id | String | -| created_at | Date (UNIX Timestamp) | -| signed_up_at | Date (UNIX Timestamp) | -| updated_at | Date (UNIX Timestamp) | -| last_seen_at | Date (UNIX Timestamp) | -| last_contacted_at | Date (UNIX Timestamp) | -| last_replied_at | Date (UNIX Timestamp) | -| last_email_opened_at | Date (UNIX Timestamp) | -| last_email_clicked_at | Date (UNIX Timestamp) | -| language_override | String | -| browser | String | -| browser_language | String | -| os | String | -| location.country | String | -| location.region | String | -| location.city | String | -| unsubscribed_from_emails | Boolean | -| marked_email_as_spam | Boolean | -| has_hard_bounced | Boolean | -| ios_last_seen_at | Date (UNIX Timestamp) | -| ios_app_version | String | -| ios_device | String | -| ios_app_device | String | -| ios_os_version | String | -| ios_app_name | String | -| ios_sdk_version | String | -| android_last_seen_at | Date (UNIX Timestamp) | -| android_app_version | String | -| android_device | String | -| android_app_name | String | -| andoid_sdk_version | String | -| segment_id | String | -| tag_id | String | -| custom_attributes.{attribute_name} | String | - -### Accepted Operators - -{% admonition type="warning" name="Searching based on `created_at`" %} -You cannot use the `<=` or `>=` operators to search by `created_at`. -{% /admonition %} - -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). - -| Operator | Valid Types | Description | -| :------- | :------------------------------- | :--------------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In
Shortcut for `OR` queries
Values must be in Array | -| NIN | All | Not In
Shortcut for `OR !` queries
Values must be in Array | -| > | Integer
Date (UNIX Timestamp) | Greater than | -| < | Integer
Date (UNIX Timestamp) | Lower than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | - +You can update the details of a single internal article by making a PUT request to `https://api.intercom.io/internal_articles/`.
@@ -2470,46 +2285,13 @@ The table below shows the operators you can use to define how you want to search
```typescript -const response = await client.contacts.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, +await client.internalArticles.updateInternalArticle({ + internal_article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

" }); -for await (const item of response) { - console.log(item); -} -// Or you can manually iterate page-by-page -const page = await client.contacts.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -2523,26 +2305,27 @@ while (page.hasNextPage()) {
-**request:** `Intercom.SearchRequest` - +**request:** `Intercom.UpdateInternalArticleRequestBody` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.list({ ...params }) -> core.Page +
client.internalArticles.deleteInternalArticle({ ...params }) -> Intercom.DeletedInternalArticleObject
@@ -2554,12 +2337,7 @@ while (page.hasNextPage()) {
-You can fetch a list of all contacts (ie. users or leads) in your workspace. -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `50` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} - +You can delete a single internal article by making a DELETE request to `https://api.intercom.io/internal_articles/`.
@@ -2574,18 +2352,11 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -const response = await client.contacts.list(); -for await (const item of response) { - console.log(item); -} +await client.internalArticles.deleteInternalArticle({ + internal_article_id: 1 +}); -// Or you can manually iterate page-by-page -const page = await client.contacts.list(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -2599,26 +2370,27 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListContactsRequest` - +**request:** `Intercom.DeleteInternalArticleRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.create({ ...params }) -> Intercom.Contact +
client.internalArticles.searchInternalArticles({ ...params }) -> Intercom.InternalArticleSearchResponse
@@ -2630,8 +2402,7 @@ while (page.hasNextPage()) {
-You can create a new contact (ie. user or lead). - +You can search for internal articles by making a GET request to `https://api.intercom.io/internal_articles/search`.
@@ -2646,11 +2417,11 @@ You can create a new contact (ie. user or lead).
```typescript -await client.contacts.create({ - email: "joebloggs@intercom.io", +await client.internalArticles.searchInternalArticles({ + folder_id: "folder_id" }); -``` +```
@@ -2664,26 +2435,28 @@ await client.contacts.create({
-**request:** `Intercom.CreateContactRequest` - +**request:** `Intercom.SearchInternalArticlesRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.contacts.archive({ ...params }) -> Intercom.ContactArchived +## Companies +
client.companies.retrieve({ ...params }) -> Intercom.CompaniesRetrieveResponse
@@ -2695,8 +2468,17 @@ await client.contacts.create({
-You can archive a single contact. +You can fetch a single company by passing in `company_id` or `name`. + + `https://api.intercom.io/companies?name={name}` + + `https://api.intercom.io/companies?company_id={company_id}` + +You can fetch all companies and filter by `segment_id` or `tag_id` as a query parameter. + + `https://api.intercom.io/companies?tag_id={tag_id}` + `https://api.intercom.io/companies?segment_id={segment_id}`
@@ -2711,11 +2493,16 @@ You can archive a single contact.
```typescript -await client.contacts.archive({ - contact_id: "63a07ddf05a32042dffac965", +await client.companies.retrieve({ + name: "my company", + company_id: "12345", + tag_id: "678910", + segment_id: "98765", + page: 1, + per_page: 1 }); -``` +```
@@ -2729,26 +2516,27 @@ await client.contacts.archive({
-**request:** `Intercom.ArchiveContactRequest` - +**request:** `Intercom.RetrieveCompanyRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.contacts.unarchive({ ...params }) -> Intercom.ContactUnarchived +
client.companies.createOrUpdate({ ...params }) -> Intercom.Company
@@ -2760,8 +2548,15 @@ await client.contacts.archive({
-You can unarchive a single contact. +You can create or update a company. +Companies will be only visible in Intercom when there is at least one associated user. + +Companies are looked up via `company_id` in a `POST` request, if not found via `company_id`, the new company will be created, if found, that company will be updated. + +{% admonition type="warning" name="Using `company_id`" %} + You can set a unique `company_id` value when creating a company. However, it is not possible to update `company_id`. Be sure to set a unique value once upon creation of the company. +{% /admonition %}
@@ -2776,11 +2571,13 @@ You can unarchive a single contact.
```typescript -await client.contacts.unarchive({ - contact_id: "63a07ddf05a32042dffac965", +await client.companies.createOrUpdate({ + name: "my company", + company_id: "company_remote_id", + remote_created_at: 1374138000 }); -``` +```
@@ -2794,28 +2591,27 @@ await client.contacts.unarchive({
-**request:** `Intercom.UnarchiveContactRequest` - +**request:** `Intercom.CreateOrUpdateCompanyRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-## Notes - -
client.notes.list({ ...params }) -> core.Page +
client.companies.find({ ...params }) -> Intercom.Company
@@ -2827,8 +2623,7 @@ await client.contacts.unarchive({
-You can fetch a list of notes that are associated to a contact. - +You can fetch a single company.
@@ -2843,22 +2638,11 @@ You can fetch a list of notes that are associated to a contact.
```typescript -const response = await client.notes.list({ - contact_id: "contact_id", +await client.companies.find({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -for await (const item of response) { - console.log(item); -} -// Or you can manually iterate page-by-page -const page = await client.notes.list({ - contact_id: "contact_id", -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -2872,26 +2656,27 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListContactNotesRequest` - +**request:** `Intercom.FindCompanyRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.notes.create({ ...params }) -> Intercom.Note +
client.companies.update({ ...params }) -> Intercom.Company
@@ -2903,8 +2688,11 @@ while (page.hasNextPage()) {
-You can add a note to a single contact. +You can update a single company using the Intercom provisioned `id`. +{% admonition type="warning" name="Using `company_id`" %} + When updating a company it is not possible to update `company_id`. This can only be set once upon creation of the company. +{% /admonition %}
@@ -2919,13 +2707,15 @@ You can add a note to a single contact.
```typescript -await client.notes.create({ - contact_id: "123", - body: "Hello", - admin_id: "123", +await client.companies.update({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + body: { + name: "my company", + website: "http://www.mycompany.com/" + } }); -``` +```
@@ -2939,26 +2729,27 @@ await client.notes.create({
-**request:** `Intercom.CreateContactNoteRequest` - +**request:** `Intercom.UpdateCompanyRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.notes.find({ ...params }) -> Intercom.Note +
client.companies.delete({ ...params }) -> Intercom.DeletedCompanyObject
@@ -2970,8 +2761,7 @@ await client.notes.create({
-You can fetch the details of a single note. - +You can delete a single company.
@@ -2986,11 +2776,11 @@ You can fetch the details of a single note.
```typescript -await client.notes.find({ - note_id: "1", +await client.companies.delete({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -3004,28 +2794,27 @@ await client.notes.find({
-**request:** `Intercom.FindNoteRequest` - +**request:** `Intercom.DeleteCompanyRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-## Tags - -
client.tags.tagContact({ ...params }) -> Intercom.Tag +
client.companies.listAttachedContacts({ ...params }) -> Intercom.CompanyAttachedContacts
@@ -3037,8 +2826,7 @@ await client.notes.find({
-You can tag a specific contact. This will return a tag object for the tag that was added to the contact. - +You can fetch a list of all contacts that belong to a company.
@@ -3053,12 +2841,11 @@ You can tag a specific contact. This will return a tag object for the tag that w
```typescript -await client.tags.tagContact({ - contact_id: "63a07ddf05a32042dffac965", - id: "7522907", +await client.companies.listAttachedContacts({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -3072,26 +2859,27 @@ await client.tags.tagContact({
-**request:** `Intercom.TagContactRequest` - +**request:** `Intercom.ListAttachedContactsRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.untagContact({ ...params }) -> Intercom.Tag +
client.companies.listAttachedSegments({ ...params }) -> Intercom.CompanyAttachedSegments
@@ -3103,8 +2891,7 @@ await client.tags.tagContact({
-You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. - +You can fetch a list of all segments that belong to a company.
@@ -3119,12 +2906,11 @@ You can remove tag from a specific contact. This will return a tag object for th
```typescript -await client.tags.untagContact({ - contact_id: "63a07ddf05a32042dffac965", - tag_id: "7522907", +await client.companies.listAttachedSegments({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -3138,26 +2924,27 @@ await client.tags.untagContact({
-**request:** `Intercom.UntagContactRequest` - +**request:** `Intercom.ListSegmentsAttachedToCompanyRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.tagConversation({ ...params }) -> Intercom.Tag +
client.companies.list({ ...params }) -> core.Page
@@ -3169,8 +2956,15 @@ await client.tags.untagContact({
-You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. +You can list companies. The company list is sorted by the `last_request_at` field and by default is ordered descending, most recently requested first. + +Note that the API does not include companies who have no associated users in list responses. +When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the [Scroll API](https://developers.intercom.com/reference#iterating-over-all-companies). +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %}
@@ -3185,13 +2979,29 @@ You can tag a specific conversation. This will return a tag object for the tag t
```typescript -await client.tags.tagConversation({ - conversation_id: "64619700005694", - id: "7522907", - admin_id: "780", +const pageableResponse = await client.companies.list({ + page: 1, + per_page: 1, + order: "desc" }); -``` +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.companies.list({ + page: 1, + per_page: 1, + order: "desc" +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; +```
@@ -3205,26 +3015,27 @@ await client.tags.tagConversation({
-**request:** `Intercom.TagConversationRequest` - +**request:** `Intercom.ListCompaniesRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.untagConversation({ ...params }) -> Intercom.Tag +
client.companies.scroll({ ...params }) -> core.Page
@@ -3236,8 +3047,21 @@ await client.tags.tagConversation({
-You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. + The `list all companies` functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + +- Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app. +- If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail +- If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire +{% admonition type="info" name="Scroll Parameter" %} + You can get the first page of companies by simply sending a GET request to the scroll endpoint. + For subsequent requests you will need to use the scroll parameter from the response. +{% /admonition %} +{% admonition type="danger" name="Scroll network timeouts" %} + Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + "Request failed due to an internal network error. Please restart the scroll operation." + If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. +{% /admonition %}
@@ -3252,13 +3076,25 @@ You can remove tag from a specific conversation. This will return a tag object f
```typescript -await client.tags.untagConversation({ - conversation_id: "64619700005694", - tag_id: "7522907", - admin_id: "123", +const pageableResponse = await client.companies.scroll({ + scroll_param: "scroll_param" }); -``` +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.companies.scroll({ + scroll_param: "scroll_param" +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; +```
@@ -3272,26 +3108,27 @@ await client.tags.untagConversation({
-**request:** `Intercom.UntagConversationRequest` - +**request:** `Intercom.ScrollCompaniesRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.list() -> Intercom.TagList +
client.companies.attachContact({ ...params }) -> Intercom.Company
@@ -3303,8 +3140,7 @@ await client.tags.untagConversation({
-You can fetch a list of all tags for a given workspace. - +You can attach a company to a single contact.
@@ -3319,9 +3155,12 @@ You can fetch a list of all tags for a given workspace.
```typescript -await client.tags.list(); -``` +await client.companies.attachContact({ + contact_id: "contact_id", + id: "6762f09a1bb69f9f2193bb34" +}); +```
@@ -3335,18 +3174,27 @@ await client.tags.list();
-**requestOptions:** `Tags.RequestOptions` +**request:** `Intercom.AttachContactToCompanyRequest` + +
+
+ +
+
+**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.create({ ...params }) -> Intercom.Tag +
client.companies.detachContact({ ...params }) -> Intercom.Company
@@ -3358,20 +3206,7 @@ await client.tags.list();
-You can use this endpoint to perform the following operations: - -**1. Create a new tag:** You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below. - -**2. Update an existing tag:** You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below. - -**3. Tag Companies:** You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically. - -**4. Untag Companies:** You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below. - -**5. Tag Multiple Users:** You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below. - -Each operation will return a tag object. - +You can detach a company from a single contact.
@@ -3386,11 +3221,12 @@ Each operation will return a tag object.
```typescript -await client.tags.create({ - name: "test", +await client.companies.detachContact({ + contact_id: "58a430d35458202d41b1e65b", + company_id: "58a430d35458202d41b1e65b" }); -``` +```
@@ -3404,26 +3240,28 @@ await client.tags.create({
-**request:** `Intercom.TagsCreateRequestBody` - +**request:** `Intercom.DetachContactFromCompanyRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.tags.find({ ...params }) -> Intercom.Tag +## Contacts +
client.contacts.listAttachedCompanies({ ...params }) -> core.Page
@@ -3435,9 +3273,7 @@ await client.tags.create({
-You can fetch the details of tags that are on the workspace by their id. -This will return a tag object. - +You can fetch a list of companies that are associated to a contact.
@@ -3452,11 +3288,29 @@ This will return a tag object.
```typescript -await client.tags.find({ - tag_id: "123", +const pageableResponse = await client.contacts.listAttachedCompanies({ + contact_id: "63a07ddf05a32042dffac965", + page: 1, + per_page: 1 }); -``` +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.contacts.listAttachedCompanies({ + contact_id: "63a07ddf05a32042dffac965", + page: 1, + per_page: 1 +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; +```
@@ -3470,26 +3324,27 @@ await client.tags.find({
-**request:** `Intercom.FindTagRequest` - +**request:** `Intercom.ListAttachedCompaniesRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.tags.delete({ ...params }) -> void +
client.contacts.listAttachedSegments({ ...params }) -> Intercom.ContactSegments
@@ -3501,8 +3356,7 @@ await client.tags.find({
-You can delete the details of tags that are on the workspace by passing in the id. - +You can fetch a list of segments that are associated to a contact.
@@ -3517,11 +3371,11 @@ You can delete the details of tags that are on the workspace by passing in the i
```typescript -await client.tags.delete({ - tag_id: "123", +await client.contacts.listAttachedSegments({ + contact_id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -3535,26 +3389,27 @@ await client.tags.delete({
-**request:** `Intercom.DeleteTagRequest` - +**request:** `Intercom.ListSegmentsAttachedToContactRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.tags.tagTicket({ ...params }) -> Intercom.Tag +
client.contacts.listAttachedSubscriptions({ ...params }) -> Intercom.SubscriptionTypeList
@@ -3566,8 +3421,13 @@ await client.tags.delete({
-You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. +You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. +This will return a list of Subscription Type objects that the contact is associated with. + +The data property will show a combined list of: + 1.Opt-out subscription types that the user has opted-out from. + 2.Opt-in subscription types that the user has opted-in to receiving.
@@ -3582,13 +3442,11 @@ You can tag a specific ticket. This will return a tag object for the tag that wa
```typescript -await client.tags.tagTicket({ - ticket_id: "64619700005694", - id: "7522907", - admin_id: "780", +await client.contacts.listAttachedSubscriptions({ + contact_id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -3602,26 +3460,27 @@ await client.tags.tagTicket({
-**request:** `Intercom.TagTicketRequest` - +**request:** `Intercom.ListAttachedSubscriptionsRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.tags.untagTicket({ ...params }) -> Intercom.Tag +
client.contacts.attachSubscription({ ...params }) -> Intercom.SubscriptionType
@@ -3633,8 +3492,13 @@ await client.tags.tagTicket({
-You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. +You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: + 1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type. + + 2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type. + +This will return a subscription type model for the subscription type that was added to the contact.
@@ -3649,13 +3513,13 @@ You can remove tag from a specific ticket. This will return a tag object for the
```typescript -await client.tags.untagTicket({ - ticket_id: "64619700005694", - tag_id: "7522907", - admin_id: "123", +await client.contacts.attachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in" }); -``` +```
@@ -3669,28 +3533,27 @@ await client.tags.untagTicket({
-**request:** `Intercom.UntagTicketRequest` - +**request:** `Intercom.AttachSubscriptionToContactRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-## Conversations - -
client.conversations.list({ ...params }) -> core.Page +
client.contacts.detachSubscription({ ...params }) -> Intercom.SubscriptionType
@@ -3702,14 +3565,73 @@ await client.tags.untagTicket({
-You can fetch a list of all conversations. +You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. +
+
+
+
-You can optionally request the result page size and the cursor to start after to fetch the result. -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.detachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + subscription_id: "37846" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DetachSubscriptionFromContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + + + +
+ +
client.contacts.listAttachedTags({ ...params }) -> Intercom.TagList +
+
+ +#### 📝 Description + +
+
+ +
+
+You can fetch a list of all tags that are attached to a specific contact.
@@ -3724,18 +3646,11 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -const response = await client.conversations.list(); -for await (const item of response) { - console.log(item); -} +await client.contacts.listAttachedTags({ + contact_id: "63a07ddf05a32042dffac965" +}); -// Or you can manually iterate page-by-page -const page = await client.conversations.list(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -3749,26 +3664,92 @@ while (page.hasNextPage()) {
-**request:** `Intercom.ListConversationsRequest` +**request:** `Intercom.ListTagsAttachedToContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+ +
+ + + + +
+ +
client.contacts.find({ ...params }) -> Intercom.ContactsFindResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch the details of a single contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.find({ + contact_id: "63a07ddf05a32042dffac965" +}); +``` +
+
+#### ⚙️ Parameters + +
+
+
-**requestOptions:** `Conversations.RequestOptions` +**request:** `Intercom.FindContactRequest` + +
+
+ +
+
+**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.conversations.create({ ...params }) -> Intercom.Message +
client.contacts.update({ ...params }) -> Intercom.ContactsUpdateResponse
@@ -3780,16 +3761,80 @@ while (page.hasNextPage()) {
-You can create a conversation that has been initiated by a contact (ie. user or lead). -The conversation can be an in-app message only. +You can update an existing contact (ie. user or lead). -{% admonition type="info" name="Sending for visitors" %} -You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`. -This visitor will be automatically converted to a contact with a lead role once the conversation is created. +{% admonition type="info" %} + This endpoint handles both **contact updates** and **custom object associations**. + + See _`update a contact with an association to a custom object instance`_ in the request/response examples to see the custom object association format. {% /admonition %} +
+
+
+
-This will return the Message model that has been created. +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.update({ + contact_id: "63a07ddf05a32042dffac965", + email: "joebloggs@intercom.io", + name: "joe bloggs" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UpdateContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + + + +
+ +
client.contacts.delete({ ...params }) -> Intercom.ContactDeleted +
+
+ +#### 📝 Description + +
+
+ +
+
+You can delete a single contact.
@@ -3804,15 +3849,11 @@ This will return the Message model that has been created.
```typescript -await client.conversations.create({ - from: { - type: "user", - id: "667d60d18a68186f43bafddd", - }, - body: "Hello there", +await client.contacts.delete({ + contact_id: "contact_id" }); -``` +```
@@ -3826,26 +3867,4299 @@ await client.conversations.create({
-**request:** `Intercom.CreateConversationRequest` +**request:** `Intercom.DeleteContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+ +
+ + + + +
+ +
client.contacts.mergeLeadInUser({ ...params }) -> Intercom.ContactsMergeLeadInUserResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`. +
+
+#### 🔌 Usage + +
+
+
-**requestOptions:** `Conversations.RequestOptions` +```typescript +await client.contacts.mergeLeadInUser({ + from: "6762f0d51bb69f9f2193bb7f", + into: "6762f0d51bb69f9f2193bb80" +}); +```
+#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.MergeContactsRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.search({ ...params }) -> core.Page +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + +To search for contacts, you need to send a `POST` request to `https://api.intercom.io/contacts/search`. + +This will accept a query object in the body which will define your filters in order to search for contacts. + +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `50` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} +### Contact Creation Delay + +If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters. + +### Nesting & Limitations + +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiple's there can be: +* There's a limit of max 2 nested filters +* There's a limit of max 15 filters for each AND or OR group + +### Searching for Timestamp Fields + +All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. +For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. +If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). +This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly. + +### Accepted Fields + +Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). + +| Field | Type | +| ---------------------------------- | ------------------------------ | +| id | String | +| role | String
Accepts user or lead | +| name | String | +| avatar | String | +| owner_id | Integer | +| email | String | +| email_domain | String | +| phone | String | +| external_id | String | +| created_at | Date (UNIX Timestamp) | +| signed_up_at | Date (UNIX Timestamp) | +| updated_at | Date (UNIX Timestamp) | +| last_seen_at | Date (UNIX Timestamp) | +| last_contacted_at | Date (UNIX Timestamp) | +| last_replied_at | Date (UNIX Timestamp) | +| last_email_opened_at | Date (UNIX Timestamp) | +| last_email_clicked_at | Date (UNIX Timestamp) | +| language_override | String | +| browser | String | +| browser_language | String | +| os | String | +| location.country | String | +| location.region | String | +| location.city | String | +| unsubscribed_from_emails | Boolean | +| marked_email_as_spam | Boolean | +| has_hard_bounced | Boolean | +| ios_last_seen_at | Date (UNIX Timestamp) | +| ios_app_version | String | +| ios_device | String | +| ios_app_device | String | +| ios_os_version | String | +| ios_app_name | String | +| ios_sdk_version | String | +| android_last_seen_at | Date (UNIX Timestamp) | +| android_app_version | String | +| android_device | String | +| android_app_name | String | +| andoid_sdk_version | String | +| segment_id | String | +| tag_id | String | +| custom_attributes.{attribute_name} | String | + +### Accepted Operators + +{% admonition type="warning" name="Searching based on `created_at`" %} + You cannot use the `<=` or `>=` operators to search by `created_at`. +{% /admonition %} + +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). + +| Operator | Valid Types | Description | +| :------- | :------------------------------- | :--------------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In
Shortcut for `OR` queries
Values must be in Array | +| NIN | All | Not In
Shortcut for `OR !` queries
Values must be in Array | +| > | Integer
Date (UNIX Timestamp) | Greater than | +| < | Integer
Date (UNIX Timestamp) | Lower than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With | +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.contacts.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.contacts.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.SearchRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.list({ ...params }) -> core.Page +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of all contacts (ie. users or leads) in your workspace. +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `50` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %} +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.contacts.list(); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.contacts.list(); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListContactsRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.create({ ...params }) -> Intercom.ContactsCreateResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can create a new contact (ie. user or lead). +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.create({ + email: "joebloggs@intercom.io" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.showContactByExternalId({ ...params }) -> Intercom.ShowContactByExternalIdResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.showContactByExternalId({ + external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ShowContactByExternalIdRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.archive({ ...params }) -> Intercom.ContactArchived +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can archive a single contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.archive({ + contact_id: "63a07ddf05a32042dffac965" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ArchiveContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.unarchive({ ...params }) -> Intercom.ContactUnarchived +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can unarchive a single contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.unarchive({ + contact_id: "63a07ddf05a32042dffac965" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UnarchiveContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.contacts.blockContact({ ...params }) -> Intercom.ContactBlocked +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Block a single contact.
**Note:** conversations of the contact will also be archived during the process.
More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs) +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.contacts.blockContact({ + contact_id: "63a07ddf05a32042dffac965" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.BlockContactRequest` + +
+
+ +
+
+ +**requestOptions:** `ContactsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Notes +
client.notes.list({ ...params }) -> core.Page +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of notes that are associated to a contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.notes.list({ + contact_id: "contact_id" +}); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.notes.list({ + contact_id: "contact_id" +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListContactNotesRequest` + +
+
+ +
+
+ +**requestOptions:** `NotesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.notes.create({ ...params }) -> Intercom.Note +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can add a note to a single contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.notes.create({ + contact_id: "123", + body: "Hello", + admin_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateContactNoteRequest` + +
+
+ +
+
+ +**requestOptions:** `NotesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.notes.find({ ...params }) -> Intercom.Note +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch the details of a single note. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.notes.find({ + note_id: 1 +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.FindNoteRequest` + +
+
+ +
+
+ +**requestOptions:** `NotesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Tags +
client.tags.tagContact({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can tag a specific contact. This will return a tag object for the tag that was added to the contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.tagContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.TagContactRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.untagContact({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.untagContact({ + contact_id: "63a07ddf05a32042dffac965", + tag_id: "7522907" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UntagContactRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.tagConversation({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.tagConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.TagConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.untagConversation({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.untagConversation({ + conversation_id: "64619700005694", + tag_id: "7522907", + admin_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UntagConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.list() -> Intercom.TagList +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of all tags for a given workspace. + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.list(); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.create({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can use this endpoint to perform the following operations: + + **1. Create a new tag:** You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below. + + **2. Update an existing tag:** You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below. + + **3. Tag Companies:** You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically. + + **4. Untag Companies:** You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below. + + **5. Tag Multiple Users:** You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below. + +Each operation will return a tag object. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.create({ + name: "test" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.TagsCreateRequestBody` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.find({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch the details of tags that are on the workspace by their id. +This will return a tag object. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.find({ + tag_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.FindTagRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.delete({ ...params }) -> void +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can delete the details of tags that are on the workspace by passing in the id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.delete({ + tag_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DeleteTagRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.tagTicket({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.tagTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.TagTicketRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.tags.untagTicket({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.tags.untagTicket({ + ticket_id: "64619700005694", + tag_id: "7522907", + admin_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UntagTicketRequest` + +
+
+ +
+
+ +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Conversations +
client.conversations.list({ ...params }) -> core.Page +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of all conversations. + +You can optionally request the result page size and the cursor to start after to fetch the result. +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %} +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.conversations.list({ + per_page: 1, + starting_after: "starting_after" +}); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.conversations.list({ + per_page: 1, + starting_after: "starting_after" +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListConversationsRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.create({ ...params }) -> Intercom.Message +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can create a conversation that has been initiated by a contact (ie. user or lead). +The conversation can be an in-app message only. + +{% admonition type="info" name="Sending for visitors" %} +You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`. +This visitor will be automatically converted to a contact with a lead role once the conversation is created. +{% /admonition %} + +This will return the Message model that has been created. + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.create({ + from: { + type: "user", + id: "6762f11b1bb69f9f2193bba3" + }, + body: "Hello there" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.find({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ + +You can fetch the details of a single conversation. + +This will return a single Conversation model with all its conversation parts. + +{% admonition type="warning" name="Hard limit of 500 parts" %} +The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. +{% /admonition %} + +For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671). +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.find({ + conversation_id: "123", + display_as: "plaintext", + include_translations: true +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.FindConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.update({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ + +You can update an existing conversation. + +{% admonition type="info" name="Replying and other actions" %} +If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. +{% /admonition %} + +{% admonition type="info" %} + This endpoint handles both **conversation updates** and **custom object associations**. + + See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format. +{% /admonition %} + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.update({ + conversation_id: "conversation_id", + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + "issue_type": "Billing", + "priority": "High" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UpdateConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.deleteConversation({ ...params }) -> Intercom.ConversationDeleted +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can delete a single conversation. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.deleteConversation({ + conversation_id: 1 +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DeleteConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.search({ ...params }) -> core.Page +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + +To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`. + +This will accept a query object in the body which will define your filters in order to search for conversations. +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} + +### Nesting & Limitations + +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiple's there can be: +- There's a limit of max 2 nested filters +- There's a limit of max 15 filters for each AND or OR group + +### Accepted Fields + +Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). +The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. + +| Field | Type | +| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | +| id | String | +| created_at | Date (UNIX timestamp) | +| updated_at | Date (UNIX timestamp) | +| source.type | String
Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. | +| source.id | String | +| source.delivered_as | String | +| source.subject | String | +| source.body | String | +| source.author.id | String | +| source.author.type | String | +| source.author.name | String | +| source.author.email | String | +| source.url | String | +| contact_ids | String | +| teammate_ids | String | +| admin_assignee_id | String | +| team_assignee_id | String | +| channel_initiated | String | +| open | Boolean | +| read | Boolean | +| state | String | +| waiting_since | Date (UNIX timestamp) | +| snoozed_until | Date (UNIX timestamp) | +| tag_ids | String | +| priority | String | +| statistics.time_to_assignment | Integer | +| statistics.time_to_admin_reply | Integer | +| statistics.time_to_first_close | Integer | +| statistics.time_to_last_close | Integer | +| statistics.median_time_to_reply | Integer | +| statistics.first_contact_reply_at | Date (UNIX timestamp) | +| statistics.first_assignment_at | Date (UNIX timestamp) | +| statistics.first_admin_reply_at | Date (UNIX timestamp) | +| statistics.first_close_at | Date (UNIX timestamp) | +| statistics.last_assignment_at | Date (UNIX timestamp) | +| statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | +| statistics.last_contact_reply_at | Date (UNIX timestamp) | +| statistics.last_admin_reply_at | Date (UNIX timestamp) | +| statistics.last_close_at | Date (UNIX timestamp) | +| statistics.last_closed_by_id | String | +| statistics.count_reopens | Integer | +| statistics.count_assignments | Integer | +| statistics.count_conversation_parts | Integer | +| conversation_rating.requested_at | Date (UNIX timestamp) | +| conversation_rating.replied_at | Date (UNIX timestamp) | +| conversation_rating.score | Integer | +| conversation_rating.remark | String | +| conversation_rating.contact_id | String | +| conversation_rating.admin_d | String | +| ai_agent_participated | Boolean | +| ai_agent.resolution_state | String | +| ai_agent.last_answer_type | String | +| ai_agent.rating | Integer | +| ai_agent.rating_remark | String | +| ai_agent.source_type | String | +| ai_agent.source_title | String | + +### Accepted Operators + +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). + +| Operator | Valid Types | Description | +| :------- | :----------------------------- | :----------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In Shortcut for `OR` queries Values most be in Array | +| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | +| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | +| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With | +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.conversations.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.conversations.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.SearchRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.reply({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.reply({ + conversation_id: "123 or \"last\"", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ReplyToConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.manage({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +For managing conversations you can: +- Close a conversation +- Snooze a conversation to reopen on a future date +- Open a conversation which is `snoozed` or `closed` +- Assign a conversation to an admin and/or team. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ManageConversationPartsRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.attachContactAsAdmin({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + +{% admonition type="warning" name="Contacts without an email" %} +If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. +{% /admonition %} + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.attachContactAsAdmin({ + conversation_id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19b1bb69f9f2193bbd4" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.AttachContactToConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.detachContactAsAdmin({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + +{% admonition type="warning" name="Contacts without an email" %} +If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. +{% /admonition %} + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.detachContactAsAdmin({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DetachContactFromConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.redactConversationPart({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can redact a conversation part or the source message of a conversation (as seen in the source object). + +{% admonition type="info" name="Redacting parts and messages" %} +If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. +{% /admonition %} + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.redactConversationPart({ + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.RedactConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.convertToTicket({ ...params }) -> Intercom.Ticket | undefined +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can convert a conversation to a ticket. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.convertToTicket({ + conversation_id: 1, + ticket_type_id: "53" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ConvertConversationToTicketRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.conversations.runAssignmentRules({ ...params }) -> Intercom.Conversation +
+
+ +#### 📝 Description + +
+
+ +
+
+ +{% admonition type="danger" name="Deprecation of Run Assignment Rules" %} +Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. +{% /admonition %} +You can let a conversation be automatically assigned following assignment rules. +{% admonition type="warning" name="When using workflows" %} +It is not possible to use this endpoint with Workflows. +{% /admonition %} +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.conversations.runAssignmentRules({ + conversation_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.AutoAssignConversationRequest` + +
+
+ +
+
+ +**requestOptions:** `ConversationsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Custom Channel Events +
client.customChannelEvents.notifyNewConversation({ ...params }) -> Intercom.CustomChannelNotificationResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CustomChannelBaseEvent` + +
+
+ +
+
+ +**requestOptions:** `CustomChannelEventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customChannelEvents.notifyNewMessage({ ...params }) -> Intercom.CustomChannelNotificationResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.NotifyNewMessageRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomChannelEventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customChannelEvents.notifyQuickReplySelected({ ...params }) -> Intercom.CustomChannelNotificationResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customChannelEvents.notifyQuickReplySelected({ + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { + type: "user", + external_id: "user_003", + name: "Alice Example", + email: "alice@example.com" + }, + quick_reply_option_id: "1234" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.NotifyQuickReplySelectedRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomChannelEventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customChannelEvents.notifyAttributeCollected({ ...params }) -> Intercom.CustomChannelNotificationResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value" + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.NotifyAttributeCollectedRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomChannelEventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Custom Object Instances +
client.customObjectInstances.getCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstance | undefined +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Fetch a Custom Object Instance by external_id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + external_id: "external_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.GetCustomObjectInstancesByExternalIdRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customObjectInstances.createCustomObjectInstances({ ...params }) -> Intercom.CustomObjectInstance | undefined +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Create or update a custom object instance +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "Order", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { + "order_number": "ORDER-12345", + "total_amount": "custom_attributes" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateOrUpdateCustomObjectInstanceRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customObjectInstances.deleteCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstanceDeleted +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Delete a single Custom Object instance by external_id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + external_id: "external_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DeleteCustomObjectInstancesByIdRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customObjectInstances.getCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstance | undefined +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Fetch a Custom Object Instance by id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + custom_object_instance_id: "custom_object_instance_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.GetCustomObjectInstancesByIdRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstanceDeleted +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Delete a single Custom Object instance using the Intercom defined id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + custom_object_instance_id: "custom_object_instance_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.DeleteCustomObjectInstancesByExternalIdRequest` + +
+
+ +
+
+ +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Data Attributes +
client.dataAttributes.list({ ...params }) -> Intercom.DataAttributeList +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.dataAttributes.list({ + model: "contact", + include_archived: true +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListDataAttributesRequest` + +
+
+ +
+
+ +**requestOptions:** `DataAttributesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.dataAttributes.create({ ...params }) -> Intercom.DataAttribute +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can create a data attributes for a `contact` or a `company`. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.dataAttributes.create({ + data_type: "string" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateDataAttributeRequest` + +
+
+ +
+
+ +**requestOptions:** `DataAttributesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.dataAttributes.update({ ...params }) -> Intercom.DataAttribute +
+
+ +#### 📝 Description + +
+
+ +
+
+ + +You can update a data attribute. + +> 🚧 Updating the data type is not possible +> +> It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [{ + value: "1-10" + }, { + value: "11-20" + }] + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.UpdateDataAttributeRequest` + +
+
+ +
+
+ +**requestOptions:** `DataAttributesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Events +
client.events.list({ ...params }) -> Intercom.DataEventSummary +
+
+ +#### 📝 Description + +
+
+ +
+
+ + +> 🚧 +> +> Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days + +The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`. + +- `https://api.intercom.io/events?type=user&user_id={user_id}` +- `https://api.intercom.io/events?type=user&email={email}` +- `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads) + +The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending. + +You can optionally define the result page size as well with the `per_page` parameter. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.events.list({ + user_id: "user_id", + intercom_user_id: "intercom_user_id", + email: "email", + type: "type", + summary: true, + per_page: 1 +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListEventsRequest` + +
+
+ +
+
+ +**requestOptions:** `EventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.events.create({ ...params }) -> void +
+
+ +#### 📝 Description + +
+
+ +
+
+ + +You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`. + +When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event. + +With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`). + +**NB: For the JSON object types, please note that we do not currently support nested JSON structure.** + +| Type | Description | Example | +| :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | +| String | The value is a JSON String | `"source":"desktop"` | +| Number | The value is a JSON Number | `"load": 3.67` | +| Date | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272` | +| Link | The value is a HTTP or HTTPS URI. | `"article": "https://example.org/ab1de.html"` | +| Rich Link | The value is a JSON object that contains `url` and `value` keys. | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` | +| Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | `"price": {"amount": 34999, "currency": "eur"}` | + +**Lead Events** + +When submitting events for Leads, you will need to specify the Lead's `id`. + +**Metadata behaviour** + +- We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event. +- It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one. +- There might be up to 24 hrs delay when you send a new metadata for an existing event. + +**Event de-duplication** + +The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field. + +Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place. + +### HTTP API Responses + +- Successful responses to submitted events return `202 Accepted` with an empty body. +- Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code. +- Events sent about users that cannot be found will return a `404 Not Found`. +- Event lists containing duplicate events will have those duplicates ignored. +- Server errors will return a `500` response code and may contain an error message in the body. + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.events.create({ + id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", + event_name: "invited-friend", + created_at: 1671028894 +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateDataEventRequest` + +
+
+ +
+
+ +**requestOptions:** `EventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.events.summaries({ ...params }) -> void +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.events.summaries(); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListEventSummariesRequest` + +
+
+ +
+
+ +**requestOptions:** `EventsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Jobs +
client.jobs.status({ ...params }) -> Intercom.Jobs +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Retrieve the status of job execution. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.jobs.status({ + job_id: "job_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.JobsStatusRequest` + +
+
+ +
+
+ +**requestOptions:** `JobsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Messages +
client.messages.create({ ...params }) -> Intercom.Message +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. + +> 🚧 Sending for visitors +> +> There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case. + +This will return the Message model that has been created. + +> 🚧 Retrieving Associated Conversations +> +> As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051 + }, + to: { + type: "user", + id: "536e564f316c83104c000020" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreateMessageRequest` + +
+
+ +
+
+ +**requestOptions:** `MessagesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Segments +
client.segments.list({ ...params }) -> Intercom.SegmentList +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch a list of all segments. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.segments.list({ + include_count: true +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListSegmentsRequest` + +
+
+ +
+
+ +**requestOptions:** `SegmentsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.segments.find({ ...params }) -> Intercom.Segment +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can fetch the details of a single segment. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.segments.find({ + segment_id: "123" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.FindSegmentRequest` + +
+
+ +
+
+ +**requestOptions:** `SegmentsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Subscription Types +
client.subscriptionTypes.list() -> Intercom.SubscriptionTypeList +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can list all subscription types. A list of subscription type objects will be returned. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.subscriptionTypes.list(); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**requestOptions:** `SubscriptionTypesClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## PhoneCallRedirects +
client.phoneCallRedirects.create({ ...params }) -> Intercom.PhoneSwitch | undefined +
+
+ +#### 📝 Description + +
+
+ +
+
+ +You can use the API to deflect phone calls to the Intercom Messenger. +Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. + +If custom attributes are specified, they will be added to the user or lead's custom data attributes. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.phoneCallRedirects.create({ + phone: "+353832345678", + custom_attributes: { + "issue_type": "Billing", + "priority": "High" + } +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.CreatePhoneSwitchRequest` + +
+
+ +
+
+ +**requestOptions:** `PhoneCallRedirectsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +## Calls +
client.calls.listCalls({ ...params }) -> Intercom.CallList +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Retrieve a paginated list of calls. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.calls.listCalls({ + page: 1, + per_page: 1 +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ListCallsRequest` + +
+
+ +
+
+ +**requestOptions:** `CallsClient.RequestOptions` + +
+
+
+
+ + +
+
+
+ +
client.calls.showCall({ ...params }) -> Intercom.Call +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Retrieve a single call by id. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +await client.calls.showCall({ + call_id: "call_id" +}); + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Intercom.ShowCallRequest` + +
+
+ +
+
+ +**requestOptions:** `CallsClient.RequestOptions` + +
+
+
+
+ +
-
client.conversations.find({ ...params }) -> Intercom.Conversation +
client.calls.showCallRecording({ ...params }) -> void
@@ -3857,16 +8171,7 @@ await client.conversations.create({
-You can fetch the details of a single conversation. - -This will return a single Conversation model with all its conversation parts. - -{% admonition type="warning" name="Hard limit of 500 parts" %} -The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. -{% /admonition %} - -For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671). - +Redirects to a signed URL for the call's recording if it exists.
@@ -3881,12 +8186,11 @@ For AI agent conversation metadata, please note that you need to have the agent
```typescript -await client.conversations.find({ - conversation_id: "123", - display_as: "plaintext", +await client.calls.showCallRecording({ + call_id: "call_id" }); -``` +```
@@ -3900,26 +8204,27 @@ await client.conversations.find({
-**request:** `Intercom.FindConversationRequest` - +**request:** `Intercom.ShowCallRecordingRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.conversations.update({ ...params }) -> Intercom.Conversation +
client.calls.showCallTranscript({ ...params }) -> string
@@ -3931,12 +8236,7 @@ await client.conversations.find({
-You can update an existing conversation. - -{% admonition type="info" name="Replying and other actions" %} -If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. -{% /admonition %} - +Returns the transcript for the specified call as a downloadable text file.
@@ -3951,17 +8251,11 @@ If you want to reply to a coveration or take an action such as assign, unassign,
```typescript -await client.conversations.update({ - conversation_id: "123", - display_as: "plaintext", - read: true, - custom_attributes: { - issue_type: "Billing", - priority: "High", - }, +await client.calls.showCallTranscript({ + call_id: "call_id" }); -``` +```
@@ -3975,26 +8269,27 @@ await client.conversations.update({
-**request:** `Intercom.UpdateConversationRequest` - +**request:** `Intercom.ShowCallTranscriptRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.conversations.search({ ...params }) -> core.Page +
client.calls.listCallsWithTranscripts({ ...params }) -> Intercom.ListCallsWithTranscriptsResponse
@@ -4006,107 +8301,8 @@ await client.conversations.update({
-You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. - -To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`. - -This will accept a query object in the body which will define your filters in order to search for conversations. -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} - -### Nesting & Limitations - -You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiple's there can be: - -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group - -### Accepted Fields - -Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). -The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. - -| Field | Type | -| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | -| id | String | -| created_at | Date (UNIX timestamp) | -| updated_at | Date (UNIX timestamp) | -| source.type | String
Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. | -| source.id | String | -| source.delivered_as | String | -| source.subject | String | -| source.body | String | -| source.author.id | String | -| source.author.type | String | -| source.author.name | String | -| source.author.email | String | -| source.url | String | -| contact_ids | String | -| teammate_ids | String | -| admin_assignee_id | String | -| team_assignee_id | String | -| channel_initiated | String | -| open | Boolean | -| read | Boolean | -| state | String | -| waiting_since | Date (UNIX timestamp) | -| snoozed_until | Date (UNIX timestamp) | -| tag_ids | String | -| priority | String | -| statistics.time_to_assignment | Integer | -| statistics.time_to_admin_reply | Integer | -| statistics.time_to_first_close | Integer | -| statistics.time_to_last_close | Integer | -| statistics.median_time_to_reply | Integer | -| statistics.first_contact_reply_at | Date (UNIX timestamp) | -| statistics.first_assignment_at | Date (UNIX timestamp) | -| statistics.first_admin_reply_at | Date (UNIX timestamp) | -| statistics.first_close_at | Date (UNIX timestamp) | -| statistics.last_assignment_at | Date (UNIX timestamp) | -| statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | -| statistics.last_contact_reply_at | Date (UNIX timestamp) | -| statistics.last_admin_reply_at | Date (UNIX timestamp) | -| statistics.last_close_at | Date (UNIX timestamp) | -| statistics.last_closed_by_id | String | -| statistics.count_reopens | Integer | -| statistics.count_assignments | Integer | -| statistics.count_conversation_parts | Integer | -| conversation_rating.requested_at | Date (UNIX timestamp) | -| conversation_rating.replied_at | Date (UNIX timestamp) | -| conversation_rating.score | Integer | -| conversation_rating.remark | String | -| conversation_rating.contact_id | String | -| conversation_rating.admin_d | String | -| ai_agent_participated | Boolean | -| ai_agent.resolution_state | String | -| ai_agent.last_answer_type | String | -| ai_agent.rating | Integer | -| ai_agent.rating_remark | String | -| ai_agent.source_type | String | -| ai_agent.source_title | String | - -### Accepted Operators - -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). - -| Operator | Valid Types | Description | -| :------- | :---------------------------- | :--------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In Shortcut for `OR` queries Values most be in Array | -| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | -| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | -| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | - +Retrieve calls by a list of conversation ids and include transcripts when available. +A maximum of 20 `conversation_ids` can be provided. If none are provided or more than 20 are provided, a 400 error is returned.
@@ -4121,46 +8317,11 @@ The table below shows the operators you can use to define how you want to search
```typescript -const response = await client.conversations.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, +await client.calls.listCallsWithTranscripts({ + conversation_ids: ["64619700005694", "64619700005695"] }); -for await (const item of response) { - console.log(item); -} -// Or you can manually iterate page-by-page -const page = await client.conversations.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -4174,26 +8335,28 @@ while (page.hasNextPage()) {
-**request:** `Intercom.SearchRequest` - +**request:** `Intercom.ListCallsWithTranscriptsRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.conversations.reply({ ...params }) -> Intercom.Conversation +## Teams +
client.teams.list() -> Intercom.TeamList
@@ -4205,8 +8368,7 @@ while (page.hasNextPage()) {
-You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. - +This will return a list of team objects for the App.
@@ -4221,17 +8383,9 @@ You can reply to a conversation with a message from an admin or on behalf of a c
```typescript -await client.conversations.reply({ - conversation_id: '123 or "last"', - body: { - message_type: "comment", - type: "user", - body: "Thanks again :)", - intercom_user_id: "667d60f18a68186f43bafdf4", - }, -}); -``` +await client.teams.list(); +```
@@ -4245,26 +8399,19 @@ await client.conversations.reply({
-**request:** `Intercom.ReplyToConversationRequest` - -
-
- -
-
- -**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TeamsClient.RequestOptions` +
+
-
client.conversations.manage({ ...params }) -> Intercom.Conversation +
client.teams.find({ ...params }) -> Intercom.Team
@@ -4276,16 +8423,11 @@ await client.conversations.reply({
-For managing conversations you can: - -- Close a conversation -- Snooze a conversation to reopen on a future date -- Open a conversation which is `snoozed` or `closed` -- Assign a conversation to an admin and/or team. -
-
-
-
+You can fetch the details of a single team, containing an array of admins that belong to this team. + + + + #### 🔌 Usage @@ -4296,16 +8438,11 @@ For managing conversations you can:
```typescript -await client.conversations.manage({ - conversation_id: "123", - body: { - message_type: "close", - type: "admin", - admin_id: "12345", - }, +await client.teams.find({ + team_id: "123" }); -``` +```
@@ -4319,26 +8456,28 @@ await client.conversations.manage({
-**request:** `Intercom.ManageConversationPartsRequest` - +**request:** `Intercom.FindTeamRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TeamsClient.RequestOptions` +
+
-
client.conversations.runAssignmentRules({ ...params }) -> Intercom.Conversation +## Ticket States +
client.ticketStates.listTicketStates() -> Intercom.TicketStateList
@@ -4350,14 +8489,7 @@ await client.conversations.manage({
-{% admonition type="danger" name="Deprecation of Run Assignment Rules" %} -Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. -{% /admonition %} -You can let a conversation be automatically assigned following assignment rules. -{% admonition type="warning" name="When using workflows" %} -It is not possible to use this endpoint with Workflows. -{% /admonition %} - +You can get a list of all ticket states for a workspace.
@@ -4372,11 +8504,9 @@ It is not possible to use this endpoint with Workflows.
```typescript -await client.conversations.runAssignmentRules({ - conversation_id: "123", -}); -``` +await client.ticketStates.listTicketStates(); +```
@@ -4390,26 +8520,20 @@ await client.conversations.runAssignmentRules({
-**request:** `Intercom.AutoAssignConversationRequest` - -
-
- -
-
- -**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TicketStatesClient.RequestOptions` +
+
-
client.conversations.attachContactAsAdmin({ ...params }) -> Intercom.Conversation +## Ticket Types +
client.ticketTypes.list() -> Intercom.TicketTypeList
@@ -4421,12 +8545,7 @@ await client.conversations.runAssignmentRules({
-You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. - -{% admonition type="warning" name="Contacts without an email" %} -If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. -{% /admonition %} - +You can get a list of all ticket types for a workspace.
@@ -4441,15 +8560,9 @@ If you add a contact via the email parameter and there is no user/lead found on
```typescript -await client.conversations.attachContactAsAdmin({ - conversation_id: "123", - admin_id: "12345", - customer: { - intercom_user_id: "667d61168a68186f43bafe0d", - }, -}); -``` +await client.ticketTypes.list(); +```
@@ -4463,26 +8576,19 @@ await client.conversations.attachContactAsAdmin({
-**request:** `Intercom.AttachContactToConversationRequest` - -
-
- -
-
- -**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-
client.conversations.detachContactAsAdmin({ ...params }) -> Intercom.Conversation +
client.ticketTypes.create({ ...params }) -> Intercom.TicketType | undefined
@@ -4492,14 +8598,13 @@ await client.conversations.attachContactAsAdmin({
-
- -You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. - -{% admonition type="warning" name="Contacts without an email" %} -If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. -{% /admonition %} +
+You can create a new ticket type. +> 📘 Creating ticket types. +> +> Every ticket type will be created with two default attributes: _default_title_ and _default_description_. +> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/)
@@ -4514,13 +8619,14 @@ If you add a contact via the email parameter and there is no user/lead found on
```typescript -await client.conversations.detachContactAsAdmin({ - conversation_id: "123", - contact_id: "123", - admin_id: "5017690", +await client.ticketTypes.create({ + name: "Customer Issue", + description: "Customer Report Template", + category: "Customer", + icon: "\uD83C\uDF9F\uFE0F" }); -``` +```
@@ -4534,26 +8640,27 @@ await client.conversations.detachContactAsAdmin({
-**request:** `Intercom.DetachContactFromConversationRequest` - +**request:** `Intercom.CreateTicketTypeRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-
client.conversations.redactConversationPart({ ...params }) -> Intercom.Conversation +
client.ticketTypes.get({ ...params }) -> Intercom.TicketType | undefined
@@ -4565,12 +8672,7 @@ await client.conversations.detachContactAsAdmin({
-You can redact a conversation part or the source message of a conversation (as seen in the source object). - -{% admonition type="info" name="Redacting parts and messages" %} -If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. -{% /admonition %} - +You can fetch the details of a single ticket type.
@@ -4585,13 +8687,11 @@ If you are redacting a conversation part, it must have a `body`. If you are reda
```typescript -await client.conversations.redactConversationPart({ - type: "conversation_part", - conversation_id: "19894788788", - conversation_part_id: "19381789428", +await client.ticketTypes.get({ + ticket_type_id: "ticket_type_id" }); -``` +```
@@ -4605,26 +8705,27 @@ await client.conversations.redactConversationPart({
-**request:** `Intercom.RedactConversationRequest` - +**request:** `Intercom.FindTicketTypeRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-
client.conversations.convertToTicket({ ...params }) -> Intercom.Ticket +
client.ticketTypes.update({ ...params }) -> Intercom.TicketType | undefined
@@ -4636,8 +8737,12 @@ await client.conversations.redactConversationPart({
-You can convert a conversation to a ticket. +You can update a ticket type. + +> 📘 Updating a ticket type. +> +> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/)
@@ -4652,12 +8757,12 @@ You can convert a conversation to a ticket.
```typescript -await client.conversations.convertToTicket({ - conversation_id: "123", - ticket_type_id: "79", +await client.ticketTypes.update({ + ticket_type_id: "ticket_type_id", + name: "Bug Report 2" }); -``` +```
@@ -4671,28 +8776,28 @@ await client.conversations.convertToTicket({
-**request:** `Intercom.ConvertConversationToTicketRequest` - +**request:** `Intercom.UpdateTicketTypeRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-## Data Attributes - -
client.dataAttributes.list({ ...params }) -> Intercom.DataAttributeList +## Tickets +
client.tickets.reply({ ...params }) -> Intercom.TicketReply
@@ -4704,8 +8809,7 @@ await client.conversations.convertToTicket({
-You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. - +You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins.
@@ -4720,9 +8824,17 @@ You can fetch a list of all data attributes belonging to a workspace for contact
```typescript -await client.dataAttributes.list(); -``` +await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49" + } +}); +```
@@ -4736,26 +8848,27 @@ await client.dataAttributes.list();
-**request:** `Intercom.ListDataAttributesRequest` - +**request:** `Intercom.ReplyToTicketRequest` +
-**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.dataAttributes.create({ ...params }) -> Intercom.DataAttribute +
client.tickets.create({ ...params }) -> Intercom.Ticket | undefined
@@ -4767,8 +8880,7 @@ await client.dataAttributes.list();
-You can create a data attributes for a `contact` or a `company`. - +You can create a new ticket.
@@ -4783,13 +8895,14 @@ You can create a data attributes for a `contact` or a `company`.
```typescript -await client.dataAttributes.create({ - name: "Mithril Shirt", - model: "company", - data_type: "string", +await client.tickets.create({ + ticket_type_id: "1234", + contacts: [{ + id: "6762f2d81bb69f9f2193bc54" + }] }); -``` +```
@@ -4803,26 +8916,27 @@ await client.dataAttributes.create({
-**request:** `Intercom.CreateDataAttributeRequest` - +**request:** `Intercom.CreateTicketRequest` +
-**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.dataAttributes.update({ ...params }) -> Intercom.DataAttribute +
client.tickets.enqueueCreateTicket({ ...params }) -> Intercom.Jobs
@@ -4834,12 +8948,7 @@ await client.dataAttributes.create({
-You can update a data attribute. - -> 🚧 Updating the data type is not possible -> -> It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead. - +Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job.
@@ -4854,21 +8963,14 @@ You can update a data attribute.
```typescript -await client.dataAttributes.update({ - data_attribute_id: "1", - archived: false, - description: "Just a plain old ring", - options: [ - { - value: "1-10", - }, - { - value: "11-20", - }, - ], +await client.tickets.enqueueCreateTicket({ + ticket_type_id: "1234", + contacts: [{ + id: "6762f2d81bb69f9f2193bc54" + }] }); -``` +```
@@ -4882,28 +8984,27 @@ await client.dataAttributes.update({
-**request:** `Intercom.UpdateDataAttributeRequest` - +**request:** `Intercom.EnqueueCreateTicketRequest` +
-**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-## Events - -
client.events.list({ ...params }) -> Intercom.DataEventSummary +
client.tickets.get({ ...params }) -> Intercom.Ticket | undefined
@@ -4915,20 +9016,7 @@ await client.dataAttributes.update({
-> 🚧 -> -> Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days - -The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`. - -- `https://api.intercom.io/events?type=user&user_id={user_id}` -- `https://api.intercom.io/events?type=user&email={email}` -- `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads) - -The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending. - -You can optionally define the result page size as well with the `per_page` parameter. - +You can fetch the details of a single ticket.
@@ -4943,11 +9031,11 @@ You can optionally define the result page size as well with the `per_page` param
```typescript -await client.events.list({ - type: "type", +await client.tickets.get({ + ticket_id: "ticket_id" }); -``` +```
@@ -4961,26 +9049,27 @@ await client.events.list({
-**request:** `Intercom.ListEventsRequest` - +**request:** `Intercom.FindTicketRequest` +
-**requestOptions:** `Events.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.events.create({ ...params }) -> void +
client.tickets.update({ ...params }) -> Intercom.Ticket | undefined
@@ -4992,50 +9081,11 @@ await client.events.list({
-You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`. - -When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event. - -With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`). - -**NB: For the JSON object types, please note that we do not currently support nested JSON structure.** - -| Type | Description | Example | -| :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | -| String | The value is a JSON String | `"source":"desktop"` | -| Number | The value is a JSON Number | `"load": 3.67` | -| Date | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272` | -| Link | The value is a HTTP or HTTPS URI. | `"article": "https://example.org/ab1de.html"` | -| Rich Link | The value is a JSON object that contains `url` and `value` keys. | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` | -| Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | `"price": {"amount": 34999, "currency": "eur"}` | - -**Lead Events** - -When submitting events for Leads, you will need to specify the Lead's `id`. - -**Metadata behaviour** - -- We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event. -- It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one. -- There might be up to 24 hrs delay when you send a new metadata for an existing event. - -**Event de-duplication** - -The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field. - -Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place. - -### HTTP API Responses - -- Successful responses to submitted events return `202 Accepted` with an empty body. -- Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code. -- Events sent about users that cannot be found will return a `404 Not Found`. -- Event lists containing duplicate events will have those duplicates ignored. -- Server errors will return a `500` response code and may contain an error message in the body. -
-
-
-
+You can update a ticket. + + + + #### 🔌 Usage @@ -5046,13 +9096,20 @@ Duplicated events are responded to using the normal `202 Accepted` code - an err
```typescript -await client.events.create({ - id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", - event_name: "invited-friend", - created_at: 1671028894, +await client.tickets.update({ + ticket_id: "ticket_id", + ticket_attributes: { + "_default_title_": "example", + "_default_description_": "there is a problem" + }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123" }); -``` +```
@@ -5066,26 +9123,27 @@ await client.events.create({
-**request:** `Intercom.CreateDataEventRequest` - +**request:** `Intercom.UpdateTicketRequest` +
-**requestOptions:** `Events.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.events.summaries({ ...params }) -> void +
client.tickets.deleteTicket({ ...params }) -> Intercom.DeleteTicketResponse
@@ -5097,8 +9155,7 @@ await client.events.create({
-Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. - +You can delete a ticket using the Intercom provided ID.
@@ -5113,9 +9170,11 @@ Create event summaries for a user. Event summaries are used to track the number
```typescript -await client.events.summaries(); -``` +await client.tickets.deleteTicket({ + ticket_id: "ticket_id" +}); +```
@@ -5129,28 +9188,27 @@ await client.events.summaries();
-**request:** `Intercom.ListEventSummariesRequest` - +**request:** `Intercom.DeleteTicketRequest` +
-**requestOptions:** `Events.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-## Data Export - -
client.dataExport.create({ ...params }) -> Intercom.DataExport +
client.tickets.search({ ...params }) -> core.Page<(Intercom.Ticket | undefined), Intercom.TicketList>
@@ -5162,22 +9220,75 @@ await client.events.summaries();
-To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. +You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. -The only parameters you need to provide are the range of dates that you want exported. +To search for tickets, you send a `POST` request to `https://api.intercom.io/tickets/search`. -> 🚧 Limit of one active job -> -> You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job. +This will accept a query object in the body which will define your filters. +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} -> ❗️ Updated_at not included -> -> It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job. +### Nesting & Limitations -> 📘 Date ranges are inclusive -> -> Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99. +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiples there can be: +- There's a limit of max 2 nested filters +- There's a limit of max 15 filters for each AND or OR group + +### Accepted Fields + +Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foobar"`). +The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. + +| Field | Type | +| :---------------------------------------- | :--------------------------------------------------------------------------------------- | +| id | String | +| created_at | Date (UNIX timestamp) | +| updated_at | Date (UNIX timestamp) | +| title | String | +| description | String | +| category | String | +| ticket_type_id | String | +| contact_ids | String | +| teammate_ids | String | +| admin_assignee_id | String | +| team_assignee_id | String | +| open | Boolean | +| state | String | +| snoozed_until | Date (UNIX timestamp) | +| ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | + +{% admonition type="info" name="Searching by Category" %} +When searching for tickets by the **`category`** field, specific terms must be used instead of the category names: +* For **Customer** category tickets, use the term `request`. +* For **Back-office** category tickets, use the term `task`. +* For **Tracker** category tickets, use the term `tracker`. +{% /admonition %} + +### Accepted Operators + +{% admonition type="info" name="Searching based on `created_at`" %} + You may use the `<=` or `>=` operators to search by `created_at`. +{% /admonition %} +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). + +| Operator | Valid Types | Description | +| :------- | :----------------------------- | :----------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In Shortcut for `OR` queries Values most be in Array | +| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | +| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | +| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With |
@@ -5188,16 +9299,49 @@ The only parameters you need to provide are the range of dates that you want exp
-
-
+
+
+ +```typescript +const pageableResponse = await client.tickets.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.tickets.search({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } +}); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; -```typescript -await client.dataExport.create({ - created_at_after: 1719474967, - created_at_before: 1719492967, -}); ``` -
@@ -5211,26 +9355,28 @@ await client.dataExport.create({
-**request:** `Intercom.CreateDataExportRequest` - +**request:** `Intercom.SearchRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.dataExport.find({ ...params }) -> Intercom.DataExport +## Visitors +
client.visitors.find({ ...params }) -> Intercom.Visitor | undefined
@@ -5242,12 +9388,7 @@ await client.dataExport.create({
-You can view the status of your job by sending a `GET` request to the URL -`https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. - -> 🚧 Jobs expire after two days -> All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available. - +You can fetch the details of a single visitor.
@@ -5262,11 +9403,11 @@ You can view the status of your job by sending a `GET` request to the URL
```typescript -await client.dataExport.find({ - job_identifier: "job_identifier", +await client.visitors.find({ + user_id: "user_id" }); -``` +```
@@ -5280,26 +9421,27 @@ await client.dataExport.find({
-**request:** `Intercom.FindDataExportRequest` - +**request:** `Intercom.FindVisitorRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-
client.dataExport.cancel({ ...params }) -> Intercom.DataExport +
client.visitors.update({ ...params }) -> Intercom.Visitor | undefined
@@ -5311,8 +9453,11 @@ await client.dataExport.find({
-You can cancel your job +Sending a PUT request to `/visitors` will result in an update of an existing Visitor. + +**Option 1.** You can update a visitor by passing in the `user_id` of the visitor in the Request body. +**Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body.
@@ -5327,11 +9472,12 @@ You can cancel your job
```typescript -await client.dataExport.cancel({ - job_identifier: "job_identifier", +await client.visitors.update({ + id: "6762f30c1bb69f9f2193bc5e", + name: "Gareth Bale" }); -``` +```
@@ -5345,26 +9491,27 @@ await client.dataExport.cancel({
-**request:** `Intercom.CancelDataExportRequest` - +**request:** `Intercom.UpdateVisitorRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-
client.dataExport.download({ ...params }) -> void +
client.visitors.mergeToContact({ ...params }) -> Intercom.Contact
@@ -5376,14 +9523,11 @@ await client.dataExport.cancel({
-When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. - -Your exported message data will be streamed continuously back down to you in a gzipped CSV format. +You can merge a Visitor to a Contact of role type `lead` or `user`. -> 📘 Octet header required +> 📘 What happens upon a visitor being converted? > -> You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint. - +> If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.
@@ -5398,11 +9542,18 @@ Your exported message data will be streamed continuously back down to you in a g
```typescript -await client.dataExport.download({ - job_identifier: "job_identifier", +await client.visitors.mergeToContact({ + type: "user", + user: { + id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", + email: "foo@bar.com" + }, + visitor: { + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3" + } }); -``` +```
@@ -5416,28 +9567,28 @@ await client.dataExport.download({
-**request:** `Intercom.DownloadDataExportRequest` - +**request:** `Intercom.MergeVisitorToContactRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-## Messages - -
client.messages.create({ ...params }) -> Intercom.Message +## HelpCenters Collections +
client.helpCenters.collections.list({ ...params }) -> core.Page
@@ -5449,18 +9600,9 @@ await client.dataExport.download({
-You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. - -> 🚧 Sending for visitors -> -> There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case. - -This will return the Message model that has been created. - -> 🚧 Retrieving Associated Conversations -> -> As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message. +You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. +Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.
@@ -5475,22 +9617,21 @@ This will return the Message model that has been created.
```typescript -await client.messages.create({ - message_type: "email", - subject: "Thanks for everything", - body: "Hello there", - template: "plain", - from: { - type: "admin", - id: 394051, - }, - to: { - type: "user", - id: "536e564f316c83104c000020", - }, -}); -``` +const pageableResponse = await client.helpCenters.collections.list(); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.helpCenters.collections.list(); +while (page.hasNextPage()) { + page = page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; +```
@@ -5504,28 +9645,27 @@ await client.messages.create({
-**request:** `Intercom.CreateMessageRequest` - +**request:** `Intercom.helpCenters.ListCollectionsRequest` +
-**requestOptions:** `Messages.RequestOptions` - +**requestOptions:** `CollectionsClient.RequestOptions` +
+
-## Segments - -
client.segments.list({ ...params }) -> Intercom.SegmentList +
client.helpCenters.collections.create({ ...params }) -> Intercom.Collection
@@ -5537,8 +9677,7 @@ await client.messages.create({
-You can fetch a list of all segments. - +You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.`
@@ -5553,9 +9692,11 @@ You can fetch a list of all segments.
```typescript -await client.segments.list(); -``` +await client.helpCenters.collections.create({ + name: "Thanks for everything" +}); +```
@@ -5569,26 +9710,27 @@ await client.segments.list();
-**request:** `Intercom.ListSegmentsRequest` - +**request:** `Intercom.helpCenters.CreateCollectionRequest` +
-**requestOptions:** `Segments.RequestOptions` - +**requestOptions:** `CollectionsClient.RequestOptions` +
+
-
client.segments.find({ ...params }) -> Intercom.Segment +
client.helpCenters.collections.find({ ...params }) -> Intercom.Collection
@@ -5600,8 +9742,7 @@ await client.segments.list();
-You can fetch the details of a single segment. - +You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`.
@@ -5616,11 +9757,11 @@ You can fetch the details of a single segment.
```typescript -await client.segments.find({ - segment_id: "123", +await client.helpCenters.collections.find({ + collection_id: 1 }); -``` +```
@@ -5634,28 +9775,27 @@ await client.segments.find({
-**request:** `Intercom.FindSegmentRequest` - +**request:** `Intercom.helpCenters.FindCollectionRequest` +
-**requestOptions:** `Segments.RequestOptions` - +**requestOptions:** `CollectionsClient.RequestOptions` +
+
-## Subscription Types - -
client.subscriptionTypes.list() -> Intercom.SubscriptionTypeList +
client.helpCenters.collections.update({ ...params }) -> Intercom.Collection
@@ -5667,8 +9807,7 @@ await client.segments.find({
-You can list all subscription types. A list of subscription type objects will be returned. - +You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`.
@@ -5683,9 +9822,12 @@ You can list all subscription types. A list of subscription type objects will be
```typescript -await client.subscriptionTypes.list(); -``` +await client.helpCenters.collections.update({ + collection_id: 1, + name: "Update collection name" +}); +```
@@ -5699,20 +9841,27 @@ await client.subscriptionTypes.list();
-**requestOptions:** `SubscriptionTypes.RequestOptions` +**request:** `Intercom.helpCenters.UpdateCollectionRequest` + +
+
+ +
+
+**requestOptions:** `CollectionsClient.RequestOptions` +
+
-## PhoneCallRedirects - -
client.phoneCallRedirects.create({ ...params }) -> Intercom.PhoneSwitch +
client.helpCenters.collections.delete({ ...params }) -> Intercom.DeletedCollectionObject
@@ -5724,11 +9873,7 @@ await client.subscriptionTypes.list();
-You can use the API to deflect phone calls to the Intercom Messenger. -Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. - -If custom attributes are specified, they will be added to the user or lead's custom data attributes. - +You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`.
@@ -5743,15 +9888,11 @@ If custom attributes are specified, they will be added to the user or lead's cus
```typescript -await client.phoneCallRedirects.create({ - phone: "+353832345678", - custom_attributes: { - issue_type: "Billing", - priority: "High", - }, +await client.helpCenters.collections.delete({ + collection_id: 1 }); -``` +```
@@ -5765,28 +9906,28 @@ await client.phoneCallRedirects.create({
-**request:** `Intercom.CreatePhoneCallRedirectRequest` - +**request:** `Intercom.helpCenters.DeleteCollectionRequest` +
-**requestOptions:** `PhoneCallRedirects.RequestOptions` - +**requestOptions:** `CollectionsClient.RequestOptions` +
+
-## Teams - -
client.teams.list() -> Intercom.TeamList +## News Items +
client.news.items.list() -> Intercom.PaginatedResponse
@@ -5798,8 +9939,7 @@ await client.phoneCallRedirects.create({
-This will return a list of team objects for the App. - +You can fetch a list of all news items
@@ -5814,9 +9954,9 @@ This will return a list of team objects for the App.
```typescript -await client.teams.list(); -``` +await client.news.items.list(); +```
@@ -5830,18 +9970,19 @@ await client.teams.list();
-**requestOptions:** `Teams.RequestOptions` - +**requestOptions:** `ItemsClient.RequestOptions` +
+
-
client.teams.find({ ...params }) -> Intercom.Team +
client.news.items.create({ ...params }) -> Intercom.NewsItem
@@ -5853,8 +9994,7 @@ await client.teams.list();
-You can fetch the details of a single team, containing an array of admins that belong to this team. - +You can create a news item
@@ -5869,11 +10009,21 @@ You can fetch the details of a single team, containing an array of admins that b
```typescript -await client.teams.find({ - team_id: "123", +await client.news.items.create({ + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + newsfeed_assignments: [{ + newsfeed_id: 53, + published_at: 1664638214 + }] }); -``` +```
@@ -5887,28 +10037,27 @@ await client.teams.find({
-**request:** `Intercom.FindTeamRequest` - +**request:** `Intercom.NewsItemRequest` +
-**requestOptions:** `Teams.RequestOptions` - +**requestOptions:** `ItemsClient.RequestOptions` +
+
-## Ticket Types - -
client.ticketTypes.list() -> Intercom.TicketTypeList +
client.news.items.find({ ...params }) -> Intercom.NewsItem
@@ -5920,8 +10069,7 @@ await client.teams.find({
-You can get a list of all ticket types for a workspace. - +You can fetch the details of a single news item.
@@ -5936,9 +10084,11 @@ You can get a list of all ticket types for a workspace.
```typescript -await client.ticketTypes.list(); -``` +await client.news.items.find({ + news_item_id: 1 +}); +```
@@ -5952,41 +10102,30 @@ await client.ticketTypes.list();
-**requestOptions:** `TicketTypes.RequestOptions` +**request:** `Intercom.news.FindNewsItemRequest` + +
+
+ +
+
+**requestOptions:** `ItemsClient.RequestOptions` +
+
-
client.ticketTypes.create({ ...params }) -> Intercom.TicketType -
-
- -#### 📝 Description - -
-
- +
client.news.items.update({ ...params }) -> Intercom.NewsItem
-You can create a new ticket type. - -> 📘 Creating ticket types. -> -> Every ticket type will be created with two default attributes: _default_title_ and _default_description_. -> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) - -
-
-
-
- #### 🔌 Usage
@@ -5996,14 +10135,17 @@ You can create a new ticket type.
```typescript -await client.ticketTypes.create({ - name: "Customer Issue", - description: "Customer Report Template", - category: "Customer", - icon: "\uD83C\uDF9F\uFE0F", +await client.news.items.update({ + news_item_id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] + } }); -``` +```
@@ -6017,26 +10159,27 @@ await client.ticketTypes.create({
-**request:** `Intercom.CreateTicketTypeRequest` - +**request:** `Intercom.news.UpdateNewsItemRequest` +
-**requestOptions:** `TicketTypes.RequestOptions` - +**requestOptions:** `ItemsClient.RequestOptions` +
+
-
client.ticketTypes.get({ ...params }) -> Intercom.TicketType +
client.news.items.delete({ ...params }) -> Intercom.DeletedObject
@@ -6048,8 +10191,7 @@ await client.ticketTypes.create({
-You can fetch the details of a single ticket type. - +You can delete a single news item.
@@ -6064,11 +10206,11 @@ You can fetch the details of a single ticket type.
```typescript -await client.ticketTypes.get({ - ticket_type_id: "ticket_type_id", +await client.news.items.delete({ + news_item_id: 1 }); -``` +```
@@ -6082,26 +10224,28 @@ await client.ticketTypes.get({
-**request:** `Intercom.FindTicketTypeRequest` - +**request:** `Intercom.news.DeleteNewsItemRequest` +
-**requestOptions:** `TicketTypes.RequestOptions` - +**requestOptions:** `ItemsClient.RequestOptions` +
+
-
client.ticketTypes.update({ ...params }) -> Intercom.TicketType +## News Feeds +
client.news.feeds.listItems({ ...params }) -> Intercom.PaginatedResponse
@@ -6113,12 +10257,7 @@ await client.ticketTypes.get({
-You can update a ticket type. - -> 📘 Updating a ticket type. -> -> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) - +You can fetch a list of all news items that are live on a given newsfeed
@@ -6133,12 +10272,11 @@ You can update a ticket type.
```typescript -await client.ticketTypes.update({ - ticket_type_id: "ticket_type_id", - name: "Bug Report 2", +await client.news.feeds.listItems({ + newsfeed_id: "123" }); -``` +```
@@ -6152,28 +10290,27 @@ await client.ticketTypes.update({
-**request:** `Intercom.UpdateTicketTypeRequest` - +**request:** `Intercom.news.ListNewsFeedItemsRequest` +
-**requestOptions:** `TicketTypes.RequestOptions` - +**requestOptions:** `FeedsClient.RequestOptions` +
+
-## Tickets - -
client.tickets.reply({ ...params }) -> Intercom.TicketReply +
client.news.feeds.list() -> Intercom.PaginatedResponse
@@ -6185,8 +10322,7 @@ await client.ticketTypes.update({
-You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. - +You can fetch a list of all newsfeeds
@@ -6201,17 +10337,9 @@ You can reply to a ticket with a message from an admin or on behalf of a contact
```typescript -await client.tickets.reply({ - ticket_id: "123", - body: { - message_type: "comment", - type: "user", - body: "Thanks again :)", - intercom_user_id: "667d619d8a68186f43bafe82", - }, -}); -``` +await client.news.feeds.list(); +```
@@ -6225,26 +10353,19 @@ await client.tickets.reply({
-**request:** `Intercom.ReplyToTicketRequest` - -
-
- -
-
- -**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `FeedsClient.RequestOptions` +
+
-
client.tickets.create({ ...params }) -> Intercom.Ticket +
client.news.feeds.find({ ...params }) -> Intercom.Newsfeed
@@ -6256,8 +10377,7 @@ await client.tickets.reply({
-You can create a new ticket. - +You can fetch the details of a single newsfeed
@@ -6272,20 +10392,11 @@ You can create a new ticket.
```typescript -await client.tickets.create({ - ticket_type_id: "1234", - contacts: [ - { - id: "667d61b78a68186f43bafe8d", - }, - ], - ticket_attributes: { - _default_title_: "example", - _default_description_: "there is a problem", - }, +await client.news.feeds.find({ + newsfeed_id: "123" }); -``` +```
@@ -6299,26 +10410,28 @@ await client.tickets.create({
-**request:** `Intercom.CreateTicketRequest` - +**request:** `Intercom.news.FindNewsFeedRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `FeedsClient.RequestOptions` +
+
-
client.tickets.get({ ...params }) -> Intercom.Ticket +## TicketTypes Attributes +
client.ticketTypes.attributes.create({ ...params }) -> Intercom.TicketTypeAttribute | undefined
@@ -6330,8 +10443,7 @@ await client.tickets.create({
-You can fetch the details of a single ticket. - +You can create a new attribute for a ticket type.
@@ -6346,11 +10458,15 @@ You can fetch the details of a single ticket.
```typescript -await client.tickets.get({ - ticket_id: "ticket_id", +await client.ticketTypes.attributes.create({ + ticket_type_id: "ticket_type_id", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false }); -``` +```
@@ -6364,26 +10480,27 @@ await client.tickets.get({
-**request:** `Intercom.FindTicketRequest` - +**request:** `Intercom.ticketTypes.CreateTicketTypeAttributeRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `AttributesClient.RequestOptions` +
+
-
client.tickets.update({ ...params }) -> Intercom.Ticket +
client.ticketTypes.attributes.update({ ...params }) -> Intercom.TicketTypeAttribute | undefined
@@ -6395,8 +10512,7 @@ await client.tickets.get({
-You can update a ticket. - +You can update an existing attribute for a ticket type.
@@ -6411,22 +10527,13 @@ You can update a ticket.
```typescript -await client.tickets.update({ - ticket_id: "ticket_id", - ticket_attributes: { - _default_title_: "example", - _default_description_: "there is a problem", - }, - state: "in_progress", - open: true, - snoozed_until: 1673609604, - assignment: { - admin_id: "991267883", - assignee_id: "991267885", - }, +await client.ticketTypes.attributes.update({ + ticket_type_id: "ticket_type_id", + attribute_id: "attribute_id", + description: "New Attribute Description" }); -``` +```
@@ -6440,26 +10547,28 @@ await client.tickets.update({
-**request:** `Intercom.UpdateTicketRequest` - +**request:** `Intercom.ticketTypes.UpdateTicketTypeAttributeRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `AttributesClient.RequestOptions` +
+
-
client.tickets.search({ ...params }) -> core.Page +## Admins +
client.unstable.admins.identifyAdmin() -> Intercom.AdminWithApp | undefined
@@ -6471,69 +10580,12 @@ await client.tickets.update({
-You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. - -To search for tickets, you send a `POST` request to `https://api.intercom.io/tickets/search`. - -This will accept a query object in the body which will define your filters. -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} - -### Nesting & Limitations - -You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiples there can be: - -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group - -### Accepted Fields - -Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foobar"`). - -| Field | Type | -| :-------------------- | :------------------------------------------------------------- | -| id | String | -| created_at | Date (UNIX timestamp) | -| updated_at | Date (UNIX timestamp) | -| _default_title_ | String | -| _default_description_ | String | -| category | String | -| ticket_type_id | String | -| contact_ids | String | -| teammate_ids | String | -| admin_assignee_id | String | -| team_assignee_id | String | -| open | Boolean | -| state | String | -| snoozed_until | Date (UNIX timestamp) | -| ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | - -### Accepted Operators - -{% admonition type="info" name="Searching based on `created_at`" %} -You may use the `<=` or `>=` operators to search by `created_at`. -{% /admonition %} -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). - -| Operator | Valid Types | Description | -| :------- | :---------------------------- | :--------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In Shortcut for `OR` queries Values most be in Array | -| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | -| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | -| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | +You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). +> 🚧 Single Sign On +> +> If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.
@@ -6548,46 +10600,9 @@ The table below shows the operators you can use to define how you want to search
```typescript -const response = await client.tickets.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, -}); -for await (const item of response) { - console.log(item); -} +await client.unstable.admins.identifyAdmin(); -// Or you can manually iterate page-by-page -const page = await client.tickets.search({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, -}); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -6601,28 +10616,19 @@ while (page.hasNextPage()) {
-**request:** `Intercom.SearchRequest` - -
-
- -
-
- -**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-## Visitors - -
client.visitors.find({ ...params }) -> Intercom.Visitor +
client.unstable.admins.setAwayAdmin({ ...params }) -> Intercom.Admin | undefined
@@ -6634,8 +10640,7 @@ while (page.hasNextPage()) {
-You can fetch the details of a single visitor. - +You can set an Admin as away for the Inbox.
@@ -6650,11 +10655,14 @@ You can fetch the details of a single visitor.
```typescript -await client.visitors.find({ - user_id: "user_id", +await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345 }); -``` +```
@@ -6668,26 +10676,27 @@ await client.visitors.find({
-**request:** `Intercom.FindVisitorRequest` - +**request:** `Intercom.unstable.SetAwayAdminRequest` +
-**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-
client.visitors.update({ ...params }) -> Intercom.Visitor +
client.unstable.admins.listActivityLogs({ ...params }) -> Intercom.ActivityLogList
@@ -6699,12 +10708,7 @@ await client.visitors.find({
-Sending a PUT request to `/visitors` will result in an update of an existing Visitor. - -**Option 1.** You can update a visitor by passing in the `user_id` of the visitor in the Request body. - -**Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body. - +You can get a log of activities by all admins in an app.
@@ -6719,12 +10723,12 @@ Sending a PUT request to `/visitors` will result in an update of an existing Vis
```typescript -await client.visitors.update({ - id: "667d61cc8a68186f43bafe95", - name: "Gareth Bale", +await client.unstable.admins.listActivityLogs({ + created_at_after: "1677253093", + created_at_before: "1677861493" }); -``` +```
@@ -6738,26 +10742,27 @@ await client.visitors.update({
-**request:** `Intercom.UpdateVisitorRequest` - +**request:** `Intercom.unstable.ListActivityLogsRequest` +
-**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-
client.visitors.mergeToContact({ ...params }) -> Intercom.Contact +
client.unstable.admins.listAdmins() -> Intercom.AdminList
@@ -6769,12 +10774,7 @@ await client.visitors.update({
-You can merge a Visitor to a Contact of role type `lead` or `user`. - -> 📘 What happens upon a visitor being converted? -> -> If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers. - +You can fetch a list of admins for a given workspace.
@@ -6789,18 +10789,9 @@ You can merge a Visitor to a Contact of role type `lead` or `user`.
```typescript -await client.visitors.mergeToContact({ - type: "user", - user: { - id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", - email: "foo@bar.com", - }, - visitor: { - user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", - }, -}); -``` +await client.unstable.admins.listAdmins(); +```
@@ -6814,28 +10805,19 @@ await client.visitors.mergeToContact({
-**request:** `Intercom.MergeVisitorToContactRequest` - -
-
- -
-
- -**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-## HelpCenters Collections - -
client.helpCenters.collections.list({ ...params }) -> core.Page +
client.unstable.admins.retrieveAdmin({ ...params }) -> Intercom.Admin | undefined
@@ -6847,10 +10829,7 @@ await client.visitors.mergeToContact({
-You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. - -Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first. - +You can retrieve the details of a single admin.
@@ -6865,18 +10844,11 @@ Collections will be returned in descending order on the `updated_at` attribute.
```typescript -const response = await client.helpCenters.collections.list(); -for await (const item of response) { - console.log(item); -} +await client.unstable.admins.retrieveAdmin({ + id: 1 +}); -// Or you can manually iterate page-by-page -const page = await client.helpCenters.collections.list(); -while (page.hasNextPage()) { - page = page.getNextPage(); -} ``` -
@@ -6890,26 +10862,28 @@ while (page.hasNextPage()) {
-**request:** `Intercom.helpCenters.ListCollectionsRequest` - +**request:** `Intercom.unstable.RetrieveAdminRequest` +
-**requestOptions:** `Collections.RequestOptions` - +**requestOptions:** `AdminsClient.RequestOptions` +
+
-
client.helpCenters.collections.create({ ...params }) -> Intercom.Collection +## AI Content +
client.unstable.aiContent.listContentImportSources() -> Intercom.ContentImportSourcesList
@@ -6921,8 +10895,7 @@ while (page.hasNextPage()) {
-You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.` - +You can retrieve a list of all content import sources for a workspace.
@@ -6937,11 +10910,9 @@ You can create a new collection by making a POST request to `https://api.interco
```typescript -await client.helpCenters.collections.create({ - name: "Thanks for everything", -}); -``` +await client.unstable.aiContent.listContentImportSources(); +```
@@ -6955,26 +10926,19 @@ await client.helpCenters.collections.create({
-**request:** `Intercom.helpCenters.CreateCollectionRequest` - -
-
- -
-
- -**requestOptions:** `Collections.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.helpCenters.collections.find({ ...params }) -> Intercom.Collection +
client.unstable.aiContent.createContentImportSource({ ...params }) -> Intercom.ContentImportSource
@@ -6986,8 +10950,7 @@ await client.helpCenters.collections.create({
-You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`. - +You can create a new content import source by sending a POST request to this endpoint.
@@ -7002,11 +10965,11 @@ You can fetch the details of a single collection by making a GET request to `htt
```typescript -await client.helpCenters.collections.find({ - collection_id: "123", +await client.unstable.aiContent.createContentImportSource({ + url: "https://www.example.com" }); -``` +```
@@ -7020,44 +10983,30 @@ await client.helpCenters.collections.find({
-**request:** `Intercom.helpCenters.FindCollectionRequest` - +**request:** `Intercom.unstable.CreateContentImportSourceRequest` +
-**requestOptions:** `Collections.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.helpCenters.collections.update({ ...params }) -> Intercom.Collection -
-
- -#### 📝 Description - -
-
- +
client.unstable.aiContent.getContentImportSource({ ...params }) -> Intercom.ContentImportSource
-You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`. - -
-
-
-
- #### 🔌 Usage
@@ -7067,12 +11016,11 @@ You can update the details of a single collection by making a PUT request to `ht
```typescript -await client.helpCenters.collections.update({ - collection_id: "123", - name: "Update collection name", +await client.unstable.aiContent.getContentImportSource({ + id: "id" }); -``` +```
@@ -7086,26 +11034,27 @@ await client.helpCenters.collections.update({
-**request:** `Intercom.helpCenters.UpdateCollectionRequest` - +**request:** `Intercom.unstable.GetContentImportSourceRequest` +
-**requestOptions:** `Collections.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.helpCenters.collections.delete({ ...params }) -> Intercom.DeletedCollectionObject +
client.unstable.aiContent.updateContentImportSource({ ...params }) -> Intercom.ContentImportSource
@@ -7117,8 +11066,7 @@ await client.helpCenters.collections.update({
-You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`. - +You can update an existing content import source.
@@ -7133,11 +11081,13 @@ You can delete a single collection by making a DELETE request to `https://api.in
```typescript -await client.helpCenters.collections.delete({ - collection_id: "123", +await client.unstable.aiContent.updateContentImportSource({ + id: "id", + sync_behavior: "api", + url: "https://www.example.com" }); -``` +```
@@ -7151,28 +11101,27 @@ await client.helpCenters.collections.delete({
-**request:** `Intercom.helpCenters.DeleteCollectionRequest` - +**request:** `Intercom.unstable.UpdateContentImportSourceRequest` +
-**requestOptions:** `Collections.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-## News Items - -
client.news.items.list() -> Intercom.PaginatedNewsItemResponse +
client.unstable.aiContent.deleteContentImportSource({ ...params }) -> void
@@ -7184,8 +11133,7 @@ await client.helpCenters.collections.delete({
-You can fetch a list of all news items - +You can delete a content import source by making a DELETE request this endpoint. This will also delete all external pages that were imported from this source.
@@ -7200,9 +11148,11 @@ You can fetch a list of all news items
```typescript -await client.news.items.list(); -``` +await client.unstable.aiContent.deleteContentImportSource({ + id: "id" +}); +```
@@ -7216,18 +11166,27 @@ await client.news.items.list();
-**requestOptions:** `Items.RequestOptions` +**request:** `Intercom.unstable.DeleteContentImportSourceRequest` + +
+
+ +
+
+**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.news.items.create({ ...params }) -> Intercom.NewsItem +
client.unstable.aiContent.listExternalPages() -> Intercom.ExternalPagesList
@@ -7239,8 +11198,7 @@ await client.news.items.list();
-You can create a news item - +You can retrieve a list of all external pages for a workspace.
@@ -7255,23 +11213,9 @@ You can create a news item
```typescript -await client.news.items.create({ - title: "Halloween is here!", - body: "

New costumes in store for this spooky season

", - sender_id: 991267734, - state: "live", - deliver_silently: true, - labels: ["Product", "Update", "New"], - reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], - newsfeed_assignments: [ - { - newsfeed_id: 53, - published_at: 1664638214, - }, - ], -}); -``` +await client.unstable.aiContent.listExternalPages(); +```
@@ -7285,26 +11229,19 @@ await client.news.items.create({
-**request:** `Intercom.NewsItemRequest` - -
-
- -
-
- -**requestOptions:** `Items.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.news.items.find({ ...params }) -> Intercom.NewsItem +
client.unstable.aiContent.createExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -7316,8 +11253,7 @@ await client.news.items.create({
-You can fetch the details of a single news item. - +You can create a new external page by sending a POST request to this endpoint. If an external page already exists with the specified source_id and external_id, it will be updated instead.
@@ -7332,11 +11268,15 @@ You can fetch the details of a single news item.
```typescript -await client.news.items.find({ - news_item_id: "123", +await client.unstable.aiContent.createExternalPage({ + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 44, + external_id: "abc1234" }); -``` +```
@@ -7350,29 +11290,44 @@ await client.news.items.find({
-**request:** `Intercom.news.FindNewsItemRequest` - +**request:** `Intercom.unstable.CreateExternalPageRequest` +
-**requestOptions:** `Items.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.news.items.update({ ...params }) -> Intercom.NewsItem +
client.unstable.aiContent.getExternalPage({ ...params }) -> Intercom.ExternalPage +
+
+ +#### 📝 Description + +
+
+
+You can retrieve an external page. +
+
+
+
+ #### 🔌 Usage
@@ -7382,17 +11337,11 @@ await client.news.items.find({
```typescript -await client.news.items.update({ - news_item_id: "123", - body: { - title: "Christmas is here!", - body: "

New gifts in store for the jolly season

", - sender_id: 991267745, - reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], - }, +await client.unstable.aiContent.getExternalPage({ + id: "id" }); -``` +```
@@ -7406,26 +11355,27 @@ await client.news.items.update({
-**request:** `Intercom.news.UpdateNewsItemRequest` - +**request:** `Intercom.unstable.GetExternalPageRequest` +
-**requestOptions:** `Items.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.news.items.delete({ ...params }) -> Intercom.DeletedObject +
client.unstable.aiContent.updateExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -7437,8 +11387,7 @@ await client.news.items.update({
-You can delete a single news item. - +You can update an existing external page (if it was created via the API).
@@ -7453,11 +11402,16 @@ You can delete a single news item.
```typescript -await client.news.items.delete({ - news_item_id: "123", +await client.unstable.aiContent.updateExternalPage({ + id: "id", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 47, + external_id: "5678" }); -``` +```
@@ -7471,28 +11425,27 @@ await client.news.items.delete({
-**request:** `Intercom.news.DeleteNewsItemRequest` - +**request:** `Intercom.unstable.UpdateExternalPageRequest` +
-**requestOptions:** `Items.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-## News Feeds - -
client.news.feeds.listItems({ ...params }) -> Intercom.PaginatedNewsItemResponse +
client.unstable.aiContent.deleteExternalPage({ ...params }) -> Intercom.ExternalPage
@@ -7504,8 +11457,7 @@ await client.news.items.delete({
-You can fetch a list of all news items that are live on a given newsfeed - +Sending a DELETE request for an external page will remove it from the content library UI and from being used for AI answers.
@@ -7520,11 +11472,11 @@ You can fetch a list of all news items that are live on a given newsfeed
```typescript -await client.news.feeds.listItems({ - newsfeed_id: "123", +await client.unstable.aiContent.deleteExternalPage({ + id: "id" }); -``` +```
@@ -7538,26 +11490,28 @@ await client.news.feeds.listItems({
-**request:** `Intercom.news.ListNewsFeedItemsRequest` - +**request:** `Intercom.unstable.DeleteExternalPageRequest` +
-**requestOptions:** `Feeds.RequestOptions` - +**requestOptions:** `AiContentClient.RequestOptions` +
+
-
client.news.feeds.list() -> Intercom.PaginatedNewsfeedResponse +## Articles +
client.unstable.articles.listArticles() -> Intercom.ArticleList
@@ -7569,8 +11523,11 @@ await client.news.feeds.listItems({
-You can fetch a list of all newsfeeds +You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. +> 📘 How are the articles sorted and ordered? +> +> Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.
@@ -7585,9 +11542,9 @@ You can fetch a list of all newsfeeds
```typescript -await client.news.feeds.list(); -``` +await client.unstable.articles.listArticles(); +```
@@ -7601,18 +11558,19 @@ await client.news.feeds.list();
-**requestOptions:** `Feeds.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.news.feeds.find({ ...params }) -> Intercom.Newsfeed +
client.unstable.articles.createArticle({ ...params }) -> Intercom.Article
@@ -7624,8 +11582,7 @@ await client.news.feeds.list();
-You can fetch the details of a single newsfeed - +You can create a new article by making a POST request to `https://api.intercom.io/articles`.
@@ -7640,11 +11597,11 @@ You can fetch the details of a single newsfeed
```typescript -await client.news.feeds.find({ - newsfeed_id: "123", +await client.unstable.articles.createArticle({ + "key": "value" }); -``` +```
@@ -7658,28 +11615,27 @@ await client.news.feeds.find({
-**request:** `Intercom.news.FindNewsFeedRequest` - +**request:** `unknown` +
-**requestOptions:** `Feeds.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-## TicketTypes Attributes - -
client.ticketTypes.attributes.create({ ...params }) -> Intercom.TicketTypeAttribute +
client.unstable.articles.retrieveArticle({ ...params }) -> Intercom.Article
@@ -7691,8 +11647,7 @@ await client.news.feeds.find({
-You can create a new attribute for a ticket type. - +You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`.
@@ -7707,15 +11662,11 @@ You can create a new attribute for a ticket type.
```typescript -await client.ticketTypes.attributes.create({ - ticket_type_id: "ticket_type_id", - name: "Attribute Title", - description: "Attribute Description", - data_type: "string", - required_to_create: false, +await client.unstable.articles.retrieveArticle({ + id: 1 }); -``` +```
@@ -7729,26 +11680,27 @@ await client.ticketTypes.attributes.create({
-**request:** `Intercom.ticketTypes.CreateTicketTypeAttributeRequest` - +**request:** `Intercom.unstable.RetrieveArticleRequest` +
-**requestOptions:** `Attributes.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.ticketTypes.attributes.update({ ...params }) -> Intercom.TicketTypeAttribute +
client.unstable.articles.deleteArticle({ ...params }) -> Intercom.DeletedArticleObject
@@ -7760,8 +11712,7 @@ await client.ticketTypes.attributes.create({
-You can update an existing attribute for a ticket type. - +You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`.
@@ -7776,13 +11727,11 @@ You can update an existing attribute for a ticket type.
```typescript -await client.ticketTypes.attributes.update({ - ticket_type_id: "ticket_type_id", - attribute_id: "attribute_id", - description: "New Attribute Description", +await client.unstable.articles.deleteArticle({ + id: 1 }); -``` +```
@@ -7796,28 +11745,27 @@ await client.ticketTypes.attributes.update({
-**request:** `Intercom.ticketTypes.UpdateTicketTypeAttributeRequest` - +**request:** `Intercom.unstable.DeleteArticleRequest` +
-**requestOptions:** `Attributes.RequestOptions` - +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-## Admins - -
client.unstable.admins.identifyAdmin() -> Intercom.AdminWithApp | undefined +
client.unstable.articles.searchArticles({ ...params }) -> Intercom.ArticleSearchResponse
@@ -7829,12 +11777,7 @@ await client.ticketTypes.attributes.update({
-You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). - -> 🚧 Single Sign On -> -> If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk. - +You can search for articles by making a GET request to `https://api.intercom.io/articles/search`.
@@ -7849,9 +11792,14 @@ You can view the currently authorised admin along with the embedded app object (
```typescript -await client.unstable.admins.identifyAdmin(); -``` +await client.unstable.articles.searchArticles({ + phrase: "Getting started", + state: "published", + help_center_id: 1, + highlight: true +}); +```
@@ -7865,18 +11813,28 @@ await client.unstable.admins.identifyAdmin();
-**requestOptions:** `Admins.RequestOptions` - +**request:** `Intercom.unstable.SearchArticlesRequest` + +
+
+ +
+
+ +**requestOptions:** `ArticlesClient.RequestOptions` +
+
-
client.unstable.admins.setAwayAdmin({ ...params }) -> Intercom.Admin | undefined +## Away Status Reasons +
client.unstable.awayStatusReasons.listAwayStatusReasons() -> Intercom.AwayStatusReason[]
@@ -7888,8 +11846,7 @@ await client.unstable.admins.identifyAdmin();
-You can set an Admin as away for the Inbox. - +Returns a list of all away status reasons configured for the workspace, including deleted ones.
@@ -7904,14 +11861,9 @@ You can set an Admin as away for the Inbox.
```typescript -await client.unstable.admins.setAwayAdmin({ - id: 1, - away_mode_enabled: true, - away_mode_reassign: true, - away_status_reason_id: 12345, -}); -``` +await client.unstable.awayStatusReasons.listAwayStatusReasons(); +```
@@ -7925,30 +11877,24 @@ await client.unstable.admins.setAwayAdmin({
-**request:** `Intercom.unstable.SetAwayAdminRequest` - -
-
- -
-
- -**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `AwayStatusReasonsClient.RequestOptions` +
+
-
client.unstable.admins.listActivityLogs({ ...params }) -> Intercom.ActivityLogList +## Unstable Export +
client.unstable.export.enqueueANewReportingDataExportJob({ ...params }) -> Intercom.PostExportReportingDataEnqueueResponse
-#### 📝 Description +#### 🔌 Usage
@@ -7956,14 +11902,21 @@ await client.unstable.admins.setAwayAdmin({
-You can get a log of activities by all admins in an app. +```typescript +await client.unstable.export.enqueueANewReportingDataExportJob({ + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000 +}); +```
-#### 🔌 Usage +#### ⚙️ Parameters
@@ -7971,19 +11924,31 @@ You can get a log of activities by all admins in an app.
-```typescript -await client.unstable.admins.listActivityLogs({ - created_at_after: "1677253093", - created_at_before: "1677861493", -}); -``` +**request:** `Intercom.unstable.PostExportReportingDataEnqueueRequest` + +
+
+ +
+
+**requestOptions:** `ExportClient.RequestOptions` +
-#### ⚙️ Parameters + +
+
+
+ +
client.unstable.export.listAvailableDatasetsAndAttributes() -> Intercom.GetExportReportingDataGetDatasetsResponse +
+
+ +#### 🔌 Usage
@@ -7991,26 +11956,37 @@ await client.unstable.admins.listActivityLogs({
-**request:** `Intercom.unstable.ListActivityLogsRequest` +```typescript +await client.unstable.export.listAvailableDatasetsAndAttributes(); +``` +
+
+#### ⚙️ Parameters +
-**requestOptions:** `Admins.RequestOptions` +
+
+**requestOptions:** `ExportClient.RequestOptions` +
+
-
client.unstable.admins.listAdmins() -> Intercom.AdminList +## Help Center +
client.unstable.helpCenter.listAllCollections() -> Intercom.CollectionList
@@ -8022,8 +11998,9 @@ await client.unstable.admins.listActivityLogs({
-You can fetch a list of admins for a given workspace. +You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. +Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.
@@ -8038,9 +12015,9 @@ You can fetch a list of admins for a given workspace.
```typescript -await client.unstable.admins.listAdmins(); -``` +await client.unstable.helpCenter.listAllCollections(); +```
@@ -8054,18 +12031,19 @@ await client.unstable.admins.listAdmins();
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.admins.retrieveAdmin({ ...params }) -> Intercom.Admin | undefined +
client.unstable.helpCenter.createCollection({ ...params }) -> Intercom.Collection
@@ -8077,8 +12055,7 @@ await client.unstable.admins.listAdmins();
-You can retrieve the details of a single admin. - +You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.`
@@ -8093,11 +12070,11 @@ You can retrieve the details of a single admin.
```typescript -await client.unstable.admins.retrieveAdmin({ - id: 1, +await client.unstable.helpCenter.createCollection({ + name: "Thanks for everything" }); -``` +```
@@ -8111,28 +12088,27 @@ await client.unstable.admins.retrieveAdmin({
-**request:** `Intercom.unstable.RetrieveAdminRequest` - +**request:** `Intercom.unstable.CreateCollectionRequest` +
-**requestOptions:** `Admins.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-## AI Content - -
client.unstable.aiContent.listContentImportSources() -> Intercom.ContentImportSourcesList +
client.unstable.helpCenter.retrieveCollection({ ...params }) -> Intercom.Collection
@@ -8144,8 +12120,7 @@ await client.unstable.admins.retrieveAdmin({
-You can retrieve a list of all content import sources for a workspace. - +You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`.
@@ -8160,9 +12135,11 @@ You can retrieve a list of all content import sources for a workspace.
```typescript -await client.unstable.aiContent.listContentImportSources(); -``` +await client.unstable.helpCenter.retrieveCollection({ + id: 1 +}); +```
@@ -8176,18 +12153,27 @@ await client.unstable.aiContent.listContentImportSources();
-**requestOptions:** `AiContent.RequestOptions` +**request:** `Intercom.unstable.RetrieveCollectionRequest` + +
+
+ +
+
+**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.aiContent.createContentImportSource({ ...params }) -> Intercom.ContentImportSource +
client.unstable.helpCenter.updateCollection({ ...params }) -> Intercom.Collection
@@ -8199,8 +12185,7 @@ await client.unstable.aiContent.listContentImportSources();
-You can create a new content import source by sending a POST request to this endpoint. - +You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`.
@@ -8215,11 +12200,12 @@ You can create a new content import source by sending a POST request to this end
```typescript -await client.unstable.aiContent.createContentImportSource({ - url: "https://www.example.com", +await client.unstable.helpCenter.updateCollection({ + id: 1, + name: "Update collection name" }); -``` +```
@@ -8233,29 +12219,44 @@ await client.unstable.aiContent.createContentImportSource({
-**request:** `Intercom.unstable.CreateContentImportSourceRequest` - +**request:** `Intercom.unstable.UpdateCollectionRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.aiContent.getContentImportSource({ ...params }) -> Intercom.ContentImportSource +
client.unstable.helpCenter.deleteCollection({ ...params }) -> Intercom.DeletedCollectionObject +
+
+ +#### 📝 Description + +
+
+
+You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`. +
+
+
+
+ #### 🔌 Usage
@@ -8265,11 +12266,11 @@ await client.unstable.aiContent.createContentImportSource({
```typescript -await client.unstable.aiContent.getContentImportSource({ - id: "id", +await client.unstable.helpCenter.deleteCollection({ + id: 1 }); -``` +```
@@ -8283,26 +12284,27 @@ await client.unstable.aiContent.getContentImportSource({
-**request:** `Intercom.unstable.GetContentImportSourceRequest` - +**request:** `Intercom.unstable.DeleteCollectionRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.aiContent.updateContentImportSource({ ...params }) -> Intercom.ContentImportSource +
client.unstable.helpCenter.retrieveHelpCenter({ ...params }) -> Intercom.HelpCenter
@@ -8314,8 +12316,7 @@ await client.unstable.aiContent.getContentImportSource({
-You can update an existing content import source. - +You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`.
@@ -8330,13 +12331,11 @@ You can update an existing content import source.
```typescript -await client.unstable.aiContent.updateContentImportSource({ - id: "id", - sync_behavior: "api", - url: "https://www.example.com", +await client.unstable.helpCenter.retrieveHelpCenter({ + id: 1 }); -``` +```
@@ -8350,26 +12349,27 @@ await client.unstable.aiContent.updateContentImportSource({
-**request:** `Intercom.unstable.UpdateContentImportSourceRequest` - +**request:** `Intercom.unstable.RetrieveHelpCenterRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.aiContent.deleteContentImportSource({ ...params }) -> void +
client.unstable.helpCenter.listHelpCenters() -> Intercom.HelpCenterList
@@ -8381,8 +12381,7 @@ await client.unstable.aiContent.updateContentImportSource({
-You can delete a content import source by making a DELETE request this endpoint. This will also delete all external pages that were imported from this source. - +You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`.
@@ -8397,11 +12396,9 @@ You can delete a content import source by making a DELETE request this endpoint.
```typescript -await client.unstable.aiContent.deleteContentImportSource({ - id: "id", -}); -``` +await client.unstable.helpCenter.listHelpCenters(); +```
@@ -8415,26 +12412,20 @@ await client.unstable.aiContent.deleteContentImportSource({
-**request:** `Intercom.unstable.DeleteContentImportSourceRequest` - -
-
- -
-
- -**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `HelpCenterClient.RequestOptions` +
+
-
client.unstable.aiContent.listExternalPages() -> Intercom.ExternalPagesList +## Internal Articles +
client.unstable.internalArticles.listInternalArticles() -> Intercom.InternalArticleList
@@ -8446,8 +12437,7 @@ await client.unstable.aiContent.deleteContentImportSource({
-You can retrieve a list of all external pages for a workspace. - +You can fetch a list of all internal articles by making a GET request to `https://api.intercom.io/internal_articles`.
@@ -8462,9 +12452,9 @@ You can retrieve a list of all external pages for a workspace.
```typescript -await client.unstable.aiContent.listExternalPages(); -``` +await client.unstable.internalArticles.listInternalArticles(); +```
@@ -8478,18 +12468,19 @@ await client.unstable.aiContent.listExternalPages();
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.unstable.aiContent.createExternalPage({ ...params }) -> Intercom.ExternalPage +
client.unstable.internalArticles.createInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -8501,8 +12492,7 @@ await client.unstable.aiContent.listExternalPages();
-You can create a new external page by sending a POST request to this endpoint. If an external page already exists with the specified source_id and external_id, it will be updated instead. - +You can create a new internal article by making a POST request to `https://api.intercom.io/internal_articles`.
@@ -8517,15 +12507,14 @@ You can create a new external page by sending a POST request to this endpoint. I
```typescript -await client.unstable.aiContent.createExternalPage({ - title: "Test", - html: "

Test

", - url: "https://www.example.com", - source_id: 44, - external_id: "abc1234", +await client.unstable.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252 }); -``` +```
@@ -8539,26 +12528,27 @@ await client.unstable.aiContent.createExternalPage({
-**request:** `Intercom.unstable.CreateExternalPageRequest` - +**request:** `Intercom.CreateInternalArticleRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.unstable.aiContent.getExternalPage({ ...params }) -> Intercom.ExternalPage +
client.unstable.internalArticles.retrieveInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -8570,8 +12560,7 @@ await client.unstable.aiContent.createExternalPage({
-You can retrieve an external page. - +You can fetch the details of a single internal article by making a GET request to `https://api.intercom.io/internal_articles/`.
@@ -8586,11 +12575,11 @@ You can retrieve an external page.
```typescript -await client.unstable.aiContent.getExternalPage({ - id: "id", +await client.unstable.internalArticles.retrieveInternalArticle({ + id: 1 }); -``` +```
@@ -8604,26 +12593,27 @@ await client.unstable.aiContent.getExternalPage({
-**request:** `Intercom.unstable.GetExternalPageRequest` - +**request:** `Intercom.unstable.RetrieveInternalArticleRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.unstable.aiContent.updateExternalPage({ ...params }) -> Intercom.ExternalPage +
client.unstable.internalArticles.updateInternalArticle({ ...params }) -> Intercom.InternalArticle
@@ -8635,8 +12625,7 @@ await client.unstable.aiContent.getExternalPage({
-You can update an existing external page (if it was created via the API). - +You can update the details of a single internal article by making a PUT request to `https://api.intercom.io/internal_articles/`.
@@ -8651,16 +12640,13 @@ You can update an existing external page (if it was created via the API).
```typescript -await client.unstable.aiContent.updateExternalPage({ - id: "id", - title: "Test", - html: "

Test

", - url: "https://www.example.com", - source_id: 47, - external_id: "5678", +await client.unstable.internalArticles.updateInternalArticle({ + id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

" }); -``` +```
@@ -8674,26 +12660,27 @@ await client.unstable.aiContent.updateExternalPage({
-**request:** `Intercom.unstable.UpdateExternalPageRequest` - +**request:** `Intercom.unstable.UpdateInternalArticleRequestBody` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.unstable.aiContent.deleteExternalPage({ ...params }) -> Intercom.ExternalPage +
client.unstable.internalArticles.deleteInternalArticle({ ...params }) -> Intercom.DeletedInternalArticleObject
@@ -8705,8 +12692,7 @@ await client.unstable.aiContent.updateExternalPage({
-Sending a DELETE request for an external page will remove it from the content library UI and from being used for AI answers. - +You can delete a single internal article by making a DELETE request to `https://api.intercom.io/internal_articles/`.
@@ -8721,11 +12707,11 @@ Sending a DELETE request for an external page will remove it from the content li
```typescript -await client.unstable.aiContent.deleteExternalPage({ - id: "id", +await client.unstable.internalArticles.deleteInternalArticle({ + id: 1 }); -``` +```
@@ -8739,28 +12725,27 @@ await client.unstable.aiContent.deleteExternalPage({
-**request:** `Intercom.unstable.DeleteExternalPageRequest` - +**request:** `Intercom.unstable.DeleteInternalArticleRequest` +
-**requestOptions:** `AiContent.RequestOptions` - +**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-## Articles - -
client.unstable.articles.listArticles() -> Intercom.ArticleList +
client.unstable.internalArticles.searchInternalArticles({ ...params }) -> Intercom.InternalArticleSearchResponse
@@ -8769,15 +12754,10 @@ await client.unstable.aiContent.deleteExternalPage({
-
-
- -You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. - -> 📘 How are the articles sorted and ordered? -> -> Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first. +
+
+You can search for internal articles by making a GET request to `https://api.intercom.io/internal_articles/search`.
@@ -8792,9 +12772,11 @@ You can fetch a list of all articles by making a GET request to `https://api.int
```typescript -await client.unstable.articles.listArticles(); -``` +await client.unstable.internalArticles.searchInternalArticles({ + folder_id: "folder_id" +}); +```
@@ -8808,18 +12790,28 @@ await client.unstable.articles.listArticles();
-**requestOptions:** `Articles.RequestOptions` +**request:** `Intercom.unstable.SearchInternalArticlesRequest` + +
+
+ +
+
+**requestOptions:** `InternalArticlesClient.RequestOptions` +
+
-
client.unstable.articles.createArticle({ ...params }) -> Intercom.Article +## Companies +
client.unstable.companies.retrieveCompany({ ...params }) -> Intercom.CompanyList
@@ -8831,8 +12823,17 @@ await client.unstable.articles.listArticles();
-You can create a new article by making a POST request to `https://api.intercom.io/articles`. +You can fetch a single company by passing in `company_id` or `name`. + + `https://api.intercom.io/companies?name={name}` + + `https://api.intercom.io/companies?company_id={company_id}` + +You can fetch all companies and filter by `segment_id` or `tag_id` as a query parameter. + `https://api.intercom.io/companies?tag_id={tag_id}` + + `https://api.intercom.io/companies?segment_id={segment_id}`
@@ -8847,11 +12848,16 @@ You can create a new article by making a POST request to `https://api.intercom.i
```typescript -await client.unstable.articles.createArticle({ - key: "value", +await client.unstable.companies.retrieveCompany({ + name: "my company", + company_id: "12345", + tag_id: "678910", + segment_id: "98765", + page: 1, + per_page: 1 }); -``` +```
@@ -8865,26 +12871,27 @@ await client.unstable.articles.createArticle({
-**request:** `unknown` - +**request:** `Intercom.unstable.RetrieveCompanyRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.articles.retrieveArticle({ ...params }) -> Intercom.Article +
client.unstable.companies.createOrUpdateCompany({ ...params }) -> Intercom.Company
@@ -8896,8 +12903,15 @@ await client.unstable.articles.createArticle({
-You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`. +You can create or update a company. +Companies will be only visible in Intercom when there is at least one associated user. + +Companies are looked up via `company_id` in a `POST` request, if not found via `company_id`, the new company will be created, if found, that company will be updated. + +{% admonition type="warning" name="Using `company_id`" %} + You can set a unique `company_id` value when creating a company. However, it is not possible to update `company_id`. Be sure to set a unique value once upon creation of the company. +{% /admonition %}
@@ -8912,11 +12926,11 @@ You can fetch the details of a single article by making a GET request to `https:
```typescript -await client.unstable.articles.retrieveArticle({ - id: 1, +await client.unstable.companies.createOrUpdateCompany({ + "key": "value" }); -``` +```
@@ -8930,26 +12944,27 @@ await client.unstable.articles.retrieveArticle({
-**request:** `Intercom.unstable.RetrieveArticleRequest` - +**request:** `unknown` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.articles.deleteArticle({ ...params }) -> Intercom.DeletedArticleObject +
client.unstable.companies.retrieveACompanyById({ ...params }) -> Intercom.Company
@@ -8961,8 +12976,7 @@ await client.unstable.articles.retrieveArticle({
-You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`. - +You can fetch a single company.
@@ -8977,11 +12991,11 @@ You can delete a single article by making a DELETE request to `https://api.inter
```typescript -await client.unstable.articles.deleteArticle({ - id: 1, +await client.unstable.companies.retrieveACompanyById({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -8995,26 +13009,27 @@ await client.unstable.articles.deleteArticle({
-**request:** `Intercom.unstable.DeleteArticleRequest` - +**request:** `Intercom.unstable.RetrieveACompanyByIdRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.articles.searchArticles({ ...params }) -> Intercom.ArticleSearchResponse +
client.unstable.companies.updateCompany({ ...params }) -> Intercom.Company
@@ -9026,8 +13041,11 @@ await client.unstable.articles.deleteArticle({
-You can search for articles by making a GET request to `https://api.intercom.io/articles/search`. +You can update a single company using the Intercom provisioned `id`. +{% admonition type="warning" name="Using `company_id`" %} + When updating a company it is not possible to update `company_id`. This can only be set once upon creation of the company. +{% /admonition %}
@@ -9042,12 +13060,11 @@ You can search for articles by making a GET request to `https://api.intercom.io/
```typescript -await client.unstable.articles.searchArticles({ - phrase: "Getting started", - state: "published", +await client.unstable.companies.updateCompany({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -9061,28 +13078,27 @@ await client.unstable.articles.searchArticles({
-**request:** `Intercom.unstable.SearchArticlesRequest` - +**request:** `Intercom.unstable.UpdateCompanyRequest` +
-**requestOptions:** `Articles.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-## Away Status Reasons - -
client.unstable.awayStatusReasons.listAwayStatusReasons() -> Intercom.AwayStatusReason[] +
client.unstable.companies.deleteCompany({ ...params }) -> Intercom.DeletedCompanyObject
@@ -9094,8 +13110,7 @@ await client.unstable.articles.searchArticles({
-Returns a list of all away status reasons configured for the workspace, including deleted ones. - +You can delete a single company.
@@ -9110,9 +13125,11 @@ Returns a list of all away status reasons configured for the workspace, includin
```typescript -await client.unstable.awayStatusReasons.listAwayStatusReasons(); -``` +await client.unstable.companies.deleteCompany({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" +}); +```
@@ -9126,23 +13143,44 @@ await client.unstable.awayStatusReasons.listAwayStatusReasons();
-**requestOptions:** `AwayStatusReasons.RequestOptions` +**request:** `Intercom.unstable.DeleteCompanyRequest` + +
+
+ +
+
+**requestOptions:** `CompaniesClient.RequestOptions` +
+
-## Unstable Export +
client.unstable.companies.listAttachedContacts({ ...params }) -> Intercom.CompanyAttachedContacts +
+
+ +#### 📝 Description + +
+
-
client.unstable.export.enqueueANewReportingDataExportJob({ ...params }) -> Intercom.PostExportReportingDataEnqueueResponse
+You can fetch a list of all contacts that belong to a company. +
+
+
+
+ #### 🔌 Usage
@@ -9152,14 +13190,11 @@ await client.unstable.awayStatusReasons.listAwayStatusReasons();
```typescript -await client.unstable.export.enqueueANewReportingDataExportJob({ - dataset_id: "conversation", - attribute_ids: ["conversation.id", "conversation.first_user_conversation_part_created_at"], - start_time: 1717490000, - end_time: 1717510000, +await client.unstable.companies.listAttachedContacts({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -9173,29 +13208,44 @@ await client.unstable.export.enqueueANewReportingDataExportJob({
-**request:** `Intercom.unstable.PostExportReportingDataEnqueueRequest` - +**request:** `Intercom.unstable.ListAttachedContactsRequest` +
-**requestOptions:** `Export.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.export.listAvailableDatasetsAndAttributes() -> Intercom.GetExportReportingDataGetDatasetsResponse +
client.unstable.companies.listAttachedSegmentsForCompanies({ ...params }) -> Intercom.CompanyAttachedSegments +
+
+ +#### 📝 Description +
+
+
+ +You can fetch a list of all segments that belong to a company. +
+
+
+
+ #### 🔌 Usage
@@ -9205,9 +13255,11 @@ await client.unstable.export.enqueueANewReportingDataExportJob({
```typescript -await client.unstable.export.listAvailableDatasetsAndAttributes(); -``` +await client.unstable.companies.listAttachedSegmentsForCompanies({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" +}); +```
@@ -9221,20 +13273,27 @@ await client.unstable.export.listAvailableDatasetsAndAttributes();
-**requestOptions:** `Export.RequestOptions` +**request:** `Intercom.unstable.ListAttachedSegmentsForCompaniesRequest` + +
+
+ +
+
+**requestOptions:** `CompaniesClient.RequestOptions` +
+
-## Help Center - -
client.unstable.helpCenter.listAllCollections() -> Intercom.CollectionList +
client.unstable.companies.listAllCompanies({ ...params }) -> Intercom.CompanyList
@@ -9246,10 +13305,15 @@ await client.unstable.export.listAvailableDatasetsAndAttributes();
-You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. +You can list companies. The company list is sorted by the `last_request_at` field and by default is ordered descending, most recently requested first. -Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first. +Note that the API does not include companies who have no associated users in list responses. +When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the [Scroll API](https://developers.intercom.com/reference#iterating-over-all-companies). +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %}
@@ -9264,9 +13328,13 @@ Collections will be returned in descending order on the `updated_at` attribute.
```typescript -await client.unstable.helpCenter.listAllCollections(); -``` +await client.unstable.companies.listAllCompanies({ + page: 1, + per_page: 1, + order: "desc" +}); +```
@@ -9280,18 +13348,27 @@ await client.unstable.helpCenter.listAllCollections();
-**requestOptions:** `HelpCenter.RequestOptions` +**request:** `Intercom.unstable.ListAllCompaniesRequest` + +
+
+ +
+
+**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.helpCenter.createCollection({ ...params }) -> Intercom.Collection +
client.unstable.companies.scrollOverAllCompanies({ ...params }) -> Intercom.CompanyScroll | undefined
@@ -9303,8 +13380,21 @@ await client.unstable.helpCenter.listAllCollections();
-You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.` + The `list all companies` functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + +- Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app. +- If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail +- If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire +{% admonition type="info" name="Scroll Parameter" %} + You can get the first page of companies by simply sending a GET request to the scroll endpoint. + For subsequent requests you will need to use the scroll parameter from the response. +{% /admonition %} +{% admonition type="danger" name="Scroll network timeouts" %} + Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + "Request failed due to an internal network error. Please restart the scroll operation." + If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. +{% /admonition %}
@@ -9319,11 +13409,11 @@ You can create a new collection by making a POST request to `https://api.interco
```typescript -await client.unstable.helpCenter.createCollection({ - name: "Thanks for everything", +await client.unstable.companies.scrollOverAllCompanies({ + scroll_param: "scroll_param" }); -``` +```
@@ -9337,26 +13427,27 @@ await client.unstable.helpCenter.createCollection({
-**request:** `Intercom.unstable.CreateCollectionRequest` - +**request:** `Intercom.unstable.ScrollOverAllCompaniesRequest` +
-**requestOptions:** `HelpCenter.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.helpCenter.retrieveCollection({ ...params }) -> Intercom.Collection +
client.unstable.companies.attachContactToACompany({ ...params }) -> Intercom.Company
@@ -9368,8 +13459,7 @@ await client.unstable.helpCenter.createCollection({
-You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`. - +You can attach a company to a single contact.
@@ -9384,11 +13474,12 @@ You can fetch the details of a single collection by making a GET request to `htt
```typescript -await client.unstable.helpCenter.retrieveCollection({ - id: 1, +await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "6762f09a1bb69f9f2193bb34" }); -``` +```
@@ -9402,26 +13493,27 @@ await client.unstable.helpCenter.retrieveCollection({
-**request:** `Intercom.unstable.RetrieveCollectionRequest` - +**request:** `Intercom.unstable.AttachContactToACompanyRequest` +
-**requestOptions:** `HelpCenter.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.helpCenter.updateCollection({ ...params }) -> Intercom.Collection +
client.unstable.companies.detachContactFromACompany({ ...params }) -> Intercom.Company
@@ -9433,8 +13525,7 @@ await client.unstable.helpCenter.retrieveCollection({
-You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`. - +You can detach a company from a single contact.
@@ -9449,12 +13540,12 @@ You can update the details of a single collection by making a PUT request to `ht
```typescript -await client.unstable.helpCenter.updateCollection({ - id: 1, - name: "Update collection name", +await client.unstable.companies.detachContactFromACompany({ + contact_id: "58a430d35458202d41b1e65b", + id: "58a430d35458202d41b1e65b" }); -``` +```
@@ -9468,26 +13559,28 @@ await client.unstable.helpCenter.updateCollection({
-**request:** `Intercom.unstable.UpdateCollectionRequest` - +**request:** `Intercom.unstable.DetachContactFromACompanyRequest` +
-**requestOptions:** `HelpCenter.RequestOptions` - +**requestOptions:** `CompaniesClient.RequestOptions` +
+
-
client.unstable.helpCenter.deleteCollection({ ...params }) -> Intercom.DeletedCollectionObject +## Notes +
client.unstable.notes.listCompanyNotes({ ...params }) -> Intercom.NoteList
@@ -9499,8 +13592,7 @@ await client.unstable.helpCenter.updateCollection({
-You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`. - +You can fetch a list of notes that are associated to a company.
@@ -9515,11 +13607,11 @@ You can delete a single collection by making a DELETE request to `https://api.in
```typescript -await client.unstable.helpCenter.deleteCollection({ - id: 1, +await client.unstable.notes.listCompanyNotes({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" }); -``` +```
@@ -9533,26 +13625,27 @@ await client.unstable.helpCenter.deleteCollection({
-**request:** `Intercom.unstable.DeleteCollectionRequest` - +**request:** `Intercom.unstable.ListCompanyNotesRequest` +
-**requestOptions:** `HelpCenter.RequestOptions` - +**requestOptions:** `NotesClient.RequestOptions` +
+
-
client.unstable.helpCenter.retrieveHelpCenter({ ...params }) -> Intercom.HelpCenter +
client.unstable.notes.listNotes({ ...params }) -> Intercom.NoteList
@@ -9564,8 +13657,7 @@ await client.unstable.helpCenter.deleteCollection({
-You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`. - +You can fetch a list of notes that are associated to a contact.
@@ -9580,11 +13672,11 @@ You can fetch the details of a single Help Center by making a GET request to `ht
```typescript -await client.unstable.helpCenter.retrieveHelpCenter({ - id: 1, +await client.unstable.notes.listNotes({ + id: 1 }); -``` +```
@@ -9598,26 +13690,27 @@ await client.unstable.helpCenter.retrieveHelpCenter({
-**request:** `Intercom.unstable.RetrieveHelpCenterRequest` - +**request:** `Intercom.unstable.ListNotesRequest` +
-**requestOptions:** `HelpCenter.RequestOptions` - +**requestOptions:** `NotesClient.RequestOptions` +
+
-
client.unstable.helpCenter.listHelpCenters() -> Intercom.HelpCenterList +
client.unstable.notes.createNote({ ...params }) -> Intercom.Note
@@ -9629,8 +13722,7 @@ await client.unstable.helpCenter.retrieveHelpCenter({
-You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`. - +You can add a note to a single contact.
@@ -9644,10 +13736,15 @@ You can list all Help Centers by making a GET request to `https://api.intercom.i
-```typescript -await client.unstable.helpCenter.listHelpCenters(); +```typescript +await client.unstable.notes.createNote({ + id: 1, + body: "Hello", + contact_id: "6762f0ad1bb69f9f2193bb62", + admin_id: "123" +}); + ``` -
@@ -9661,20 +13758,27 @@ await client.unstable.helpCenter.listHelpCenters();
-**requestOptions:** `HelpCenter.RequestOptions` +**request:** `Intercom.unstable.CreateNoteRequest` + +
+
+ +
+
+**requestOptions:** `NotesClient.RequestOptions` +
+
-## Companies - -
client.unstable.companies.retrieveCompany({ ...params }) -> Intercom.CompanyList +
client.unstable.notes.retrieveNote({ ...params }) -> Intercom.Note
@@ -9686,18 +13790,7 @@ await client.unstable.helpCenter.listHelpCenters();
-You can fetch a single company by passing in `company_id` or `name`. - -`https://api.intercom.io/companies?name={name}` - -`https://api.intercom.io/companies?company_id={company_id}` - -You can fetch all companies and filter by `segment_id` or `tag_id` as a query parameter. - -`https://api.intercom.io/companies?tag_id={tag_id}` - -`https://api.intercom.io/companies?segment_id={segment_id}` - +You can fetch the details of a single note.
@@ -9712,14 +13805,11 @@ You can fetch all companies and filter by `segment_id` or `tag_id` as a query pa
```typescript -await client.unstable.companies.retrieveCompany({ - name: "my company", - company_id: "12345", - tag_id: "678910", - segment_id: "98765", +await client.unstable.notes.retrieveNote({ + id: 1 }); -``` +```
@@ -9733,26 +13823,28 @@ await client.unstable.companies.retrieveCompany({
-**request:** `Intercom.unstable.RetrieveCompanyRequest` - +**request:** `Intercom.unstable.RetrieveNoteRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `NotesClient.RequestOptions` +
+
-
client.unstable.companies.createOrUpdateCompany({ ...params }) -> Intercom.Company +## Contacts +
client.unstable.contacts.listCompaniesForAContact({ ...params }) -> Intercom.ContactAttachedCompanies
@@ -9764,16 +13856,7 @@ await client.unstable.companies.retrieveCompany({
-You can create or update a company. - -Companies will be only visible in Intercom when there is at least one associated user. - -Companies are looked up via `company_id` in a `POST` request, if not found via `company_id`, the new company will be created, if found, that company will be updated. - -{% admonition type="warning" name="Using `company_id`" %} -You can set a unique `company_id` value when creating a company. However, it is not possible to update `company_id`. Be sure to set a unique value once upon creation of the company. -{% /admonition %} - +You can fetch a list of companies that are associated to a contact.
@@ -9788,11 +13871,11 @@ You can set a unique `company_id` value when creating a company. However, it is
```typescript -await client.unstable.companies.createOrUpdateCompany({ - key: "value", +await client.unstable.contacts.listCompaniesForAContact({ + id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -9806,26 +13889,27 @@ await client.unstable.companies.createOrUpdateCompany({
-**request:** `unknown` - +**request:** `Intercom.unstable.ListCompaniesForAContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.retrieveACompanyById({ ...params }) -> Intercom.Company +
client.unstable.contacts.listSegmentsForAContact({ ...params }) -> Intercom.ContactSegments
@@ -9837,8 +13921,7 @@ await client.unstable.companies.createOrUpdateCompany({
-You can fetch a single company. - +You can fetch a list of segments that are associated to a contact.
@@ -9853,11 +13936,11 @@ You can fetch a single company.
```typescript -await client.unstable.companies.retrieveACompanyById({ - id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.unstable.contacts.listSegmentsForAContact({ + contact_id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -9871,26 +13954,27 @@ await client.unstable.companies.retrieveACompanyById({
-**request:** `Intercom.unstable.RetrieveACompanyByIdRequest` - +**request:** `Intercom.unstable.ListSegmentsForAContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.updateCompany({ ...params }) -> Intercom.Company +
client.unstable.contacts.listSubscriptionsForAContact({ ...params }) -> Intercom.SubscriptionTypeList
@@ -9902,12 +13986,13 @@ await client.unstable.companies.retrieveACompanyById({
-You can update a single company using the Intercom provisioned `id`. +You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. +This will return a list of Subscription Type objects that the contact is associated with. -{% admonition type="warning" name="Using `company_id`" %} -When updating a company it is not possible to update `company_id`. This can only be set once upon creation of the company. -{% /admonition %} +The data property will show a combined list of: + 1.Opt-out subscription types that the user has opted-out from. + 2.Opt-in subscription types that the user has opted-in to receiving.
@@ -9922,11 +14007,11 @@ When updating a company it is not possible to update `company_id`. This can only
```typescript -await client.unstable.companies.updateCompany({ - id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.unstable.contacts.listSubscriptionsForAContact({ + contact_id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -9940,26 +14025,27 @@ await client.unstable.companies.updateCompany({
-**request:** `Intercom.unstable.UpdateCompanyRequest` - +**request:** `Intercom.unstable.ListSubscriptionsForAContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.deleteCompany({ ...params }) -> Intercom.DeletedCompanyObject +
client.unstable.contacts.listTagsForAContact({ ...params }) -> Intercom.TagList
@@ -9971,8 +14057,7 @@ await client.unstable.companies.updateCompany({
-You can delete a single company. - +You can fetch a list of all tags that are attached to a specific contact.
@@ -9987,11 +14072,11 @@ You can delete a single company.
```typescript -await client.unstable.companies.deleteCompany({ - id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.unstable.contacts.listTagsForAContact({ + contact_id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -10005,26 +14090,27 @@ await client.unstable.companies.deleteCompany({
-**request:** `Intercom.unstable.DeleteCompanyRequest` - +**request:** `Intercom.unstable.ListTagsForAContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.listAttachedContacts({ ...params }) -> Intercom.CompanyAttachedContacts +
client.unstable.contacts.showContact({ ...params }) -> Intercom.ShowContactResponse
@@ -10036,8 +14122,7 @@ await client.unstable.companies.deleteCompany({
-You can fetch a list of all contacts that belong to a company. - +You can fetch the details of a single contact.
@@ -10052,11 +14137,11 @@ You can fetch a list of all contacts that belong to a company.
```typescript -await client.unstable.companies.listAttachedContacts({ - id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.unstable.contacts.showContact({ + id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -10070,26 +14155,27 @@ await client.unstable.companies.listAttachedContacts({
-**request:** `Intercom.unstable.ListAttachedContactsRequest` - +**request:** `Intercom.unstable.ShowContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.listAttachedSegmentsForCompanies({ ...params }) -> Intercom.CompanyAttachedSegments +
client.unstable.contacts.updateContact({ ...params }) -> Intercom.UpdateContactResponse
@@ -10101,8 +14187,13 @@ await client.unstable.companies.listAttachedContacts({
-You can fetch a list of all segments that belong to a company. +You can update an existing contact (ie. user or lead). +{% admonition type="info" %} + This endpoint handles both **contact updates** and **custom object associations**. + + See _`update a contact with an association to a custom object instance`_ in the request/response examples to see the custom object association format. +{% /admonition %}
@@ -10117,11 +14208,13 @@ You can fetch a list of all segments that belong to a company.
```typescript -await client.unstable.companies.listAttachedSegmentsForCompanies({ - id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", +await client.unstable.contacts.updateContact({ + id: "63a07ddf05a32042dffac965", + email: "joebloggs@intercom.io", + name: "joe bloggs" }); -``` +```
@@ -10135,26 +14228,27 @@ await client.unstable.companies.listAttachedSegmentsForCompanies({
-**request:** `Intercom.unstable.ListAttachedSegmentsForCompaniesRequest` - +**request:** `Intercom.unstable.UpdateContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.listAllCompanies({ ...params }) -> Intercom.CompanyList +
client.unstable.contacts.deleteContact({ ...params }) -> Intercom.ContactDeleted
@@ -10166,16 +14260,7 @@ await client.unstable.companies.listAttachedSegmentsForCompanies({
-You can list companies. The company list is sorted by the `last_request_at` field and by default is ordered descending, most recently requested first. - -Note that the API does not include companies who have no associated users in list responses. - -When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the [Scroll API](https://developers.intercom.com/reference#iterating-over-all-companies). -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} - +You can delete a single contact.
@@ -10190,11 +14275,11 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -await client.unstable.companies.listAllCompanies({ - order: "desc", +await client.unstable.contacts.deleteContact({ + id: "id" }); -``` +```
@@ -10208,26 +14293,27 @@ await client.unstable.companies.listAllCompanies({
-**request:** `Intercom.unstable.ListAllCompaniesRequest` - +**request:** `Intercom.unstable.DeleteContactRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.scrollOverAllCompanies({ ...params }) -> Intercom.CompanyScroll | undefined +
client.unstable.contacts.mergeContact({ ...params }) -> Intercom.MergeContactResponse
@@ -10239,22 +14325,7 @@ await client.unstable.companies.listAllCompanies({
- The `list all companies` functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. - -- Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app. -- If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail -- If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire - -{% admonition type="info" name="Scroll Parameter" %} -You can get the first page of companies by simply sending a GET request to the scroll endpoint. -For subsequent requests you will need to use the scroll parameter from the response. -{% /admonition %} -{% admonition type="danger" name="Scroll network timeouts" %} -Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: -"Request failed due to an internal network error. Please restart the scroll operation." -If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. -{% /admonition %} - +You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`.
@@ -10269,9 +14340,12 @@ If this happens, you will need to restart your scroll query: It is not possible
```typescript -await client.unstable.companies.scrollOverAllCompanies(); -``` +await client.unstable.contacts.mergeContact({ + from: "6762f0d51bb69f9f2193bb7f", + into: "6762f0d51bb69f9f2193bb80" +}); +```
@@ -10285,26 +14359,27 @@ await client.unstable.companies.scrollOverAllCompanies();
-**request:** `Intercom.unstable.ScrollOverAllCompaniesRequest` - +**request:** `Intercom.unstable.MergeContactsRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.attachContactToACompany({ ...params }) -> Intercom.Company +
client.unstable.contacts.searchContacts({ ...params }) -> Intercom.ContactList
@@ -10316,8 +14391,106 @@ await client.unstable.companies.scrollOverAllCompanies();
-You can attach a company to a single contact. +You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + +To search for contacts, you need to send a `POST` request to `https://api.intercom.io/contacts/search`. + +This will accept a query object in the body which will define your filters in order to search for contacts. + +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `50` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} +### Contact Creation Delay + +If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters. + +### Nesting & Limitations + +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiple's there can be: +* There's a limit of max 2 nested filters +* There's a limit of max 15 filters for each AND or OR group + +### Searching for Timestamp Fields + +All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. +For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. +If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). +This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly. + +### Accepted Fields + +Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). + +| Field | Type | +| ---------------------------------- | ------------------------------ | +| id | String | +| role | String
Accepts user or lead | +| name | String | +| avatar | String | +| owner_id | Integer | +| email | String | +| email_domain | String | +| phone | String | +| formatted_phone | String | +| external_id | String | +| created_at | Date (UNIX Timestamp) | +| signed_up_at | Date (UNIX Timestamp) | +| updated_at | Date (UNIX Timestamp) | +| last_seen_at | Date (UNIX Timestamp) | +| last_contacted_at | Date (UNIX Timestamp) | +| last_replied_at | Date (UNIX Timestamp) | +| last_email_opened_at | Date (UNIX Timestamp) | +| last_email_clicked_at | Date (UNIX Timestamp) | +| language_override | String | +| browser | String | +| browser_language | String | +| os | String | +| location.country | String | +| location.region | String | +| location.city | String | +| unsubscribed_from_emails | Boolean | +| marked_email_as_spam | Boolean | +| has_hard_bounced | Boolean | +| ios_last_seen_at | Date (UNIX Timestamp) | +| ios_app_version | String | +| ios_device | String | +| ios_app_device | String | +| ios_os_version | String | +| ios_app_name | String | +| ios_sdk_version | String | +| android_last_seen_at | Date (UNIX Timestamp) | +| android_app_version | String | +| android_device | String | +| android_app_name | String | +| andoid_sdk_version | String | +| segment_id | String | +| tag_id | String | +| custom_attributes.{attribute_name} | String | + +### Accepted Operators + +{% admonition type="warning" name="Searching based on `created_at`" %} + You cannot use the `<=` or `>=` operators to search by `created_at`. +{% /admonition %} + +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). +| Operator | Valid Types | Description | +| :------- | :------------------------------- | :--------------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In
Shortcut for `OR` queries
Values must be in Array | +| NIN | All | Not In
Shortcut for `OR !` queries
Values must be in Array | +| > | Integer
Date (UNIX Timestamp) | Greater than | +| < | Integer
Date (UNIX Timestamp) | Lower than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With |
@@ -10331,13 +14504,22 @@ You can attach a company to a single contact.
-```typescript -await client.unstable.companies.attachContactToACompany({ - id: "id", - company_id: "6762f09a1bb69f9f2193bb34", +```typescript +await client.unstable.contacts.searchContacts({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } }); -``` +```
@@ -10351,26 +14533,27 @@ await client.unstable.companies.attachContactToACompany({
-**request:** `Intercom.unstable.AttachContactToACompanyRequest` - +**request:** `Intercom.SearchRequest` +
-**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.companies.detachContactFromACompany({ ...params }) -> Intercom.Company +
client.unstable.contacts.listContacts() -> Intercom.ContactList
@@ -10382,8 +14565,11 @@ await client.unstable.companies.attachContactToACompany({
-You can detach a company from a single contact. - +You can fetch a list of all contacts (ie. users or leads) in your workspace. +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `50` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %}
@@ -10398,12 +14584,9 @@ You can detach a company from a single contact.
```typescript -await client.unstable.companies.detachContactFromACompany({ - contact_id: "58a430d35458202d41b1e65b", - id: "58a430d35458202d41b1e65b", -}); -``` +await client.unstable.contacts.listContacts(); +```
@@ -10417,28 +14600,19 @@ await client.unstable.companies.detachContactFromACompany({
-**request:** `Intercom.unstable.DetachContactFromACompanyRequest` - -
-
- -
-
- -**requestOptions:** `Companies.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-## Contacts - -
client.unstable.contacts.listCompaniesForAContact({ ...params }) -> Intercom.ContactAttachedCompanies +
client.unstable.contacts.createContact({ ...params }) -> Intercom.CreateContactResponse
@@ -10450,8 +14624,7 @@ await client.unstable.companies.detachContactFromACompany({
-You can fetch a list of companies that are associated to a contact. - +You can create a new contact (ie. user or lead).
@@ -10466,11 +14639,11 @@ You can fetch a list of companies that are associated to a contact.
```typescript -await client.unstable.contacts.listCompaniesForAContact({ - id: "63a07ddf05a32042dffac965", +await client.unstable.contacts.createContact({ + "email": "joebloggs@intercom.io" }); -``` +```
@@ -10484,26 +14657,27 @@ await client.unstable.contacts.listCompaniesForAContact({
-**request:** `Intercom.unstable.ListCompaniesForAContactRequest` - +**request:** `Intercom.CreateContactRequestTwo` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.contacts.listSegmentsForAContact({ ...params }) -> Intercom.ContactSegments +
client.unstable.contacts.showContactByExternalId({ ...params }) -> Intercom.ShowContactByExternalIdResponse
@@ -10515,8 +14689,7 @@ await client.unstable.contacts.listCompaniesForAContact({
-You can fetch a list of segments that are associated to a contact. - +You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads.
@@ -10531,11 +14704,11 @@ You can fetch a list of segments that are associated to a contact.
```typescript -await client.unstable.contacts.listSegmentsForAContact({ - contact_id: "63a07ddf05a32042dffac965", +await client.unstable.contacts.showContactByExternalId({ + external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27" }); -``` +```
@@ -10549,26 +14722,27 @@ await client.unstable.contacts.listSegmentsForAContact({
-**request:** `Intercom.unstable.ListSegmentsForAContactRequest` - +**request:** `Intercom.unstable.ShowContactByExternalIdRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.contacts.listSubscriptionsForAContact({ ...params }) -> Intercom.SubscriptionTypeList +
client.unstable.contacts.archiveContact({ ...params }) -> Intercom.ContactArchived
@@ -10580,14 +14754,7 @@ await client.unstable.contacts.listSegmentsForAContact({
-You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. -This will return a list of Subscription Type objects that the contact is associated with. - -The data property will show a combined list of: - -1.Opt-out subscription types that the user has opted-out from. -2.Opt-in subscription types that the user has opted-in to receiving. - +You can archive a single contact.
@@ -10602,11 +14769,11 @@ The data property will show a combined list of:
```typescript -await client.unstable.contacts.listSubscriptionsForAContact({ - contact_id: "63a07ddf05a32042dffac965", +await client.unstable.contacts.archiveContact({ + id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -10620,26 +14787,27 @@ await client.unstable.contacts.listSubscriptionsForAContact({
-**request:** `Intercom.unstable.ListSubscriptionsForAContactRequest` - +**request:** `Intercom.unstable.ArchiveContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.contacts.listTagsForAContact({ ...params }) -> Intercom.TagList +
client.unstable.contacts.unarchiveContact({ ...params }) -> Intercom.ContactUnarchived
@@ -10651,8 +14819,7 @@ await client.unstable.contacts.listSubscriptionsForAContact({
-You can fetch a list of all tags that are attached to a specific contact. - +You can unarchive a single contact.
@@ -10667,11 +14834,11 @@ You can fetch a list of all tags that are attached to a specific contact.
```typescript -await client.unstable.contacts.listTagsForAContact({ - contact_id: "63a07ddf05a32042dffac965", +await client.unstable.contacts.unarchiveContact({ + id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -10685,26 +14852,27 @@ await client.unstable.contacts.listTagsForAContact({
-**request:** `Intercom.unstable.ListTagsForAContactRequest` - +**request:** `Intercom.unstable.UnarchiveContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.contacts.showContact({ ...params }) -> Intercom.ShowContactResponse +
client.unstable.contacts.blockContact({ ...params }) -> Intercom.ContactBlocked
@@ -10716,8 +14884,7 @@ await client.unstable.contacts.listTagsForAContact({
-You can fetch the details of a single contact. - +Block a single contact.
**Note:** conversations of the contact will also be archived during the process.
More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs)
@@ -10732,11 +14899,11 @@ You can fetch the details of a single contact.
```typescript -await client.unstable.contacts.showContact({ - id: "63a07ddf05a32042dffac965", +await client.unstable.contacts.blockContact({ + id: "63a07ddf05a32042dffac965" }); -``` +```
@@ -10750,26 +14917,28 @@ await client.unstable.contacts.showContact({
-**request:** `Intercom.unstable.ShowContactRequest` - +**request:** `Intercom.unstable.BlockContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `ContactsClient.RequestOptions` +
+
-
client.unstable.contacts.updateContact({ ...params }) -> Intercom.UpdateContactResponse +## Subscription Types +
client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ ...params }) -> Intercom.SubscriptionType
@@ -10781,14 +14950,13 @@ await client.unstable.contacts.showContact({
-You can update an existing contact (ie. user or lead). +You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: -{% admonition type="info" %} -This endpoint handles both **contact updates** and **custom object associations**. + 1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type. -See _`update a contact with an association to a custom object instance`_ in the request/response examples to see the custom object association format. -{% /admonition %} + 2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type. +This will return a subscription type model for the subscription type that was added to the contact.
@@ -10803,13 +14971,13 @@ See _`update a contact with an association to a custom object instance`_ in the
```typescript -await client.unstable.contacts.updateContact({ - id: "63a07ddf05a32042dffac965", - email: "joebloggs@intercom.io", - name: "joe bloggs", +await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in" }); -``` +```
@@ -10823,26 +14991,27 @@ await client.unstable.contacts.updateContact({
-**request:** `Intercom.unstable.UpdateContactRequest` - +**request:** `Intercom.unstable.AttachSubscriptionTypeToContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `SubscriptionTypesClient.RequestOptions` +
+
-
client.unstable.contacts.deleteContact({ ...params }) -> Intercom.ContactDeleted +
client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ ...params }) -> Intercom.SubscriptionType
@@ -10854,8 +15023,7 @@ await client.unstable.contacts.updateContact({
-You can delete a single contact. - +You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact.
@@ -10870,11 +15038,12 @@ You can delete a single contact.
```typescript -await client.unstable.contacts.deleteContact({ - id: "id", +await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846" }); -``` +```
@@ -10888,26 +15057,27 @@ await client.unstable.contacts.deleteContact({
-**request:** `Intercom.unstable.DeleteContactRequest` - +**request:** `Intercom.unstable.DetachSubscriptionTypeToContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `SubscriptionTypesClient.RequestOptions` +
+
-
client.unstable.contacts.mergeContact({ ...params }) -> Intercom.MergeContactResponse +
client.unstable.subscriptionTypes.listSubscriptionTypes() -> Intercom.SubscriptionTypeList
@@ -10919,8 +15089,7 @@ await client.unstable.contacts.deleteContact({
-You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`. - +You can list all subscription types. A list of subscription type objects will be returned.
@@ -10935,12 +15104,9 @@ You can merge a contact with a `role` of `lead` into a contact with a `role` of
```typescript -await client.unstable.contacts.mergeContact({ - from: "6762f0d51bb69f9f2193bb7f", - into: "6762f0d51bb69f9f2193bb80", -}); -``` +await client.unstable.subscriptionTypes.listSubscriptionTypes(); +```
@@ -10954,26 +15120,20 @@ await client.unstable.contacts.mergeContact({
-**request:** `Intercom.unstable.MergeContactsRequest` - -
-
- -
-
- -**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `SubscriptionTypesClient.RequestOptions` +
+
-
client.unstable.contacts.searchContacts({ ...params }) -> Intercom.ContactList +## Tags +
client.unstable.tags.attachTagToContact({ ...params }) -> Intercom.Tag
@@ -10985,109 +15145,73 @@ await client.unstable.contacts.mergeContact({
-You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. - -To search for contacts, you need to send a `POST` request to `https://api.intercom.io/contacts/search`. - -This will accept a query object in the body which will define your filters in order to search for contacts. - -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `50` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} +You can tag a specific contact. This will return a tag object for the tag that was added to the contact. +
+
+
+
-### Contact Creation Delay +#### 🔌 Usage -If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters. +
+
-### Nesting & Limitations +
+
-You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiple's there can be: +```typescript +await client.unstable.tags.attachTagToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907" +}); -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group +``` +
+
+
+
-### Searching for Timestamp Fields +#### ⚙️ Parameters -All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. -For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. -If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). -This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly. +
+
-### Accepted Fields +
+
-Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). +**request:** `Intercom.unstable.AttachTagToContactRequest` + +
+
-| Field | Type | -| ---------------------------------- | ------------------------------ | -| id | String | -| role | String
Accepts user or lead | -| name | String | -| avatar | String | -| owner_id | Integer | -| email | String | -| email_domain | String | -| phone | String | -| formatted_phone | String | -| external_id | String | -| created_at | Date (UNIX Timestamp) | -| signed_up_at | Date (UNIX Timestamp) | -| updated_at | Date (UNIX Timestamp) | -| last_seen_at | Date (UNIX Timestamp) | -| last_contacted_at | Date (UNIX Timestamp) | -| last_replied_at | Date (UNIX Timestamp) | -| last_email_opened_at | Date (UNIX Timestamp) | -| last_email_clicked_at | Date (UNIX Timestamp) | -| language_override | String | -| browser | String | -| browser_language | String | -| os | String | -| location.country | String | -| location.region | String | -| location.city | String | -| unsubscribed_from_emails | Boolean | -| marked_email_as_spam | Boolean | -| has_hard_bounced | Boolean | -| ios_last_seen_at | Date (UNIX Timestamp) | -| ios_app_version | String | -| ios_device | String | -| ios_app_device | String | -| ios_os_version | String | -| ios_app_name | String | -| ios_sdk_version | String | -| android_last_seen_at | Date (UNIX Timestamp) | -| android_app_version | String | -| android_device | String | -| android_app_name | String | -| andoid_sdk_version | String | -| segment_id | String | -| tag_id | String | -| custom_attributes.{attribute_name} | String | +
+
-### Accepted Operators +**requestOptions:** `TagsClient.RequestOptions` + +
+
+
+
-{% admonition type="warning" name="Searching based on `created_at`" %} -You cannot use the `<=` or `>=` operators to search by `created_at`. -{% /admonition %} -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). + + +
-| Operator | Valid Types | Description | -| :------- | :------------------------------- | :--------------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In
Shortcut for `OR` queries
Values must be in Array | -| NIN | All | Not In
Shortcut for `OR !` queries
Values must be in Array | -| > | Integer
Date (UNIX Timestamp) | Greater than | -| < | Integer
Date (UNIX Timestamp) | Lower than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | +
client.unstable.tags.detachTagFromContact({ ...params }) -> Intercom.Tag +
+
+ +#### 📝 Description + +
+
+ +
+
+You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact.
@@ -11102,23 +15226,12 @@ The table below shows the operators you can use to define how you want to search
```typescript -await client.unstable.contacts.searchContacts({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, +await client.unstable.tags.detachTagFromContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907" }); -``` +```
@@ -11132,26 +15245,27 @@ await client.unstable.contacts.searchContacts({
-**request:** `Intercom.SearchRequest` - +**request:** `Intercom.unstable.DetachTagFromContactRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.listContacts() -> Intercom.ContactList +
client.unstable.tags.attachTagToConversation({ ...params }) -> Intercom.Tag
@@ -11163,12 +15277,7 @@ await client.unstable.contacts.searchContacts({
-You can fetch a list of all contacts (ie. users or leads) in your workspace. -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `50` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} - +You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation.
@@ -11183,9 +15292,13 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -await client.unstable.contacts.listContacts(); -``` +await client.unstable.tags.attachTagToConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780" +}); +```
@@ -11199,18 +15312,27 @@ await client.unstable.contacts.listContacts();
-**requestOptions:** `Contacts.RequestOptions` +**request:** `Intercom.unstable.AttachTagToConversationRequest` + +
+
+ +
+
+**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.createContact({ ...params }) -> Intercom.CreateContactResponse +
client.unstable.tags.detachTagFromConversation({ ...params }) -> Intercom.Tag
@@ -11222,8 +15344,7 @@ await client.unstable.contacts.listContacts();
-You can create a new contact (ie. user or lead). - +You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation.
@@ -11238,11 +15359,13 @@ You can create a new contact (ie. user or lead).
```typescript -await client.unstable.contacts.createContact({ - email: "joebloggs@intercom.io", +await client.unstable.tags.detachTagFromConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "123" }); -``` +```
@@ -11256,26 +15379,27 @@ await client.unstable.contacts.createContact({
-**request:** `Intercom.CreateContactRequestTwo` - +**request:** `Intercom.unstable.DetachTagFromConversationRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.showContactByExternalId({ ...params }) -> Intercom.ShowContactByExternalIdResponse +
client.unstable.tags.listTags() -> Intercom.TagList
@@ -11287,7 +15411,7 @@ await client.unstable.contacts.createContact({
-You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads. +You can fetch a list of all tags for a given workspace.
@@ -11303,11 +15427,9 @@ You can fetch the details of a single contact by external ID. Note that this end
```typescript -await client.unstable.contacts.showContactByExternalId({ - external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27", -}); -``` +await client.unstable.tags.listTags(); +```
@@ -11321,26 +15443,19 @@ await client.unstable.contacts.showContactByExternalId({
-**request:** `Intercom.unstable.ShowContactByExternalIdRequest` - -
-
- -
-
- -**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.archiveContact({ ...params }) -> Intercom.ContactArchived +
client.unstable.tags.createTag({ ...params }) -> Intercom.Tag
@@ -11352,8 +15467,19 @@ await client.unstable.contacts.showContactByExternalId({
-You can archive a single contact. +You can use this endpoint to perform the following operations: + + **1. Create a new tag:** You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below. + + **2. Update an existing tag:** You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below. + **3. Tag Companies:** You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically. + + **4. Untag Companies:** You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below. + + **5. Tag Multiple Users:** You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below. + +Each operation will return a tag object.
@@ -11368,11 +15494,11 @@ You can archive a single contact.
```typescript -await client.unstable.contacts.archiveContact({ - id: "63a07ddf05a32042dffac965", +await client.unstable.tags.createTag({ + name: "test" }); -``` +```
@@ -11386,26 +15512,27 @@ await client.unstable.contacts.archiveContact({
-**request:** `Intercom.unstable.ArchiveContactRequest` - +**request:** `Intercom.CreateTagRequestBody` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.unarchiveContact({ ...params }) -> Intercom.ContactUnarchived +
client.unstable.tags.findTag({ ...params }) -> Intercom.Tag
@@ -11417,8 +15544,8 @@ await client.unstable.contacts.archiveContact({
-You can unarchive a single contact. - +You can fetch the details of tags that are on the workspace by their id. +This will return a tag object.
@@ -11433,11 +15560,11 @@ You can unarchive a single contact.
```typescript -await client.unstable.contacts.unarchiveContact({ - id: "63a07ddf05a32042dffac965", +await client.unstable.tags.findTag({ + id: "123" }); -``` +```
@@ -11451,26 +15578,27 @@ await client.unstable.contacts.unarchiveContact({
-**request:** `Intercom.unstable.UnarchiveContactRequest` - +**request:** `Intercom.unstable.FindTagRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.contacts.blockContact({ ...params }) -> Intercom.ContactBlocked +
client.unstable.tags.deleteTag({ ...params }) -> void
@@ -11482,8 +15610,7 @@ await client.unstable.contacts.unarchiveContact({
-Block a single contact.
**Note:** conversations of the contact will also be archived during the process.
More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs) - +You can delete the details of tags that are on the workspace by passing in the id.
@@ -11498,11 +15625,11 @@ Block a single contact.
**Note:** conversations of the contact will also be a
```typescript -await client.unstable.contacts.blockContact({ - id: "63a07ddf05a32042dffac965", +await client.unstable.tags.deleteTag({ + id: "123" }); -``` +```
@@ -11516,28 +15643,27 @@ await client.unstable.contacts.blockContact({
-**request:** `Intercom.unstable.BlockContactRequest` - +**request:** `Intercom.unstable.DeleteTagRequest` +
-**requestOptions:** `Contacts.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-## Notes - -
client.unstable.notes.listNotes({ ...params }) -> Intercom.NoteList +
client.unstable.tags.attachTagToTicket({ ...params }) -> Intercom.Tag
@@ -11549,8 +15675,7 @@ await client.unstable.contacts.blockContact({
-You can fetch a list of notes that are associated to a contact. - +You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket.
@@ -11565,11 +15690,13 @@ You can fetch a list of notes that are associated to a contact.
```typescript -await client.unstable.notes.listNotes({ - id: 1, +await client.unstable.tags.attachTagToTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780" }); -``` +```
@@ -11583,26 +15710,27 @@ await client.unstable.notes.listNotes({
-**request:** `Intercom.unstable.ListNotesRequest` - +**request:** `Intercom.unstable.AttachTagToTicketRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.notes.createNote({ ...params }) -> Intercom.Note +
client.unstable.tags.detachTagFromTicket({ ...params }) -> Intercom.Tag
@@ -11614,8 +15742,7 @@ await client.unstable.notes.listNotes({
-You can add a note to a single contact. - +You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket.
@@ -11630,14 +15757,13 @@ You can add a note to a single contact.
```typescript -await client.unstable.notes.createNote({ - id: 1, - body: "Hello", - contact_id: "6762f0ad1bb69f9f2193bb62", - admin_id: "123", +await client.unstable.tags.detachTagFromTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "123" }); -``` +```
@@ -11651,26 +15777,28 @@ await client.unstable.notes.createNote({
-**request:** `Intercom.unstable.CreateNoteRequest` - +**request:** `Intercom.unstable.DetachTagFromTicketRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `TagsClient.RequestOptions` +
+
-
client.unstable.notes.retrieveNote({ ...params }) -> Intercom.Note +## Conversations +
client.unstable.conversations.listConversations({ ...params }) -> Intercom.ConversationList
@@ -11682,8 +15810,13 @@ await client.unstable.notes.createNote({
-You can fetch the details of a single note. +You can fetch a list of all conversations. +You can optionally request the result page size and the cursor to start after to fetch the result. +{% admonition type="warning" name="Pagination" %} + You can use pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. +{% /admonition %}
@@ -11698,11 +15831,12 @@ You can fetch the details of a single note.
```typescript -await client.unstable.notes.retrieveNote({ - id: 1, +await client.unstable.conversations.listConversations({ + per_page: 1, + starting_after: "starting_after" }); -``` +```
@@ -11716,28 +15850,27 @@ await client.unstable.notes.retrieveNote({
-**request:** `Intercom.unstable.RetrieveNoteRequest` - +**request:** `Intercom.unstable.ListConversationsRequest` +
-**requestOptions:** `Notes.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-## Subscription Types - -
client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ ...params }) -> Intercom.SubscriptionType +
client.unstable.conversations.createConversation({ ...params }) -> Intercom.Message
@@ -11749,13 +15882,15 @@ await client.unstable.notes.retrieveNote({
-You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: - -1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type. +You can create a conversation that has been initiated by a contact (ie. user or lead). +The conversation can be an in-app message only. -2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type. +{% admonition type="info" name="Sending for visitors" %} +You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`. +This visitor will be automatically converted to a contact with a lead role once the conversation is created. +{% /admonition %} -This will return a subscription type model for the subscription type that was added to the contact. +This will return the Message model that has been created.
@@ -11771,13 +15906,15 @@ This will return a subscription type model for the subscription type that was ad
```typescript -await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ - contact_id: "63a07ddf05a32042dffac965", - id: "37846", - consent_type: "opt_in", +await client.unstable.conversations.createConversation({ + from: { + type: "user", + id: "6762f11b1bb69f9f2193bba3" + }, + body: "Hello there" }); -``` +```
@@ -11791,26 +15928,27 @@ await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({
-**request:** `Intercom.unstable.AttachSubscriptionTypeToContactRequest` - +**request:** `Intercom.unstable.CreateConversationRequest` +
-**requestOptions:** `SubscriptionTypes.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ ...params }) -> Intercom.SubscriptionType +
client.unstable.conversations.retrieveConversation({ ...params }) -> Intercom.Conversation
@@ -11822,8 +15960,16 @@ await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({
-You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. +You can fetch the details of a single conversation. + +This will return a single Conversation model with all its conversation parts. + +{% admonition type="warning" name="Hard limit of 500 parts" %} +The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. +{% /admonition %} + +For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671).
@@ -11838,12 +15984,13 @@ You can remove a specific subscription from a contact. This will return a subscr
```typescript -await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ - contact_id: "63a07ddf05a32042dffac965", - id: "37846", +await client.unstable.conversations.retrieveConversation({ + id: 1, + display_as: "plaintext", + include_translations: true }); -``` +```
@@ -11857,26 +16004,27 @@ await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({
-**request:** `Intercom.unstable.DetachSubscriptionTypeToContactRequest` - +**request:** `Intercom.unstable.RetrieveConversationRequest` +
-**requestOptions:** `SubscriptionTypes.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.subscriptionTypes.listSubscriptionTypes() -> Intercom.SubscriptionTypeList +
client.unstable.conversations.updateConversation({ ...params }) -> Intercom.Conversation
@@ -11888,7 +16036,18 @@ await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({
-You can list all subscription types. A list of subscription type objects will be returned. + +You can update an existing conversation. + +{% admonition type="info" name="Replying and other actions" %} +If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. +{% /admonition %} + +{% admonition type="info" %} + This endpoint handles both **conversation updates** and **custom object associations**. + + See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format. +{% /admonition %}
@@ -11904,9 +16063,18 @@ You can list all subscription types. A list of subscription type objects will be
```typescript -await client.unstable.subscriptionTypes.listSubscriptionTypes(); -``` +await client.unstable.conversations.updateConversation({ + id: 1, + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + "issue_type": "Billing", + "priority": "High" + } +}); +```
@@ -11920,20 +16088,27 @@ await client.unstable.subscriptionTypes.listSubscriptionTypes();
-**requestOptions:** `SubscriptionTypes.RequestOptions` +**request:** `Intercom.unstable.UpdateConversationRequest` + +
+
+ +
+
+**requestOptions:** `ConversationsClient.RequestOptions` +
+
-## Tags - -
client.unstable.tags.attachTagToContact({ ...params }) -> Intercom.Tag +
client.unstable.conversations.deleteConversation({ ...params }) -> Intercom.ConversationDeleted
@@ -11945,8 +16120,7 @@ await client.unstable.subscriptionTypes.listSubscriptionTypes();
-You can tag a specific contact. This will return a tag object for the tag that was added to the contact. - +You can delete a single conversation.
@@ -11961,12 +16135,11 @@ You can tag a specific contact. This will return a tag object for the tag that w
```typescript -await client.unstable.tags.attachTagToContact({ - contact_id: "63a07ddf05a32042dffac965", - id: "7522907", +await client.unstable.conversations.deleteConversation({ + id: 1 }); -``` +```
@@ -11980,26 +16153,27 @@ await client.unstable.tags.attachTagToContact({
-**request:** `Intercom.unstable.AttachTagToContactRequest` - +**request:** `Intercom.unstable.DeleteConversationRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.detachTagFromContact({ ...params }) -> Intercom.Tag +
client.unstable.conversations.searchConversations({ ...params }) -> Intercom.ConversationList
@@ -12011,8 +16185,105 @@ await client.unstable.tags.attachTagToContact({
-You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. +You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + +To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`. + +This will accept a query object in the body which will define your filters in order to search for conversations. +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} + +### Nesting & Limitations + +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiple's there can be: +- There's a limit of max 2 nested filters +- There's a limit of max 15 filters for each AND or OR group + +### Accepted Fields + +Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). +The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. + +| Field | Type | +| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | +| id | String | +| created_at | Date (UNIX timestamp) | +| updated_at | Date (UNIX timestamp) | +| source.type | String
Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. | +| source.id | String | +| source.delivered_as | String | +| source.subject | String | +| source.body | String | +| source.author.id | String | +| source.author.type | String | +| source.author.name | String | +| source.author.email | String | +| source.url | String | +| contact_ids | String | +| teammate_ids | String | +| admin_assignee_id | String | +| team_assignee_id | String | +| channel_initiated | String | +| open | Boolean | +| read | Boolean | +| state | String | +| waiting_since | Date (UNIX timestamp) | +| snoozed_until | Date (UNIX timestamp) | +| tag_ids | String | +| priority | String | +| statistics.time_to_assignment | Integer | +| statistics.time_to_admin_reply | Integer | +| statistics.time_to_first_close | Integer | +| statistics.time_to_last_close | Integer | +| statistics.median_time_to_reply | Integer | +| statistics.first_contact_reply_at | Date (UNIX timestamp) | +| statistics.first_assignment_at | Date (UNIX timestamp) | +| statistics.first_admin_reply_at | Date (UNIX timestamp) | +| statistics.first_close_at | Date (UNIX timestamp) | +| statistics.last_assignment_at | Date (UNIX timestamp) | +| statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | +| statistics.last_contact_reply_at | Date (UNIX timestamp) | +| statistics.last_admin_reply_at | Date (UNIX timestamp) | +| statistics.last_close_at | Date (UNIX timestamp) | +| statistics.last_closed_by_id | String | +| statistics.count_reopens | Integer | +| statistics.count_assignments | Integer | +| statistics.count_conversation_parts | Integer | +| conversation_rating.requested_at | Date (UNIX timestamp) | +| conversation_rating.replied_at | Date (UNIX timestamp) | +| conversation_rating.score | Integer | +| conversation_rating.remark | String | +| conversation_rating.contact_id | String | +| conversation_rating.admin_d | String | +| ai_agent_participated | Boolean | +| ai_agent.resolution_state | String | +| ai_agent.last_answer_type | String | +| ai_agent.rating | Integer | +| ai_agent.rating_remark | String | +| ai_agent.source_type | String | +| ai_agent.source_title | String | + +### Accepted Operators + +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). +| Operator | Valid Types | Description | +| :------- | :----------------------------- | :----------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In Shortcut for `OR` queries Values most be in Array | +| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | +| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | +| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With |
@@ -12027,12 +16298,21 @@ You can remove tag from a specific contact. This will return a tag object for th
```typescript -await client.unstable.tags.detachTagFromContact({ - contact_id: "63a07ddf05a32042dffac965", - id: "7522907", +await client.unstable.conversations.searchConversations({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } }); -``` +```
@@ -12046,26 +16326,27 @@ await client.unstable.tags.detachTagFromContact({
-**request:** `Intercom.unstable.DetachTagFromContactRequest` - +**request:** `Intercom.SearchRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.attachTagToConversation({ ...params }) -> Intercom.Tag +
client.unstable.conversations.replyConversation({ ...params }) -> Intercom.Conversation
@@ -12077,8 +16358,7 @@ await client.unstable.tags.detachTagFromContact({
-You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. - +You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins.
@@ -12093,13 +16373,17 @@ You can tag a specific conversation. This will return a tag object for the tag t
```typescript -await client.unstable.tags.attachTagToConversation({ - conversation_id: "64619700005694", - id: "7522907", - admin_id: "780", +await client.unstable.conversations.replyConversation({ + id: "123 or \"last\"", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb" + } }); -``` +```
@@ -12113,26 +16397,27 @@ await client.unstable.tags.attachTagToConversation({
-**request:** `Intercom.unstable.AttachTagToConversationRequest` - +**request:** `Intercom.unstable.ReplyConversationRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.detachTagFromConversation({ ...params }) -> Intercom.Tag +
client.unstable.conversations.manageConversation({ ...params }) -> Intercom.Conversation
@@ -12144,8 +16429,11 @@ await client.unstable.tags.attachTagToConversation({
-You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. - +For managing conversations you can: +- Close a conversation +- Snooze a conversation to reopen on a future date +- Open a conversation which is `snoozed` or `closed` +- Assign a conversation to an admin and/or team.
@@ -12160,13 +16448,16 @@ You can remove tag from a specific conversation. This will return a tag object f
```typescript -await client.unstable.tags.detachTagFromConversation({ - conversation_id: "64619700005694", - id: "7522907", - admin_id: "123", +await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345" + } }); -``` +```
@@ -12180,26 +16471,27 @@ await client.unstable.tags.detachTagFromConversation({
-**request:** `Intercom.unstable.DetachTagFromConversationRequest` - +**request:** `Intercom.unstable.ManageConversationRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.listTags() -> Intercom.TagList +
client.unstable.conversations.attachContactToConversation({ ...params }) -> Intercom.Conversation
@@ -12211,7 +16503,11 @@ await client.unstable.tags.detachTagFromConversation({
-You can fetch a list of all tags for a given workspace. +You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + +{% admonition type="warning" name="Contacts without an email" %} +If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. +{% /admonition %}
@@ -12227,9 +16523,15 @@ You can fetch a list of all tags for a given workspace.
```typescript -await client.unstable.tags.listTags(); -``` +await client.unstable.conversations.attachContactToConversation({ + id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19b1bb69f9f2193bbd4" + } +}); +```
@@ -12243,18 +16545,27 @@ await client.unstable.tags.listTags();
-**requestOptions:** `Tags.RequestOptions` +**request:** `Intercom.unstable.AttachContactToConversationRequest` + +
+
+ +
+
+**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.createTag({ ...params }) -> Intercom.Tag +
client.unstable.conversations.detachContactFromConversation({ ...params }) -> Intercom.Conversation
@@ -12266,19 +16577,11 @@ await client.unstable.tags.listTags();
-You can use this endpoint to perform the following operations: - -**1. Create a new tag:** You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below. - -**2. Update an existing tag:** You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below. - -**3. Tag Companies:** You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically. - -**4. Untag Companies:** You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below. - -**5. Tag Multiple Users:** You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below. +You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. -Each operation will return a tag object. +{% admonition type="warning" name="Contacts without an email" %} +If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. +{% /admonition %}
@@ -12294,11 +16597,13 @@ Each operation will return a tag object.
```typescript -await client.unstable.tags.createTag({ - name: "test", +await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690" }); -``` +```
@@ -12312,26 +16617,27 @@ await client.unstable.tags.createTag({
-**request:** `Intercom.CreateTagRequestBody` - +**request:** `Intercom.unstable.DetachContactFromConversationRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.findTag({ ...params }) -> Intercom.Tag +
client.unstable.conversations.redactConversation({ ...params }) -> Intercom.Conversation
@@ -12343,8 +16649,11 @@ await client.unstable.tags.createTag({
-You can fetch the details of tags that are on the workspace by their id. -This will return a tag object. +You can redact a conversation part or the source message of a conversation (as seen in the source object). + +{% admonition type="info" name="Redacting parts and messages" %} +If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. +{% /admonition %}
@@ -12360,11 +16669,13 @@ This will return a tag object.
```typescript -await client.unstable.tags.findTag({ - id: "123", +await client.unstable.conversations.redactConversation({ + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428" }); -``` +```
@@ -12378,26 +16689,27 @@ await client.unstable.tags.findTag({
-**request:** `Intercom.unstable.FindTagRequest` - +**request:** `Intercom.RedactConversationRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.deleteTag({ ...params }) -> void +
client.unstable.conversations.convertConversationToTicket({ ...params }) -> Intercom.Ticket | undefined
@@ -12409,8 +16721,7 @@ await client.unstable.tags.findTag({
-You can delete the details of tags that are on the workspace by passing in the id. - +You can convert a conversation to a ticket.
@@ -12425,11 +16736,12 @@ You can delete the details of tags that are on the workspace by passing in the i
```typescript -await client.unstable.tags.deleteTag({ - id: "123", +await client.unstable.conversations.convertConversationToTicket({ + id: 1, + ticket_type_id: "53" }); -``` +```
@@ -12443,26 +16755,28 @@ await client.unstable.tags.deleteTag({
-**request:** `Intercom.unstable.DeleteTagRequest` - +**request:** `Intercom.unstable.ConvertConversationToTicketRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `ConversationsClient.RequestOptions` +
+
-
client.unstable.tags.attachTagToTicket({ ...params }) -> Intercom.Tag +## Unstable CustomChannelEvents +
client.unstable.customChannelEvents.notifyNewConversation({ ...params }) -> Intercom.CustomChannelNotificationResponse
@@ -12474,8 +16788,8 @@ await client.unstable.tags.deleteTag({
-You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. - +Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
@@ -12490,13 +16804,18 @@ You can tag a specific ticket. This will return a tag object for the tag that wa
```typescript -await client.unstable.tags.attachTagToTicket({ - ticket_id: "64619700005694", - id: "7522907", - admin_id: "780", +await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "evt_12345", + external_conversation_id: "conv_67890", + contact: { + type: "user", + external_id: "user_001", + name: "Jane Doe", + email: "jane.doe@example.com" + } }); -``` +```
@@ -12510,26 +16829,27 @@ await client.unstable.tags.attachTagToTicket({
-**request:** `Intercom.unstable.AttachTagToTicketRequest` - +**request:** `Intercom.CustomChannelBaseEvent` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CustomChannelEventsClient.RequestOptions` +
+
-
client.unstable.tags.detachTagFromTicket({ ...params }) -> Intercom.Tag +
client.unstable.customChannelEvents.notifyNewMessage({ ...params }) -> Intercom.CustomChannelNotificationResponse
@@ -12541,8 +16861,8 @@ await client.unstable.tags.attachTagToTicket({
-You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. - +Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
@@ -12557,13 +16877,19 @@ You can remove tag from a specific ticket. This will return a tag object for the
```typescript -await client.unstable.tags.detachTagFromTicket({ - ticket_id: "64619700005694", - id: "7522907", - admin_id: "123", +await client.unstable.customChannelEvents.notifyNewMessage({ + event_id: "evt_54321", + external_conversation_id: "conv_98765", + contact: { + type: "user", + external_id: "user_002", + name: "John Smith", + email: "john.smith@example.com" + }, + body: "Hello, I need help with my order." }); -``` +```
@@ -12577,28 +16903,27 @@ await client.unstable.tags.detachTagFromTicket({
-**request:** `Intercom.unstable.DetachTagFromTicketRequest` - +**request:** `Intercom.unstable.NotifyNewMessageRequest` +
-**requestOptions:** `Tags.RequestOptions` - +**requestOptions:** `CustomChannelEventsClient.RequestOptions` +
+
-## Conversations - -
client.unstable.conversations.listConversations({ ...params }) -> Intercom.ConversationList +
client.unstable.customChannelEvents.notifyQuickReplySelected({ ...params }) -> Intercom.CustomChannelNotificationResponse
@@ -12610,14 +16935,8 @@ await client.unstable.tags.detachTagFromTicket({
-You can fetch a list of all conversations. - -You can optionally request the result page size and the cursor to start after to fetch the result. -{% admonition type="warning" name="Pagination" %} -You can use pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. -{% /admonition %} - +Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
@@ -12632,9 +16951,19 @@ See the [pagination section](https://developers.intercom.com/docs/build-an-integ
```typescript -await client.unstable.conversations.listConversations(); -``` +await client.unstable.customChannelEvents.notifyQuickReplySelected({ + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { + type: "user", + external_id: "user_003", + name: "Alice Example", + email: "alice@example.com" + }, + quick_reply_option_id: "1234" +}); +```
@@ -12648,26 +16977,27 @@ await client.unstable.conversations.listConversations();
-**request:** `Intercom.unstable.ListConversationsRequest` - +**request:** `Intercom.unstable.NotifyQuickReplySelectedRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomChannelEventsClient.RequestOptions` +
+
-
client.unstable.conversations.createConversation({ ...params }) -> Intercom.Message +
client.unstable.customChannelEvents.notifyAttributeCollected({ ...params }) -> Intercom.CustomChannelNotificationResponse
@@ -12679,16 +17009,8 @@ await client.unstable.conversations.listConversations();
-You can create a conversation that has been initiated by a contact (ie. user or lead). -The conversation can be an in-app message only. - -{% admonition type="info" name="Sending for visitors" %} -You can also send a message from a visitor by specifying their `user_id` or `id` value in the `from` field, along with a `type` field value of `contact`. -This visitor will be automatically converted to a contact with a lead role once the conversation is created. -{% /admonition %} - -This will return the Message model that has been created. - +Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations. +> **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support.
@@ -12703,15 +17025,22 @@ This will return the Message model that has been created.
```typescript -await client.unstable.conversations.createConversation({ - from: { +await client.unstable.customChannelEvents.notifyAttributeCollected({ + event_id: "evt_24680", + external_conversation_id: "conv_11223", + contact: { type: "user", - id: "6762f11b1bb69f9f2193bba3", + external_id: "user_004", + name: "Bob Example", + email: "bob@example.com" }, - body: "Hello there", + attribute: { + id: "shipping_address", + value: "123 Main St, Springfield" + } }); -``` +```
@@ -12725,26 +17054,28 @@ await client.unstable.conversations.createConversation({
-**request:** `Intercom.unstable.CreateConversationRequest` - +**request:** `Intercom.unstable.NotifyAttributeCollectedRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomChannelEventsClient.RequestOptions` +
+
-
client.unstable.conversations.retrieveConversation({ ...params }) -> Intercom.Conversation +## Custom Object Instances +
client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstance | undefined
@@ -12756,16 +17087,7 @@ await client.unstable.conversations.createConversation({
-You can fetch the details of a single conversation. - -This will return a single Conversation model with all its conversation parts. - -{% admonition type="warning" name="Hard limit of 500 parts" %} -The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. -{% /admonition %} - -For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671). - +Fetch a Custom Object Instance by external_id.
@@ -12780,12 +17102,12 @@ For AI agent conversation metadata, please note that you need to have the agent
```typescript -await client.unstable.conversations.retrieveConversation({ - id: 1, - display_as: "plaintext", +await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + external_id: "external_id" }); -``` +```
@@ -12799,26 +17121,27 @@ await client.unstable.conversations.retrieveConversation({
-**request:** `Intercom.unstable.RetrieveConversationRequest` - +**request:** `Intercom.unstable.GetCustomObjectInstancesByExternalIdRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` +
+
-
client.unstable.conversations.updateConversation({ ...params }) -> Intercom.Conversation +
client.unstable.customObjectInstances.createCustomObjectInstances({ ...params }) -> Intercom.CustomObjectInstance | undefined
@@ -12830,18 +17153,7 @@ await client.unstable.conversations.retrieveConversation({
-You can update an existing conversation. - -{% admonition type="info" name="Replying and other actions" %} -If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. -{% /admonition %} - -{% admonition type="info" %} -This endpoint handles both **conversation updates** and **custom object associations**. - -See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format. -{% /admonition %} - +Create or update a custom object instance
@@ -12856,18 +17168,18 @@ See _`update a conversation with an association to a custom object instance`_ in
```typescript -await client.unstable.conversations.updateConversation({ - id: 1, - display_as: "plaintext", - read: true, - title: "new conversation title", +await client.unstable.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "Order", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, custom_attributes: { - issue_type: "Billing", - priority: "High", - }, + "order_number": "ORDER-12345", + "total_amount": "custom_attributes" + } }); -``` +```
@@ -12881,26 +17193,27 @@ await client.unstable.conversations.updateConversation({
-**request:** `Intercom.unstable.UpdateConversationRequest` - +**request:** `Intercom.unstable.CreateOrUpdateCustomObjectInstanceRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` +
+
-
client.unstable.conversations.deleteConversation({ ...params }) -> Intercom.ConversationDeleted +
client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstanceDeleted
@@ -12912,8 +17225,7 @@ await client.unstable.conversations.updateConversation({
-You can delete a single conversation. - +Delete a single Custom Object instance by external_id.
@@ -12928,11 +17240,12 @@ You can delete a single conversation.
```typescript -await client.unstable.conversations.deleteConversation({ - id: 1, +await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + external_id: "external_id" }); -``` +```
@@ -12946,138 +17259,39 @@ await client.unstable.conversations.deleteConversation({
-**request:** `Intercom.unstable.DeleteConversationRequest` - -
-
- -
-
- -**requestOptions:** `Conversations.RequestOptions` - -
-
- - - +**request:** `Intercom.unstable.DeleteCustomObjectInstancesByIdRequest` + -
- -
client.unstable.conversations.searchConversations({ ...params }) -> Intercom.ConversationList -
-
- -#### 📝 Description - -
-
-You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. - -To search for conversations, you need to send a `POST` request to `https://api.intercom.io/conversations/search`. - -This will accept a query object in the body which will define your filters in order to search for conversations. -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `20` results per page and maximum is `150`. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} - -### Nesting & Limitations - -You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiple's there can be: - -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group - -### Accepted Fields - -Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). -The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. - -| Field | Type | -| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | -| id | String | -| created_at | Date (UNIX timestamp) | -| updated_at | Date (UNIX timestamp) | -| source.type | String
Accepted fields are `conversation`, `email`, `facebook`, `instagram`, `phone_call`, `phone_switch`, `push`, `sms`, `twitter` and `whatsapp`. | -| source.id | String | -| source.delivered_as | String | -| source.subject | String | -| source.body | String | -| source.author.id | String | -| source.author.type | String | -| source.author.name | String | -| source.author.email | String | -| source.url | String | -| contact_ids | String | -| teammate_ids | String | -| admin_assignee_id | String | -| team_assignee_id | String | -| channel_initiated | String | -| open | Boolean | -| read | Boolean | -| state | String | -| waiting_since | Date (UNIX timestamp) | -| snoozed_until | Date (UNIX timestamp) | -| tag_ids | String | -| priority | String | -| statistics.time_to_assignment | Integer | -| statistics.time_to_admin_reply | Integer | -| statistics.time_to_first_close | Integer | -| statistics.time_to_last_close | Integer | -| statistics.median_time_to_reply | Integer | -| statistics.first_contact_reply_at | Date (UNIX timestamp) | -| statistics.first_assignment_at | Date (UNIX timestamp) | -| statistics.first_admin_reply_at | Date (UNIX timestamp) | -| statistics.first_close_at | Date (UNIX timestamp) | -| statistics.last_assignment_at | Date (UNIX timestamp) | -| statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | -| statistics.last_contact_reply_at | Date (UNIX timestamp) | -| statistics.last_admin_reply_at | Date (UNIX timestamp) | -| statistics.last_close_at | Date (UNIX timestamp) | -| statistics.last_closed_by_id | String | -| statistics.count_reopens | Integer | -| statistics.count_assignments | Integer | -| statistics.count_conversation_parts | Integer | -| conversation_rating.requested_at | Date (UNIX timestamp) | -| conversation_rating.replied_at | Date (UNIX timestamp) | -| conversation_rating.score | Integer | -| conversation_rating.remark | String | -| conversation_rating.contact_id | String | -| conversation_rating.admin_d | String | -| ai_agent_participated | Boolean | -| ai_agent.resolution_state | String | -| ai_agent.last_answer_type | String | -| ai_agent.rating | Integer | -| ai_agent.rating_remark | String | -| ai_agent.source_type | String | -| ai_agent.source_title | String | +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` + +
+
+
+
-### Accepted Operators -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). +
+
+
+ +
client.unstable.customObjectInstances.getCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstance | undefined +
+
+ +#### 📝 Description + +
+
-| Operator | Valid Types | Description | -| :------- | :---------------------------- | :--------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In Shortcut for `OR` queries Values most be in Array | -| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | -| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | -| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | +
+
+Fetch a Custom Object Instance by id.
@@ -13092,23 +17306,12 @@ The table below shows the operators you can use to define how you want to search
```typescript -await client.unstable.conversations.searchConversations({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, +await client.unstable.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + id: "id" }); -``` +```
@@ -13122,26 +17325,27 @@ await client.unstable.conversations.searchConversations({
-**request:** `Intercom.SearchRequest` - +**request:** `Intercom.unstable.GetCustomObjectInstancesByIdRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` +
+
-
client.unstable.conversations.replyConversation({ ...params }) -> Intercom.Conversation +
client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstanceDeleted
@@ -13153,8 +17357,7 @@ await client.unstable.conversations.searchConversations({
-You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. - +Delete a single Custom Object instance using the Intercom defined id.
@@ -13169,17 +17372,12 @@ You can reply to a conversation with a message from an admin or on behalf of a c
```typescript -await client.unstable.conversations.replyConversation({ - id: '123 or "last"', - body: { - message_type: "comment", - type: "user", - body: "Thanks again :)", - intercom_user_id: "6762f1571bb69f9f2193bbbb", - }, +await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + id: "id" }); -``` +```
@@ -13193,26 +17391,28 @@ await client.unstable.conversations.replyConversation({
-**request:** `Intercom.unstable.ReplyConversationRequest` - +**request:** `Intercom.unstable.DeleteCustomObjectInstancesByExternalIdRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `CustomObjectInstancesClient.RequestOptions` +
+
-
client.unstable.conversations.manageConversation({ ...params }) -> Intercom.Conversation +## Data Attributes +
client.unstable.dataAttributes.lisDataAttributes({ ...params }) -> Intercom.DataAttributeList
@@ -13224,16 +17424,11 @@ await client.unstable.conversations.replyConversation({
-For managing conversations you can: - -- Close a conversation -- Snooze a conversation to reopen on a future date -- Open a conversation which is `snoozed` or `closed` -- Assign a conversation to an admin and/or team. -
-
-
-
+You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + + + + #### 🔌 Usage @@ -13244,16 +17439,12 @@ For managing conversations you can:
```typescript -await client.unstable.conversations.manageConversation({ - id: "123", - body: { - message_type: "close", - type: "admin", - admin_id: "12345", - }, +await client.unstable.dataAttributes.lisDataAttributes({ + model: "contact", + include_archived: true }); -``` +```
@@ -13267,26 +17458,27 @@ await client.unstable.conversations.manageConversation({
-**request:** `Intercom.unstable.ManageConversationRequest` - +**request:** `Intercom.unstable.LisDataAttributesRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `DataAttributesClient.RequestOptions` +
+
-
client.unstable.conversations.attachContactToConversation({ ...params }) -> Intercom.Conversation +
client.unstable.dataAttributes.createDataAttribute({ ...params }) -> Intercom.DataAttribute
@@ -13298,12 +17490,7 @@ await client.unstable.conversations.manageConversation({
-You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. - -{% admonition type="warning" name="Contacts without an email" %} -If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. -{% /admonition %} - +You can create a data attributes for a `contact` or a `company`.
@@ -13318,15 +17505,11 @@ If you add a contact via the email parameter and there is no user/lead found on
```typescript -await client.unstable.conversations.attachContactToConversation({ - id: "123", - admin_id: "12345", - customer: { - intercom_user_id: "6762f19b1bb69f9f2193bbd4", - }, +await client.unstable.dataAttributes.createDataAttribute({ + "key": "value" }); -``` +```
@@ -13340,26 +17523,27 @@ await client.unstable.conversations.attachContactToConversation({
-**request:** `Intercom.unstable.AttachContactToConversationRequest` - +**request:** `unknown` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `DataAttributesClient.RequestOptions` +
+
-
client.unstable.conversations.detachContactFromConversation({ ...params }) -> Intercom.Conversation +
client.unstable.dataAttributes.updateDataAttribute({ ...params }) -> Intercom.DataAttribute
@@ -13371,12 +17555,12 @@ await client.unstable.conversations.attachContactToConversation({
-You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. -{% admonition type="warning" name="Contacts without an email" %} -If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. -{% /admonition %} +You can update a data attribute. +> 🚧 Updating the data type is not possible +> +> It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.
@@ -13391,13 +17575,14 @@ If you add a contact via the email parameter and there is no user/lead found on
```typescript -await client.unstable.conversations.detachContactFromConversation({ - conversation_id: "123", - contact_id: "123", - admin_id: "5017690", +await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + "key": "value" + } }); -``` +```
@@ -13411,26 +17596,28 @@ await client.unstable.conversations.detachContactFromConversation({
-**request:** `Intercom.unstable.DetachContactFromConversationRequest` - +**request:** `Intercom.unstable.UpdateDataAttributeRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `DataAttributesClient.RequestOptions` +
+
-
client.unstable.conversations.redactConversation({ ...params }) -> Intercom.Conversation +## Data Events +
client.unstable.dataEvents.lisDataEvents({ ...params }) -> Intercom.DataEventSummary
@@ -13442,12 +17629,20 @@ await client.unstable.conversations.detachContactFromConversation({
-You can redact a conversation part or the source message of a conversation (as seen in the source object). -{% admonition type="info" name="Redacting parts and messages" %} -If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. -{% /admonition %} +> 🚧 +> +> Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days + +The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`. + +- `https://api.intercom.io/events?type=user&user_id={user_id}` +- `https://api.intercom.io/events?type=user&email={email}` +- `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads) + +The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending. +You can optionally define the result page size as well with the `per_page` parameter.
@@ -13462,13 +17657,14 @@ If you are redacting a conversation part, it must have a `body`. If you are reda
```typescript -await client.unstable.conversations.redactConversation({ - type: "conversation_part", - conversation_id: "19894788788", - conversation_part_id: "19381789428", +await client.unstable.dataEvents.lisDataEvents({ + filter: { + user_id: "user_id" + }, + type: "type" }); -``` +```
@@ -13482,26 +17678,27 @@ await client.unstable.conversations.redactConversation({
-**request:** `Intercom.RedactConversationRequest` - +**request:** `Intercom.unstable.LisDataEventsRequest` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `DataEventsClient.RequestOptions` +
+
-
client.unstable.conversations.convertConversationToTicket({ ...params }) -> Intercom.Ticket | undefined +
client.unstable.dataEvents.createDataEvent({ ...params }) -> void
@@ -13513,7 +17710,47 @@ await client.unstable.conversations.redactConversation({
-You can convert a conversation to a ticket. + +You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`. + +When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event. + +With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`). + +**NB: For the JSON object types, please note that we do not currently support nested JSON structure.** + +| Type | Description | Example | +| :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | +| String | The value is a JSON String | `"source":"desktop"` | +| Number | The value is a JSON Number | `"load": 3.67` | +| Date | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272` | +| Link | The value is a HTTP or HTTPS URI. | `"article": "https://example.org/ab1de.html"` | +| Rich Link | The value is a JSON object that contains `url` and `value` keys. | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` | +| Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | `"price": {"amount": 34999, "currency": "eur"}` | + +**Lead Events** + +When submitting events for Leads, you will need to specify the Lead's `id`. + +**Metadata behaviour** + +- We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event. +- It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one. +- There might be up to 24 hrs delay when you send a new metadata for an existing event. + +**Event de-duplication** + +The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field. + +Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place. + +### HTTP API Responses + +- Successful responses to submitted events return `202 Accepted` with an empty body. +- Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code. +- Events sent about users that cannot be found will return a `404 Not Found`. +- Event lists containing duplicate events will have those duplicates ignored. +- Server errors will return a `500` response code and may contain an error message in the body.
@@ -13529,12 +17766,11 @@ You can convert a conversation to a ticket.
```typescript -await client.unstable.conversations.convertConversationToTicket({ - id: 1, - ticket_type_id: "53", +await client.unstable.dataEvents.createDataEvent({ + "key": "value" }); -``` +```
@@ -13548,28 +17784,27 @@ await client.unstable.conversations.convertConversationToTicket({
-**request:** `Intercom.unstable.ConvertConversationToTicketRequest` - +**request:** `Intercom.CreateDataEventRequestTwo` +
-**requestOptions:** `Conversations.RequestOptions` - +**requestOptions:** `DataEventsClient.RequestOptions` +
+
-## Unstable CustomChannelEvents - -
client.unstable.customChannelEvents.notifyNewConversation({ ...params }) -> Intercom.CustomChannelNotificationResponse +
client.unstable.dataEvents.dataEventSummaries({ ...params }) -> void
@@ -13581,9 +17816,7 @@ await client.unstable.conversations.convertConversationToTicket({
-Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration. - -> **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". +Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred.
@@ -13599,18 +17832,9 @@ Notifies Intercom that a new conversation was created in your custom channel/pla
```typescript -await client.unstable.customChannelEvents.notifyNewConversation({ - event_id: "evt_12345", - external_conversation_id: "conv_67890", - contact: { - type: "user", - external_id: "user_001", - name: "Jane Doe", - email: "jane.doe@example.com", - }, -}); -``` +await client.unstable.dataEvents.dataEventSummaries(); +```
@@ -13624,26 +17848,28 @@ await client.unstable.customChannelEvents.notifyNewConversation({
-**request:** `Intercom.CustomChannelBaseEvent` - +**request:** `Intercom.unstable.CreateDataEventSummariesRequest` +
-**requestOptions:** `CustomChannelEvents.RequestOptions` - +**requestOptions:** `DataEventsClient.RequestOptions` +
+
-
client.unstable.customChannelEvents.notifyNewMessage({ ...params }) -> Intercom.CustomChannelNotificationResponse +## Data Export +
client.unstable.dataExport.createDataExport({ ...params }) -> Intercom.DataExport
@@ -13655,10 +17881,21 @@ await client.unstable.customChannelEvents.notifyNewConversation({
-Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations. +To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. + +The only parameters you need to provide are the range of dates that you want exported. + +>🚧 Limit of one active job +> +> You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job. -> **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". +>❗️ Updated_at not included +> +> It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job. +>📘 Date ranges are inclusive +> +> Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.
@@ -13673,19 +17910,12 @@ Notifies Intercom that a new message was sent in a conversation on your custom c
```typescript -await client.unstable.customChannelEvents.notifyNewMessage({ - event_id: "evt_54321", - external_conversation_id: "conv_98765", - contact: { - type: "user", - external_id: "user_002", - name: "John Smith", - email: "john.smith@example.com", - }, - body: "Hello, I need help with my order.", +await client.unstable.dataExport.createDataExport({ + created_at_after: 1734519776, + created_at_before: 1734537776 }); -``` +```
@@ -13699,26 +17929,27 @@ await client.unstable.customChannelEvents.notifyNewMessage({
-**request:** `Intercom.unstable.NotifyNewMessageRequest` - +**request:** `Intercom.unstable.CreateDataExportsRequest` +
-**requestOptions:** `CustomChannelEvents.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.unstable.customChannelEvents.notifyQuickReplySelected({ ...params }) -> Intercom.CustomChannelNotificationResponse +
client.unstable.dataExport.getDataExport({ ...params }) -> Intercom.DataExport
@@ -13730,10 +17961,11 @@ await client.unstable.customChannelEvents.notifyNewMessage({
-Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations. - -> **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". +You can view the status of your job by sending a `GET` request to the URL +`https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. +> 🚧 Jobs expire after two days +> All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.
@@ -13748,19 +17980,11 @@ Notifies Intercom that a user selected a quick reply option in your custom chann
```typescript -await client.unstable.customChannelEvents.notifyQuickReplySelected({ - event_id: "evt_67890", - external_conversation_id: "conv_13579", - contact: { - type: "user", - external_id: "user_003", - name: "Alice Example", - email: "alice@example.com", - }, - quick_reply_option_id: "1234", +await client.unstable.dataExport.getDataExport({ + job_identifier: "job_identifier" }); -``` +```
@@ -13774,26 +17998,27 @@ await client.unstable.customChannelEvents.notifyQuickReplySelected({
-**request:** `Intercom.unstable.NotifyQuickReplySelectedRequest` - +**request:** `Intercom.unstable.GetDataExportRequest` +
-**requestOptions:** `CustomChannelEvents.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.unstable.customChannelEvents.notifyAttributeCollected({ ...params }) -> Intercom.CustomChannelNotificationResponse +
client.unstable.dataExport.cancelDataExport({ ...params }) -> Intercom.DataExport
@@ -13805,10 +18030,7 @@ await client.unstable.customChannelEvents.notifyQuickReplySelected({
-Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations. - -> **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". - +You can cancel your job
@@ -13823,22 +18045,11 @@ Notifies Intercom that a user provided a response to an attribute collector in y
```typescript -await client.unstable.customChannelEvents.notifyAttributeCollected({ - event_id: "evt_24680", - external_conversation_id: "conv_11223", - contact: { - type: "user", - external_id: "user_004", - name: "Bob Example", - email: "bob@example.com", - }, - attribute: { - id: "shipping_address", - value: "123 Main St, Springfield", - }, +await client.unstable.dataExport.cancelDataExport({ + job_identifier: "job_identifier" }); -``` +```
@@ -13852,28 +18063,27 @@ await client.unstable.customChannelEvents.notifyAttributeCollected({
-**request:** `Intercom.unstable.NotifyAttributeCollectedRequest` - +**request:** `Intercom.unstable.CancelDataExportRequest` +
-**requestOptions:** `CustomChannelEvents.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-## Custom Object Instances - -
client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstance | undefined +
client.unstable.dataExport.downloadDataExport({ ...params }) -> void
@@ -13885,8 +18095,13 @@ await client.unstable.customChannelEvents.notifyAttributeCollected({
-Fetch a Custom Object Instance by external_id. +When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + +Your exported message data will be streamed continuously back down to you in a gzipped CSV format. +> 📘 Octet header required +> +> You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint.
@@ -13901,12 +18116,11 @@ Fetch a Custom Object Instance by external_id.
```typescript -await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ - custom_object_type_identifier: "Order", - external_id: "external_id", +await client.unstable.dataExport.downloadDataExport({ + job_identifier: "job_identifier" }); -``` +```
@@ -13920,26 +18134,28 @@ await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId
-**request:** `Intercom.unstable.GetCustomObjectInstancesByExternalIdRequest` - +**request:** `Intercom.unstable.DownloadDataExportRequest` +
-**requestOptions:** `CustomObjectInstances.RequestOptions` - +**requestOptions:** `DataExportClient.RequestOptions` +
+
-
client.unstable.customObjectInstances.createCustomObjectInstances({ ...params }) -> Intercom.CustomObjectInstance | undefined +## Jobs +
client.unstable.jobs.status({ ...params }) -> Intercom.Jobs
@@ -13951,8 +18167,7 @@ await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId
-Create or update a custom object instance - +Retrieve the status of job execution.
@@ -13967,18 +18182,11 @@ Create or update a custom object instance
```typescript -await client.unstable.customObjectInstances.createCustomObjectInstances({ - custom_object_type_identifier: "Order", - external_id: "123", - external_created_at: 1392036272, - external_updated_at: 1392036272, - custom_attributes: { - order_number: "ORDER-12345", - total_amount: "custom_attributes", - }, +await client.unstable.jobs.status({ + id: "id" }); -``` +```
@@ -13992,26 +18200,28 @@ await client.unstable.customObjectInstances.createCustomObjectInstances({
-**request:** `Intercom.unstable.CreateOrUpdateCustomObjectInstanceRequest` - +**request:** `Intercom.unstable.JobsStatusRequest` +
-**requestOptions:** `CustomObjectInstances.RequestOptions` - +**requestOptions:** `JobsClient.RequestOptions` +
+
-
client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstanceDeleted +## Macros +
client.unstable.macros.listMacros({ ...params }) -> Intercom.MacroList
@@ -14023,8 +18233,19 @@ await client.unstable.customObjectInstances.createCustomObjectInstances({
-Delete a single Custom Object instance by external_id. +You can fetch a list of all macros (saved replies) in your workspace for use in automating responses. + +The macros are returned in descending order by updated_at. + +**Pagination** + +This endpoint uses cursor-based pagination via the `starting_after` parameter. The cursor is a Base64-encoded JSON array containing `[updated_at, id]` of the last item from the previous page. +**Placeholder Transformation** + +The API transforms Intercom placeholders to a more standard XML-like format: +- From: `{{user.name | fallback: 'there'}}` +- To: ``
@@ -14039,12 +18260,13 @@ Delete a single Custom Object instance by external_id.
```typescript -await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ - custom_object_type_identifier: "Order", - external_id: "external_id", +await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000 }); -``` +```
@@ -14058,26 +18280,27 @@ await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({
-**request:** `Intercom.unstable.DeleteCustomObjectInstancesByIdRequest` - +**request:** `Intercom.unstable.ListMacrosRequest` +
-**requestOptions:** `CustomObjectInstances.RequestOptions` - +**requestOptions:** `MacrosClient.RequestOptions` +
+
-
client.unstable.customObjectInstances.getCustomObjectInstancesById({ ...params }) -> Intercom.CustomObjectInstance | undefined +
client.unstable.macros.getMacro({ ...params }) -> Intercom.Macro | undefined
@@ -14089,8 +18312,23 @@ await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({
-Fetch a Custom Object Instance by id. +You can fetch a single macro (saved reply) by its ID. The macro will only be returned if it is visible to the authenticated user based on its visibility settings. + +**Visibility Rules** + +A macro is returned based on its `visible_to` setting: +- `everyone`: Always visible to all team members +- `specific_teams`: Only visible if the authenticated user belongs to one of the teams specified in `visible_to_team_ids` +If a macro exists but is not visible to the authenticated user, a 404 error is returned. + +**Placeholder Transformation** + +The API transforms Intercom placeholders to a more standard XML-like format in the `body` field: +- From: `{{user.name | fallback: 'there'}}` +- To: `` + +Default values in placeholders are HTML-escaped for security.
@@ -14105,12 +18343,11 @@ Fetch a Custom Object Instance by id.
```typescript -await client.unstable.customObjectInstances.getCustomObjectInstancesById({ - custom_object_type_identifier: "Order", - id: "id", +await client.unstable.macros.getMacro({ + id: "123" }); -``` +```
@@ -14124,26 +18361,28 @@ await client.unstable.customObjectInstances.getCustomObjectInstancesById({
-**request:** `Intercom.unstable.GetCustomObjectInstancesByIdRequest` - +**request:** `Intercom.unstable.GetMacroRequest` +
-**requestOptions:** `CustomObjectInstances.RequestOptions` - +**requestOptions:** `MacrosClient.RequestOptions` +
+
-
client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ ...params }) -> Intercom.CustomObjectInstanceDeleted +## Messages +
client.unstable.messages.createMessage({ ...params }) -> Intercom.Message
@@ -14155,8 +18394,17 @@ await client.unstable.customObjectInstances.getCustomObjectInstancesById({
-Delete a single Custom Object instance using the Intercom defined id. +You can create a message that has been initiated by an admin. The conversation can be either an in-app message, an email, sms or whatsapp. + +> 🚧 Sending for visitors +> +> There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case. + +This will return the Message model that has been created. +> 🚧 Retrieving Associated Conversations +> +> As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.
@@ -14171,12 +18419,16 @@ Delete a single Custom Object instance using the Intercom defined id.
```typescript -await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ - custom_object_type_identifier: "Order", - id: "id", +await client.unstable.messages.createMessage({ + "from": { + "type": "user", + "id": "6762f2341bb69f9f2193bc17" + }, + "body": "heyy", + "referer": "https://twitter.com/bob" }); -``` +```
@@ -14190,28 +18442,27 @@ await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExterna
-**request:** `Intercom.unstable.DeleteCustomObjectInstancesByExternalIdRequest` - +**request:** `Intercom.CreateMessageRequest | undefined` +
-**requestOptions:** `CustomObjectInstances.RequestOptions` - +**requestOptions:** `MessagesClient.RequestOptions` +
+
-## Data Attributes - -
client.unstable.dataAttributes.lisDataAttributes({ ...params }) -> Intercom.DataAttributeList +
client.unstable.messages.getWhatsAppMessageStatus({ ...params }) -> Intercom.WhatsappMessageStatusList
@@ -14223,8 +18474,11 @@ await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExterna
-You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. +Retrieves statuses of messages sent from the Outbound module. Currently, this API only supports WhatsApp messages. + +This endpoint returns paginated status events for WhatsApp messages sent via the Outbound module, providing +information about delivery state and related message details.
@@ -14239,9 +18493,13 @@ You can fetch a list of all data attributes belonging to a workspace for contact
```typescript -await client.unstable.dataAttributes.lisDataAttributes(); -``` +await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + per_page: 1, + starting_after: "starting_after" +}); +```
@@ -14255,26 +18513,28 @@ await client.unstable.dataAttributes.lisDataAttributes();
-**request:** `Intercom.unstable.LisDataAttributesRequest` - +**request:** `Intercom.unstable.GetWhatsAppMessageStatusRequest` +
-**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `MessagesClient.RequestOptions` +
+
-
client.unstable.dataAttributes.createDataAttribute({ ...params }) -> Intercom.DataAttribute +## News +
client.unstable.news.listNewsItems() -> Intercom.PaginatedResponse
@@ -14286,8 +18546,7 @@ await client.unstable.dataAttributes.lisDataAttributes();
-You can create a data attributes for a `contact` or a `company`. - +You can fetch a list of all news items
@@ -14302,13 +18561,9 @@ You can create a data attributes for a `contact` or a `company`.
```typescript -await client.unstable.dataAttributes.createDataAttribute({ - name: "Mithril Shirt", - model: "company", - data_type: "string", -}); -``` +await client.unstable.news.listNewsItems(); +```
@@ -14322,26 +18577,19 @@ await client.unstable.dataAttributes.createDataAttribute({
-**request:** `Intercom.unstable.CreateDataAttributeRequest` - -
-
- -
-
- -**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-
client.unstable.dataAttributes.updateDataAttribute({ ...params }) -> Intercom.DataAttribute +
client.unstable.news.createNewsItem({ ...params }) -> Intercom.NewsItem
@@ -14353,12 +18601,7 @@ await client.unstable.dataAttributes.createDataAttribute({
-You can update a data attribute. - -> 🚧 Updating the data type is not possible -> -> It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead. - +You can create a news item
@@ -14373,14 +18616,21 @@ You can update a data attribute.
```typescript -await client.unstable.dataAttributes.updateDataAttribute({ - id: 1, - archived: false, - description: "Just a plain old ring", - options: ["options", "options"], +await client.unstable.news.createNewsItem({ + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + newsfeed_assignments: [{ + newsfeed_id: 53, + published_at: 1664638214 + }] }); -``` +```
@@ -14394,28 +18644,27 @@ await client.unstable.dataAttributes.updateDataAttribute({
-**request:** `Intercom.unstable.UpdateDataAttributeRequest` - +**request:** `Intercom.NewsItemRequest` +
-**requestOptions:** `DataAttributes.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-## Data Events - -
client.unstable.dataEvents.lisDataEvents({ ...params }) -> Intercom.DataEventSummary +
client.unstable.news.retrieveNewsItem({ ...params }) -> Intercom.NewsItem
@@ -14427,20 +18676,7 @@ await client.unstable.dataAttributes.updateDataAttribute({
-> 🚧 -> -> Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days - -The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`. - -- `https://api.intercom.io/events?type=user&user_id={user_id}` -- `https://api.intercom.io/events?type=user&email={email}` -- `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads) - -The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending. - -You can optionally define the result page size as well with the `per_page` parameter. - +You can fetch the details of a single news item.
@@ -14455,14 +18691,11 @@ You can optionally define the result page size as well with the `per_page` param
```typescript -await client.unstable.dataEvents.lisDataEvents({ - filter: { - user_id: "user_id", - }, - type: "type", +await client.unstable.news.retrieveNewsItem({ + id: 1 }); -``` +```
@@ -14476,30 +18709,31 @@ await client.unstable.dataEvents.lisDataEvents({
-**request:** `Intercom.unstable.LisDataEventsRequest` - +**request:** `Intercom.unstable.RetrieveNewsItemRequest` +
-**requestOptions:** `DataEvents.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-
client.unstable.dataEvents.createDataEvent({ ...params }) -> void +
client.unstable.news.updateNewsItem({ ...params }) -> Intercom.NewsItem
-#### 📝 Description +#### 🔌 Usage
@@ -14507,50 +18741,68 @@ await client.unstable.dataEvents.lisDataEvents({
-You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`. +```typescript +await client.unstable.news.updateNewsItem({ + id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] + } +}); -When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event. +``` +
+
+
+
-With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`). +#### ⚙️ Parameters -**NB: For the JSON object types, please note that we do not currently support nested JSON structure.** +
+
-| Type | Description | Example | -| :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | -| String | The value is a JSON String | `"source":"desktop"` | -| Number | The value is a JSON Number | `"load": 3.67` | -| Date | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272` | -| Link | The value is a HTTP or HTTPS URI. | `"article": "https://example.org/ab1de.html"` | -| Rich Link | The value is a JSON object that contains `url` and `value` keys. | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` | -| Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | `"price": {"amount": 34999, "currency": "eur"}` | +
+
-**Lead Events** +**request:** `Intercom.unstable.UpdateNewsItemRequest` + +
+
-When submitting events for Leads, you will need to specify the Lead's `id`. +
+
-**Metadata behaviour** +**requestOptions:** `NewsClient.RequestOptions` + +
+
+
+
-- We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event. -- It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one. -- There might be up to 24 hrs delay when you send a new metadata for an existing event. -**Event de-duplication** +
+
+
-The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field. +
client.unstable.news.deleteNewsItem({ ...params }) -> Intercom.DeletedObject +
+
-Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place. +#### 📝 Description -### HTTP API Responses +
+
-- Successful responses to submitted events return `202 Accepted` with an empty body. -- Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code. -- Events sent about users that cannot be found will return a `404 Not Found`. -- Event lists containing duplicate events will have those duplicates ignored. -- Server errors will return a `500` response code and may contain an error message in the body. -
-
-
-
+
+
+ +You can delete a single news item. +
+
+ + #### 🔌 Usage @@ -14561,11 +18813,11 @@ Duplicated events are responded to using the normal `202 Accepted` code - an err
```typescript -await client.unstable.dataEvents.createDataEvent({ - key: "value", +await client.unstable.news.deleteNewsItem({ + id: 1 }); -``` +```
@@ -14579,26 +18831,27 @@ await client.unstable.dataEvents.createDataEvent({
-**request:** `Intercom.CreateDataEventRequestTwo` - +**request:** `Intercom.unstable.DeleteNewsItemRequest` +
-**requestOptions:** `DataEvents.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-
client.unstable.dataEvents.dataEventSummaries({ ...params }) -> void +
client.unstable.news.listLiveNewsfeedItems({ ...params }) -> Intercom.PaginatedResponse
@@ -14610,8 +18863,7 @@ await client.unstable.dataEvents.createDataEvent({
-Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. - +You can fetch a list of all news items that are live on a given newsfeed
@@ -14626,9 +18878,11 @@ Create event summaries for a user. Event summaries are used to track the number
```typescript -await client.unstable.dataEvents.dataEventSummaries(); -``` +await client.unstable.news.listLiveNewsfeedItems({ + id: "123" +}); +```
@@ -14642,28 +18896,27 @@ await client.unstable.dataEvents.dataEventSummaries();
-**request:** `Intercom.unstable.CreateDataEventSummariesRequest` - +**request:** `Intercom.unstable.ListLiveNewsfeedItemsRequest` +
-**requestOptions:** `DataEvents.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-## Data Export - -
client.unstable.dataExport.createDataExport({ ...params }) -> Intercom.DataExport +
client.unstable.news.listNewsfeeds() -> Intercom.PaginatedResponse
@@ -14675,22 +18928,7 @@ await client.unstable.dataEvents.dataEventSummaries();
-To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. - -The only parameters you need to provide are the range of dates that you want exported. - -> 🚧 Limit of one active job -> -> You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job. - -> ❗️ Updated_at not included -> -> It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job. - -> 📘 Date ranges are inclusive -> -> Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99. - +You can fetch a list of all newsfeeds
@@ -14705,12 +18943,9 @@ The only parameters you need to provide are the range of dates that you want exp
```typescript -await client.unstable.dataExport.createDataExport({ - created_at_after: 1734519776, - created_at_before: 1734537776, -}); -``` +await client.unstable.news.listNewsfeeds(); +```
@@ -14724,26 +18959,19 @@ await client.unstable.dataExport.createDataExport({
-**request:** `Intercom.unstable.CreateDataExportsRequest` - -
-
- -
-
- -**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-
client.unstable.dataExport.getDataExport({ ...params }) -> Intercom.DataExport +
client.unstable.news.retrieveNewsfeed({ ...params }) -> Intercom.Newsfeed
@@ -14755,12 +18983,7 @@ await client.unstable.dataExport.createDataExport({
-You can view the status of your job by sending a `GET` request to the URL -`https://api.intercom.io/export/content/data/{job_identifier}` - the `{job_identifier}` is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. - -> 🚧 Jobs expire after two days -> All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available. - +You can fetch the details of a single newsfeed
@@ -14775,11 +18998,11 @@ You can view the status of your job by sending a `GET` request to the URL
```typescript -await client.unstable.dataExport.getDataExport({ - job_identifier: "job_identifier", +await client.unstable.news.retrieveNewsfeed({ + id: "123" }); -``` +```
@@ -14793,26 +19016,28 @@ await client.unstable.dataExport.getDataExport({
-**request:** `Intercom.unstable.GetDataExportRequest` - +**request:** `Intercom.unstable.RetrieveNewsfeedRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `NewsClient.RequestOptions` +
+
-
client.unstable.dataExport.cancelDataExport({ ...params }) -> Intercom.DataExport +## Segments +
client.unstable.segments.listSegments({ ...params }) -> Intercom.SegmentList
@@ -14824,8 +19049,7 @@ await client.unstable.dataExport.getDataExport({
-You can cancel your job - +You can fetch a list of all segments.
@@ -14840,11 +19064,11 @@ You can cancel your job
```typescript -await client.unstable.dataExport.cancelDataExport({ - job_identifier: "job_identifier", +await client.unstable.segments.listSegments({ + include_count: true }); -``` +```
@@ -14858,26 +19082,27 @@ await client.unstable.dataExport.cancelDataExport({
-**request:** `Intercom.unstable.CancelDataExportRequest` - +**request:** `Intercom.unstable.ListSegmentsRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `SegmentsClient.RequestOptions` +
+
-
client.unstable.dataExport.downloadDataExport({ ...params }) -> void +
client.unstable.segments.retrieveSegment({ ...params }) -> Intercom.Segment
@@ -14889,14 +19114,7 @@ await client.unstable.dataExport.cancelDataExport({
-When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. - -Your exported message data will be streamed continuously back down to you in a gzipped CSV format. - -> 📘 Octet header required -> -> You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint. - +You can fetch the details of a single segment.
@@ -14911,11 +19129,11 @@ Your exported message data will be streamed continuously back down to you in a g
```typescript -await client.unstable.dataExport.downloadDataExport({ - job_identifier: "job_identifier", +await client.unstable.segments.retrieveSegment({ + id: "123" }); -``` +```
@@ -14929,28 +19147,28 @@ await client.unstable.dataExport.downloadDataExport({
-**request:** `Intercom.unstable.DownloadDataExportRequest` - +**request:** `Intercom.unstable.RetrieveSegmentRequest` +
-**requestOptions:** `DataExport.RequestOptions` - +**requestOptions:** `SegmentsClient.RequestOptions` +
+
-## Jobs - -
client.unstable.jobs.status({ ...params }) -> Intercom.Jobs +## Switch +
client.unstable.switch.createPhoneSwitch({ ...params }) -> Intercom.PhoneSwitch | undefined
@@ -14962,8 +19180,10 @@ await client.unstable.dataExport.downloadDataExport({
-Retrieve the status of job execution. +You can use the API to deflect phone calls to the Intercom Messenger. +Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. +If custom attributes are specified, they will be added to the user or lead's custom data attributes.
@@ -14978,11 +19198,11 @@ Retrieve the status of job execution.
```typescript -await client.unstable.jobs.status({ - id: "id", +await client.unstable.switch.createPhoneSwitch({ + "key": "value" }); -``` +```
@@ -14996,28 +19216,28 @@ await client.unstable.jobs.status({
-**request:** `Intercom.unstable.JobsStatusRequest` - +**request:** `unknown` +
-**requestOptions:** `Jobs.RequestOptions` - +**requestOptions:** `SwitchClient.RequestOptions` +
+
-## Messages - -
client.unstable.messages.createMessage({ ...params }) -> Intercom.Message +## Calls +
client.unstable.calls.listCalls({ ...params }) -> Intercom.CallList
@@ -15029,18 +19249,7 @@ await client.unstable.jobs.status({
-You can create a message that has been initiated by an admin. The conversation can be either an in-app message, an email or sms. - -> 🚧 Sending for visitors -> -> There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case. - -This will return the Message model that has been created. - -> 🚧 Retrieving Associated Conversations -> -> As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message. - +Retrieve a paginated list of calls.
@@ -15055,16 +19264,12 @@ This will return the Message model that has been created.
```typescript -await client.unstable.messages.createMessage({ - from: { - type: "user", - id: "6762f2341bb69f9f2193bc17", - }, - body: "heyy", - referer: "https://twitter.com/bob", +await client.unstable.calls.listCalls({ + page: 1, + per_page: 1 }); -``` +```
@@ -15078,26 +19283,27 @@ await client.unstable.messages.createMessage({
-**request:** `Intercom.CreateMessageRequestTwo` - +**request:** `Intercom.unstable.ListCallsRequest` +
-**requestOptions:** `Messages.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.messages.getWhatsAppMessageStatus({ ...params }) -> Intercom.WhatsappMessageStatusList +
client.unstable.calls.showCall({ ...params }) -> Intercom.Call
@@ -15109,11 +19315,7 @@ await client.unstable.messages.createMessage({
-Retrieves statuses of messages sent from the Outbound module. Currently, this API only supports WhatsApp messages. - -This endpoint returns paginated status events for WhatsApp messages sent via the Outbound module, providing -information about delivery state and related message details. - +Retrieve a single call by id.
@@ -15128,11 +19330,11 @@ information about delivery state and related message details.
```typescript -await client.unstable.messages.getWhatsAppMessageStatus({ - ruleset_id: "ruleset_id", +await client.unstable.calls.showCall({ + id: "id" }); -``` +```
@@ -15146,28 +19348,27 @@ await client.unstable.messages.getWhatsAppMessageStatus({
-**request:** `Intercom.unstable.GetWhatsAppMessageStatusRequest` - +**request:** `Intercom.unstable.ShowCallRequest` +
-**requestOptions:** `Messages.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-## News - -
client.unstable.news.listNewsItems() -> Intercom.PaginatedResponse +
client.unstable.calls.showCallRecording({ ...params }) -> void
@@ -15179,8 +19380,7 @@ await client.unstable.messages.getWhatsAppMessageStatus({
-You can fetch a list of all news items - +Redirects to a signed URL for the call's recording if it exists.
@@ -15195,9 +19395,11 @@ You can fetch a list of all news items
```typescript -await client.unstable.news.listNewsItems(); -``` +await client.unstable.calls.showCallRecording({ + id: "id" +}); +```
@@ -15211,18 +19413,27 @@ await client.unstable.news.listNewsItems();
-**requestOptions:** `News.RequestOptions` +**request:** `Intercom.unstable.ShowCallRecordingRequest` + +
+
+ +
+
+**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.createNewsItem({ ...params }) -> Intercom.NewsItem +
client.unstable.calls.showCallTranscript({ ...params }) -> string
@@ -15234,8 +19445,7 @@ await client.unstable.news.listNewsItems();
-You can create a news item - +Returns the transcript for the specified call as a downloadable text file.
@@ -15250,23 +19460,11 @@ You can create a news item
```typescript -await client.unstable.news.createNewsItem({ - title: "Halloween is here!", - body: "

New costumes in store for this spooky season

", - sender_id: 991267834, - state: "live", - deliver_silently: true, - labels: ["Product", "Update", "New"], - reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], - newsfeed_assignments: [ - { - newsfeed_id: 53, - published_at: 1664638214, - }, - ], +await client.unstable.calls.showCallTranscript({ + id: "id" }); -``` +```
@@ -15280,26 +19478,27 @@ await client.unstable.news.createNewsItem({
-**request:** `Intercom.NewsItemRequest` - +**request:** `Intercom.unstable.ShowCallTranscriptRequest` +
-**requestOptions:** `News.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.retrieveNewsItem({ ...params }) -> Intercom.NewsItem +
client.unstable.calls.listCallsWithTranscripts({ ...params }) -> Intercom.ListCallsWithTranscriptsResponse
@@ -15311,8 +19510,8 @@ await client.unstable.news.createNewsItem({
-You can fetch the details of a single news item. - +Retrieve calls by a list of conversation ids and include transcripts when available. +A maximum of 20 `conversation_ids` can be provided. If none are provided or more than 20 are provided, a 400 error is returned.
@@ -15327,11 +19526,11 @@ You can fetch the details of a single news item.
```typescript -await client.unstable.news.retrieveNewsItem({ - id: 1, +await client.unstable.calls.listCallsWithTranscripts({ + conversation_ids: ["64619700005694", "64619700005695"] }); -``` +```
@@ -15345,29 +19544,50 @@ await client.unstable.news.retrieveNewsItem({
-**request:** `Intercom.unstable.RetrieveNewsItemRequest` - -
-
- +**request:** `Intercom.unstable.ListCallsWithTranscriptsRequest` + + + + +
+
+ +**requestOptions:** `CallsClient.RequestOptions` + +
+
+ + + + + + +
+ +
client.unstable.calls.registerFinVoiceCall({ ...params }) -> Intercom.AiCallResponse +
+
+ +#### 📝 Description + +
+
+
-**requestOptions:** `News.RequestOptions` +Register a Fin Voice call with Intercom. This endpoint creates an external reference +that links an external call identifier to an Intercom call and conversation. +The call can be from different sources: +- AWS Connect (default) +- Five9 +- Zoom Phone
-
-
-
- -
client.unstable.news.updateNewsItem({ ...params }) -> Intercom.NewsItem -
-
- #### 🔌 Usage
@@ -15377,17 +19597,12 @@ await client.unstable.news.retrieveNewsItem({
```typescript -await client.unstable.news.updateNewsItem({ - id: 1, - body: { - title: "Christmas is here!", - body: "

New gifts in store for the jolly season

", - sender_id: 991267845, - reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], - }, +await client.unstable.calls.registerFinVoiceCall({ + phone_number: "+1234567890", + call_id: "call-123-abc" }); -``` +```
@@ -15401,26 +19616,27 @@ await client.unstable.news.updateNewsItem({
-**request:** `Intercom.unstable.UpdateNewsItemRequest` - +**request:** `Intercom.RegisterFinVoiceCallRequest` +
-**requestOptions:** `News.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.deleteNewsItem({ ...params }) -> Intercom.DeletedObject +
client.unstable.calls.collectFinVoiceCallById({ ...params }) -> Intercom.AiCallResponse
@@ -15432,8 +19648,7 @@ await client.unstable.news.updateNewsItem({
-You can delete a single news item. - +Retrieve information about a Fin Voice call using the external reference ID.
@@ -15448,11 +19663,11 @@ You can delete a single news item.
```typescript -await client.unstable.news.deleteNewsItem({ - id: 1, +await client.unstable.calls.collectFinVoiceCallById({ + id: 1 }); -``` +```
@@ -15466,26 +19681,27 @@ await client.unstable.news.deleteNewsItem({
-**request:** `Intercom.unstable.DeleteNewsItemRequest` - +**request:** `Intercom.unstable.CollectFinVoiceCallByIdRequest` +
-**requestOptions:** `News.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.listLiveNewsfeedItems({ ...params }) -> Intercom.PaginatedResponse +
client.unstable.calls.collectFinVoiceCallByExternalId({ ...params }) -> Intercom.AiCallResponse
@@ -15497,8 +19713,7 @@ await client.unstable.news.deleteNewsItem({
-You can fetch a list of all news items that are live on a given newsfeed - +Retrieve information about a Fin Voice call using the external call identifier.
@@ -15513,11 +19728,11 @@ You can fetch a list of all news items that are live on a given newsfeed
```typescript -await client.unstable.news.listLiveNewsfeedItems({ - id: "123", +await client.unstable.calls.collectFinVoiceCallByExternalId({ + external_id: "external_id" }); -``` +```
@@ -15531,26 +19746,27 @@ await client.unstable.news.listLiveNewsfeedItems({
-**request:** `Intercom.unstable.ListLiveNewsfeedItemsRequest` - +**request:** `Intercom.unstable.CollectFinVoiceCallByExternalIdRequest` +
-**requestOptions:** `News.RequestOptions` - +**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.listNewsfeeds() -> Intercom.PaginatedResponse +
client.unstable.calls.collectFinVoiceCallByPhoneNumber({ ...params }) -> Intercom.Error_
@@ -15562,8 +19778,9 @@ await client.unstable.news.listLiveNewsfeedItems({
-You can fetch a list of all newsfeeds +Retrieve information about a Fin Voice call using the phone number. +Returns the most recent matched call for the given phone number, ordered by creation date.
@@ -15578,9 +19795,11 @@ You can fetch a list of all newsfeeds
```typescript -await client.unstable.news.listNewsfeeds(); -``` +await client.unstable.calls.collectFinVoiceCallByPhoneNumber({ + phone_number: "phone_number" +}); +```
@@ -15594,18 +19813,28 @@ await client.unstable.news.listNewsfeeds();
-**requestOptions:** `News.RequestOptions` +**request:** `Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest` + +
+
+ +
+
+**requestOptions:** `CallsClient.RequestOptions` +
+
-
client.unstable.news.retrieveNewsfeed({ ...params }) -> Intercom.Newsfeed +## Teams +
client.unstable.teams.listTeams() -> Intercom.TeamList
@@ -15617,8 +19846,7 @@ await client.unstable.news.listNewsfeeds();
-You can fetch the details of a single newsfeed - +This will return a list of team objects for the App.
@@ -15633,11 +19861,9 @@ You can fetch the details of a single newsfeed
```typescript -await client.unstable.news.retrieveNewsfeed({ - id: "123", -}); -``` +await client.unstable.teams.listTeams(); +```
@@ -15651,28 +19877,19 @@ await client.unstable.news.retrieveNewsfeed({
-**request:** `Intercom.unstable.RetrieveNewsfeedRequest` - -
-
- -
-
- -**requestOptions:** `News.RequestOptions` - +**requestOptions:** `TeamsClient.RequestOptions` +
+
-## Segments - -
client.unstable.segments.listSegments({ ...params }) -> Intercom.SegmentList +
client.unstable.teams.retrieveTeam({ ...params }) -> Intercom.Team
@@ -15684,8 +19901,7 @@ await client.unstable.news.retrieveNewsfeed({
-You can fetch a list of all segments. - +You can fetch the details of a single team, containing an array of admins that belong to this team.
@@ -15700,9 +19916,11 @@ You can fetch a list of all segments.
```typescript -await client.unstable.segments.listSegments(); -``` +await client.unstable.teams.retrieveTeam({ + id: "123" +}); +```
@@ -15716,26 +19934,28 @@ await client.unstable.segments.listSegments();
-**request:** `Intercom.unstable.ListSegmentsRequest` - +**request:** `Intercom.unstable.RetrieveTeamRequest` +
-**requestOptions:** `Segments.RequestOptions` - +**requestOptions:** `TeamsClient.RequestOptions` +
+
-
client.unstable.segments.retrieveSegment({ ...params }) -> Intercom.Segment +## Ticket States +
client.unstable.ticketStates.listTicketStates() -> Intercom.TicketStateList
@@ -15747,8 +19967,7 @@ await client.unstable.segments.listSegments();
-You can fetch the details of a single segment. - +You can get a list of all ticket states for a workspace.
@@ -15763,11 +19982,9 @@ You can fetch the details of a single segment.
```typescript -await client.unstable.segments.retrieveSegment({ - id: "123", -}); -``` +await client.unstable.ticketStates.listTicketStates(); +```
@@ -15781,28 +19998,20 @@ await client.unstable.segments.retrieveSegment({
-**request:** `Intercom.unstable.RetrieveSegmentRequest` - -
-
- -
-
- -**requestOptions:** `Segments.RequestOptions` - +**requestOptions:** `TicketStatesClient.RequestOptions` +
+
-## Switch - -
client.unstable.switch.createPhoneSwitch({ ...params }) -> Intercom.PhoneSwitch | undefined +## Ticket Type Attributes +
client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ ...params }) -> Intercom.TicketTypeAttribute | undefined
@@ -15814,11 +20023,7 @@ await client.unstable.segments.retrieveSegment({
-You can use the API to deflect phone calls to the Intercom Messenger. -Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. - -If custom attributes are specified, they will be added to the user or lead's custom data attributes. - +You can create a new attribute for a ticket type.
@@ -15833,11 +20038,15 @@ If custom attributes are specified, they will be added to the user or lead's cus
```typescript -await client.unstable.switch.createPhoneSwitch({ - key: "value", +await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false }); -``` +```
@@ -15851,28 +20060,27 @@ await client.unstable.switch.createPhoneSwitch({
-**request:** `unknown` - +**request:** `Intercom.unstable.CreateTicketTypeAttributeRequest` +
-**requestOptions:** `Switch.RequestOptions` - +**requestOptions:** `TicketTypeAttributesClient.RequestOptions` +
+
-## Teams - -
client.unstable.teams.listTeams() -> Intercom.TeamList +
client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ ...params }) -> Intercom.TicketTypeAttribute | undefined
@@ -15884,8 +20092,7 @@ await client.unstable.switch.createPhoneSwitch({
-This will return a list of team objects for the App. - +You can update an existing attribute for a ticket type.
@@ -15900,9 +20107,13 @@ This will return a list of team objects for the App.
```typescript -await client.unstable.teams.listTeams(); -``` +await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + id: "id", + description: "New Attribute Description" +}); +```
@@ -15916,18 +20127,28 @@ await client.unstable.teams.listTeams();
-**requestOptions:** `Teams.RequestOptions` +**request:** `Intercom.unstable.UpdateTicketTypeAttributeRequest` + +
+
+ +
+
+**requestOptions:** `TicketTypeAttributesClient.RequestOptions` +
+
-
client.unstable.teams.retrieveTeam({ ...params }) -> Intercom.Team +## Ticket Types +
client.unstable.ticketTypes.listTicketTypes() -> Intercom.TicketTypeList
@@ -15939,8 +20160,7 @@ await client.unstable.teams.listTeams();
-You can fetch the details of a single team, containing an array of admins that belong to this team. - +You can get a list of all ticket types for a workspace.
@@ -15955,11 +20175,9 @@ You can fetch the details of a single team, containing an array of admins that b
```typescript -await client.unstable.teams.retrieveTeam({ - id: "123", -}); -``` +await client.unstable.ticketTypes.listTicketTypes(); +```
@@ -15973,28 +20191,19 @@ await client.unstable.teams.retrieveTeam({
-**request:** `Intercom.unstable.RetrieveTeamRequest` - -
-
- -
-
- -**requestOptions:** `Teams.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-## Ticket States - -
client.unstable.ticketStates.listTicketStates() -> Intercom.TicketStateList +
client.unstable.ticketTypes.createTicketType({ ...params }) -> Intercom.TicketType | undefined
@@ -16006,8 +20215,11 @@ await client.unstable.teams.retrieveTeam({
-You can get a list of all ticket states for a workspace. - +You can create a new ticket type. +> 📘 Creating ticket types. +> +> Every ticket type will be created with two default attributes: _default_title_ and _default_description_. +> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/)
@@ -16022,9 +20234,11 @@ You can get a list of all ticket states for a workspace.
```typescript -await client.unstable.ticketStates.listTicketStates(); -``` +await client.unstable.ticketTypes.createTicketType({ + "key": "value" +}); +```
@@ -16038,20 +20252,27 @@ await client.unstable.ticketStates.listTicketStates();
-**requestOptions:** `TicketStates.RequestOptions` +**request:** `unknown` + +
+
+ +
+
+**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-## Ticket Type Attributes - -
client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ ...params }) -> Intercom.TicketTypeAttribute | undefined +
client.unstable.ticketTypes.getTicketType({ ...params }) -> Intercom.TicketType | undefined
@@ -16063,8 +20284,7 @@ await client.unstable.ticketStates.listTicketStates();
-You can create a new attribute for a ticket type. - +You can fetch the details of a single ticket type.
@@ -16079,15 +20299,11 @@ You can create a new attribute for a ticket type.
```typescript -await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ - ticket_type_id: "ticket_type_id", - name: "Attribute Title", - description: "Attribute Description", - data_type: "string", - required_to_create: false, +await client.unstable.ticketTypes.getTicketType({ + id: "id" }); -``` +```
@@ -16101,26 +20317,28 @@ await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({
-**request:** `Intercom.unstable.CreateTicketTypeAttributeRequest` - +**request:** `Intercom.unstable.GetTicketTypeRequest` +
-**requestOptions:** `TicketTypeAttributes.RequestOptions` - +**requestOptions:** `TicketTypesClient.RequestOptions` +
+
-
client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ ...params }) -> Intercom.TicketTypeAttribute | undefined +## Tickets +
client.unstable.tickets.replyTicket({ ...params }) -> Intercom.TicketReply
@@ -16132,8 +20350,7 @@ await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({
-You can update an existing attribute for a ticket type. - +You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins.
@@ -16148,13 +20365,17 @@ You can update an existing attribute for a ticket type.
```typescript -await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ - ticket_type_id: "ticket_type_id", - id: "id", - description: "New Attribute Description", +await client.unstable.tickets.replyTicket({ + id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49" + } }); -``` +```
@@ -16168,28 +20389,27 @@ await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({
-**request:** `Intercom.unstable.UpdateTicketTypeAttributeRequest` - +**request:** `Intercom.unstable.ReplyTicketRequest` +
-**requestOptions:** `TicketTypeAttributes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-## Ticket Types - -
client.unstable.ticketTypes.listTicketTypes() -> Intercom.TicketTypeList +
client.unstable.tickets.enqueueCreateTicket({ ...params }) -> Intercom.Jobs
@@ -16201,8 +20421,7 @@ await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({
-You can get a list of all ticket types for a workspace. - +Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job.
@@ -16217,9 +20436,14 @@ You can get a list of all ticket types for a workspace.
```typescript -await client.unstable.ticketTypes.listTicketTypes(); -``` +await client.unstable.tickets.enqueueCreateTicket({ + ticket_type_id: "1234", + contacts: [{ + id: "6762f2d81bb69f9f2193bc54" + }] +}); +```
@@ -16233,18 +20457,27 @@ await client.unstable.ticketTypes.listTicketTypes();
-**requestOptions:** `TicketTypes.RequestOptions` - +**request:** `Intercom.unstable.EnqueueCreateTicketRequest` + +
+
+ +
+
+ +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.unstable.ticketTypes.createTicketType({ ...params }) -> Intercom.TicketType | undefined +
client.unstable.tickets.getTicket({ ...params }) -> Intercom.Ticket | undefined
@@ -16256,13 +20489,7 @@ await client.unstable.ticketTypes.listTicketTypes();
-You can create a new ticket type. - -> 📘 Creating ticket types. -> -> Every ticket type will be created with two default attributes: _default_title_ and _default_description_. -> For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) - +You can fetch the details of a single ticket.
@@ -16277,11 +20504,11 @@ You can create a new ticket type.
```typescript -await client.unstable.ticketTypes.createTicketType({ - key: "value", +await client.unstable.tickets.getTicket({ + id: "id" }); -``` +```
@@ -16295,26 +20522,27 @@ await client.unstable.ticketTypes.createTicketType({
-**request:** `unknown` - +**request:** `Intercom.unstable.GetTicketRequest` +
-**requestOptions:** `TicketTypes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.unstable.ticketTypes.getTicketType({ ...params }) -> Intercom.TicketType | undefined +
client.unstable.tickets.updateTicket({ ...params }) -> Intercom.Ticket | undefined
@@ -16326,8 +20554,7 @@ await client.unstable.ticketTypes.createTicketType({
-You can fetch the details of a single ticket type. - +You can update a ticket.
@@ -16342,11 +20569,20 @@ You can fetch the details of a single ticket type.
```typescript -await client.unstable.ticketTypes.getTicketType({ +await client.unstable.tickets.updateTicket({ id: "id", + ticket_attributes: { + "_default_title_": "example", + "_default_description_": "there is a problem" + }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123" }); -``` +```
@@ -16360,28 +20596,27 @@ await client.unstable.ticketTypes.getTicketType({
-**request:** `Intercom.unstable.GetTicketTypeRequest` - +**request:** `Intercom.unstable.UpdateTicketRequest` +
-**requestOptions:** `TicketTypes.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-## Tickets - -
client.unstable.tickets.replyTicket({ ...params }) -> Intercom.TicketReply +
client.unstable.tickets.deleteTicket({ ...params }) -> Intercom.DeleteTicketResponse
@@ -16393,8 +20628,7 @@ await client.unstable.ticketTypes.getTicketType({
-You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. - +You can delete a ticket using the Intercom provided ID.
@@ -16409,17 +20643,11 @@ You can reply to a ticket with a message from an admin or on behalf of a contact
```typescript -await client.unstable.tickets.replyTicket({ - id: "123", - body: { - message_type: "comment", - type: "user", - body: "Thanks again :)", - intercom_user_id: "6762f2971bb69f9f2193bc49", - }, +await client.unstable.tickets.deleteTicket({ + id: "id" }); -``` +```
@@ -16433,26 +20661,27 @@ await client.unstable.tickets.replyTicket({
-**request:** `Intercom.unstable.ReplyTicketRequest` - +**request:** `Intercom.unstable.DeleteTicketRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.unstable.tickets.enqueueCreateTicket({ ...params }) -> Intercom.Jobs +
client.unstable.tickets.searchTickets({ ...params }) -> Intercom.TicketList
@@ -16464,8 +20693,75 @@ await client.unstable.tickets.replyTicket({
-Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job. +You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. + +To search for tickets, you send a `POST` request to `https://api.intercom.io/tickets/search`. + +This will accept a query object in the body which will define your filters. +{% admonition type="warning" name="Optimizing search queries" %} + Search queries can be complex, so optimizing them can help the performance of your search. + Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize + pagination to limit the number of results returned. The default is `20` results per page. + See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. +{% /admonition %} + +### Nesting & Limitations + +You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). +There are some limitations to the amount of multiples there can be: +- There's a limit of max 2 nested filters +- There's a limit of max 15 filters for each AND or OR group + +### Accepted Fields + +Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foobar"`). +The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. + +| Field | Type | +| :---------------------------------------- | :--------------------------------------------------------------------------------------- | +| id | String | +| created_at | Date (UNIX timestamp) | +| updated_at | Date (UNIX timestamp) | +| title | String | +| description | String | +| category | String | +| ticket_type_id | String | +| contact_ids | String | +| teammate_ids | String | +| admin_assignee_id | String | +| team_assignee_id | String | +| open | Boolean | +| state | String | +| snoozed_until | Date (UNIX timestamp) | +| ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | + +{% admonition type="info" name="Searching by Category" %} +When searching for tickets by the **`category`** field, specific terms must be used instead of the category names: +* For **Customer** category tickets, use the term `request`. +* For **Back-office** category tickets, use the term `task`. +* For **Tracker** category tickets, use the term `tracker`. +{% /admonition %} + +### Accepted Operators + +{% admonition type="info" name="Searching based on `created_at`" %} + You may use the `<=` or `>=` operators to search by `created_at`. +{% /admonition %} +The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). + +| Operator | Valid Types | Description | +| :------- | :----------------------------- | :----------------------------------------------------------- | +| = | All | Equals | +| != | All | Doesn't Equal | +| IN | All | In Shortcut for `OR` queries Values most be in Array | +| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | +| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | +| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | +| ~ | String | Contains | +| !~ | String | Doesn't Contain | +| ^ | String | Starts With | +| $ | String | Ends With |
@@ -16480,16 +20776,21 @@ Enqueues ticket creation for asynchronous processing, returning if the job was e
```typescript -await client.unstable.tickets.enqueueCreateTicket({ - ticket_type_id: "1234", - contacts: [ - { - id: "6762f2d81bb69f9f2193bc54", - }, - ], +await client.unstable.tickets.searchTickets({ + query: { + operator: "AND", + value: [{ + field: "created_at", + operator: ">", + value: "1306054154" + }] + }, + pagination: { + per_page: 5 + } }); -``` +```
@@ -16503,26 +20804,28 @@ await client.unstable.tickets.enqueueCreateTicket({
-**request:** `Intercom.unstable.EnqueueCreateTicketRequest` - +**request:** `Intercom.SearchRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `TicketsClient.RequestOptions` +
+
-
client.unstable.tickets.getTicket({ ...params }) -> Intercom.Ticket | undefined +## Visitors +
client.unstable.visitors.retrieveVisitorWithUserId({ ...params }) -> Intercom.Visitor | undefined
@@ -16534,8 +20837,7 @@ await client.unstable.tickets.enqueueCreateTicket({
-You can fetch the details of a single ticket. - +You can fetch the details of a single visitor.
@@ -16550,11 +20852,11 @@ You can fetch the details of a single ticket.
```typescript -await client.unstable.tickets.getTicket({ - id: "id", +await client.unstable.visitors.retrieveVisitorWithUserId({ + user_id: "user_id" }); -``` +```
@@ -16568,26 +20870,27 @@ await client.unstable.tickets.getTicket({
-**request:** `Intercom.unstable.GetTicketRequest` - +**request:** `Intercom.unstable.RetrieveVisitorWithUserIdRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-
client.unstable.tickets.updateTicket({ ...params }) -> Intercom.Ticket | undefined +
client.unstable.visitors.updateVisitor({ ...params }) -> Intercom.Visitor | undefined
@@ -16599,8 +20902,11 @@ await client.unstable.tickets.getTicket({
-You can update a ticket. +Sending a PUT request to `/visitors` will result in an update of an existing Visitor. + +**Option 1.** You can update a visitor by passing in the `user_id` of the visitor in the Request body. +**Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body.
@@ -16615,20 +20921,12 @@ You can update a ticket.
```typescript -await client.unstable.tickets.updateTicket({ - id: "id", - ticket_attributes: { - _default_title_: "example", - _default_description_: "there is a problem", - }, - ticket_state_id: "123", - open: true, - snoozed_until: 1673609604, - admin_id: 991268011, - assignee_id: "123", +await client.unstable.visitors.updateVisitor({ + "id": "6762f30c1bb69f9f2193bc5e", + "name": "Gareth Bale" }); -``` +```
@@ -16642,26 +20940,27 @@ await client.unstable.tickets.updateTicket({
-**request:** `Intercom.unstable.UpdateTicketRequest` - +**request:** `Intercom.UpdateVisitorRequestOne` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-
client.unstable.tickets.deleteTicket({ ...params }) -> Intercom.DeleteTicketResponse +
client.unstable.visitors.convertVisitor({ ...params }) -> Intercom.Contact
@@ -16673,8 +20972,11 @@ await client.unstable.tickets.updateTicket({
-You can delete a ticket using the Intercom provided ID. +You can merge a Visitor to a Contact of role type `lead` or `user`. +> 📘 What happens upon a visitor being converted? +> +> If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.
@@ -16689,11 +20991,17 @@ You can delete a ticket using the Intercom provided ID.
```typescript -await client.unstable.tickets.deleteTicket({ - id: "id", +await client.unstable.visitors.convertVisitor({ + type: "user", + user: { + "email": "foo@bar.com" + }, + visitor: { + "user_id": "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3" + } }); -``` +```
@@ -16707,26 +21015,28 @@ await client.unstable.tickets.deleteTicket({
-**request:** `Intercom.unstable.DeleteTicketRequest` - +**request:** `Intercom.unstable.ConvertVisitorRequest` +
-**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `VisitorsClient.RequestOptions` +
+
-
client.unstable.tickets.searchTickets({ ...params }) -> Intercom.TicketList +## Brands +
client.unstable.brands.listBrands() -> Intercom.BrandList
@@ -16738,70 +21048,8 @@ await client.unstable.tickets.deleteTicket({
-You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. - -To search for tickets, you send a `POST` request to `https://api.intercom.io/tickets/search`. - -This will accept a query object in the body which will define your filters. -{% admonition type="warning" name="Optimizing search queries" %} -Search queries can be complex, so optimizing them can help the performance of your search. -Use the `AND` and `OR` operators to combine multiple filters to get the exact results you need and utilize -pagination to limit the number of results returned. The default is `20` results per page. -See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request) for more details on how to use the `starting_after` param. -{% /admonition %} - -### Nesting & Limitations - -You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). -There are some limitations to the amount of multiples there can be: - -- There's a limit of max 2 nested filters -- There's a limit of max 15 filters for each AND or OR group - -### Accepted Fields - -Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foobar"`). -The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. - -| Field | Type | -| :-------------------- | :------------------------------------------------------------- | -| id | String | -| created_at | Date (UNIX timestamp) | -| updated_at | Date (UNIX timestamp) | -| _default_title_ | String | -| _default_description_ | String | -| category | String | -| ticket_type_id | String | -| contact_ids | String | -| teammate_ids | String | -| admin_assignee_id | String | -| team_assignee_id | String | -| open | Boolean | -| state | String | -| snoozed_until | Date (UNIX timestamp) | -| ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | - -### Accepted Operators - -{% admonition type="info" name="Searching based on `created_at`" %} -You may use the `<=` or `>=` operators to search by `created_at`. -{% /admonition %} - -The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (`"="`). The operator has to be compatible with the field's type (eg. you cannot search with `>` for a given string value as it's only compatible for integer's and dates). - -| Operator | Valid Types | Description | -| :------- | :---------------------------- | :--------------------------------------------------------- | -| = | All | Equals | -| != | All | Doesn't Equal | -| IN | All | In Shortcut for `OR` queries Values most be in Array | -| NIN | All | Not In Shortcut for `OR !` queries Values must be in Array | -| > | Integer Date (UNIX Timestamp) | Greater (or equal) than | -| < | Integer Date (UNIX Timestamp) | Lower (or equal) than | -| ~ | String | Contains | -| !~ | String | Doesn't Contain | -| ^ | String | Starts With | -| $ | String | Ends With | - +Retrieves all brands for the workspace, including the default brand. +The default brand id always matches the workspace
@@ -16816,23 +21064,9 @@ The table below shows the operators you can use to define how you want to search
```typescript -await client.unstable.tickets.searchTickets({ - query: { - operator: "AND", - value: [ - { - field: "created_at", - operator: ">", - value: "1306054154", - }, - ], - }, - pagination: { - per_page: 5, - }, -}); -``` +await client.unstable.brands.listBrands(); +```
@@ -16846,28 +21080,19 @@ await client.unstable.tickets.searchTickets({
-**request:** `Intercom.SearchRequest` - -
-
- -
-
- -**requestOptions:** `Tickets.RequestOptions` - +**requestOptions:** `BrandsClient.RequestOptions` +
+
-## Visitors - -
client.unstable.visitors.retrieveVisitorWithUserId({ ...params }) -> Intercom.Visitor | undefined +
client.unstable.brands.retrieveBrand({ ...params }) -> Intercom.Brand
@@ -16879,8 +21104,7 @@ await client.unstable.tickets.searchTickets({
-You can fetch the details of a single visitor. - +Fetches a specific brand by its unique identifier
@@ -16895,11 +21119,11 @@ You can fetch the details of a single visitor.
```typescript -await client.unstable.visitors.retrieveVisitorWithUserId({ - user_id: "user_id", +await client.unstable.brands.retrieveBrand({ + id: "id" }); -``` +```
@@ -16913,26 +21137,28 @@ await client.unstable.visitors.retrieveVisitorWithUserId({
-**request:** `Intercom.unstable.RetrieveVisitorWithUserIdRequest` - +**request:** `Intercom.unstable.RetrieveBrandRequest` +
-**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `BrandsClient.RequestOptions` +
+
-
client.unstable.visitors.updateVisitor({ ...params }) -> Intercom.Visitor | undefined +## Emails +
client.unstable.emails.listEmails() -> Intercom.EmailList
@@ -16944,12 +21170,7 @@ await client.unstable.visitors.retrieveVisitorWithUserId({
-Sending a PUT request to `/visitors` will result in an update of an existing Visitor. - -**Option 1.** You can update a visitor by passing in the `user_id` of the visitor in the Request body. - -**Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body. - +Lists all sender email address settings for the workspace
@@ -16964,12 +21185,9 @@ Sending a PUT request to `/visitors` will result in an update of an existing Vis
```typescript -await client.unstable.visitors.updateVisitor({ - id: "6762f30c1bb69f9f2193bc5e", - name: "Gareth Bale", -}); -``` +await client.unstable.emails.listEmails(); +```
@@ -16983,26 +21201,19 @@ await client.unstable.visitors.updateVisitor({
-**request:** `Intercom.UpdateVisitorRequestOne` - -
-
- -
-
- -**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `EmailsClient.RequestOptions` +
+
-
client.unstable.visitors.convertVisitor({ ...params }) -> Intercom.Contact +
client.unstable.emails.retrieveEmail({ ...params }) -> Intercom.EmailSetting
@@ -17014,12 +21225,7 @@ await client.unstable.visitors.updateVisitor({
-You can merge a Visitor to a Contact of role type `lead` or `user`. - -> 📘 What happens upon a visitor being converted? -> -> If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers. - +Fetches a specific email setting by its unique identifier
@@ -17034,17 +21240,11 @@ You can merge a Visitor to a Contact of role type `lead` or `user`.
```typescript -await client.unstable.visitors.convertVisitor({ - type: "user", - user: { - email: "foo@bar.com", - }, - visitor: { - user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", - }, +await client.unstable.emails.retrieveEmail({ + id: "id" }); -``` +```
@@ -17058,21 +21258,22 @@ await client.unstable.visitors.convertVisitor({
-**request:** `Intercom.unstable.ConvertVisitorRequest` - +**request:** `Intercom.unstable.RetrieveEmailRequest` +
-**requestOptions:** `Visitors.RequestOptions` - +**requestOptions:** `EmailsClient.RequestOptions` +
+
diff --git a/scripts/rename-to-esm-files.js b/scripts/rename-to-esm-files.js index 81dac6a7..dc1df1cb 100644 --- a/scripts/rename-to-esm-files.js +++ b/scripts/rename-to-esm-files.js @@ -50,8 +50,16 @@ async function updateFileContents(file) { let newContent = content; // Update each extension type defined in the map for (const [oldExt, newExt] of Object.entries(extensionMap)) { - const regex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g"); - newContent = newContent.replace(regex, `$1$2$3${newExt}$5`); + // Handle static imports/exports + const staticRegex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g"); + newContent = newContent.replace(staticRegex, `$1$2$3${newExt}$5`); + + // Handle dynamic imports (yield import, await import, regular import()) + const dynamicRegex = new RegExp( + `(yield\\s+import|await\\s+import|import)\\s*\\(\\s*['"](\\.\\.\?\\/[^'"]+)(\\${oldExt})['"]\\s*\\)`, + "g", + ); + newContent = newContent.replace(dynamicRegex, `$1("$2${newExt}")`); } if (content !== newContent) { diff --git a/src/BaseClient.ts b/src/BaseClient.ts new file mode 100644 index 00000000..45d31870 --- /dev/null +++ b/src/BaseClient.ts @@ -0,0 +1,131 @@ +// This file was auto-generated by Fern from our API Definition. + +import { BearerAuthProvider } from "./auth/BearerAuthProvider.js"; +import { mergeHeaders } from "./core/headers.js"; +import * as core from "./core/index.js"; +import type * as environments from "./environments.js"; + +export interface BaseClientOptions { + environment?: core.Supplier; + /** Specify a custom URL to connect the client to. */ + baseUrl?: core.Supplier; + token?: core.Supplier; + /** Override the Intercom-Version header */ + version?: + | "1.0" + | "1.1" + | "1.2" + | "1.3" + | "1.4" + | "2.0" + | "2.1" + | "2.2" + | "2.3" + | "2.4" + | "2.5" + | "2.6" + | "2.7" + | "2.8" + | "2.9" + | "2.10" + | "2.11" + | "2.12" + | "2.13" + | "2.14" + | "Unstable"; + /** Additional headers to include in requests. */ + headers?: Record | null | undefined>; + /** The default maximum time to wait for a response in seconds. */ + timeoutInSeconds?: number; + /** The default number of times to retry the request. Defaults to 2. */ + maxRetries?: number; + /** Provide a custom fetch implementation. Useful for platforms that don't have a built-in fetch or need a custom implementation. */ + fetch?: typeof fetch; + fetcher?: core.FetchFunction; + /** Configure logging for the client. */ + logging?: core.logging.LogConfig | core.logging.Logger; +} + +export interface BaseRequestOptions { + /** The maximum time to wait for a response in seconds. */ + timeoutInSeconds?: number; + /** The number of times to retry the request. Defaults to 2. */ + maxRetries?: number; + /** A hook to abort the request. */ + abortSignal?: AbortSignal; + /** Additional query string parameters to include in the request. */ + queryParams?: Record; + /** Additional headers to include in the request. */ + headers?: Record | null | undefined>; + /** Override the Intercom-Version header */ + version?: + | "1.0" + | "1.1" + | "1.2" + | "1.3" + | "1.4" + | "2.0" + | "2.1" + | "2.2" + | "2.3" + | "2.4" + | "2.5" + | "2.6" + | "2.7" + | "2.8" + | "2.9" + | "2.10" + | "2.11" + | "2.12" + | "2.13" + | "2.14" + | "Unstable"; +} + +export type NormalizedClientOptions = T & { + logging: core.logging.Logger; + authProvider?: core.AuthProvider; +}; + +export type NormalizedClientOptionsWithAuth = NormalizedClientOptions & { + authProvider: core.AuthProvider; +}; + +export function normalizeClientOptions(options: T): NormalizedClientOptions { + const headers = mergeHeaders( + { + "X-Fern-Language": "JavaScript", + "X-Fern-SDK-Name": "intercom-client", + "X-Fern-SDK-Version": "7.0.0", + "User-Agent": "intercom-client/7.0.0", + "X-Fern-Runtime": core.RUNTIME.type, + "X-Fern-Runtime-Version": core.RUNTIME.version, + "Intercom-Version": options?.version ?? "2.14", + }, + options?.headers, + ); + + return { + ...options, + logging: core.logging.createLogger(options?.logging), + headers, + } as NormalizedClientOptions; +} + +export function normalizeClientOptionsWithAuth( + options: T, +): NormalizedClientOptionsWithAuth { + const normalized = normalizeClientOptions(options) as NormalizedClientOptionsWithAuth; + const normalizedWithNoOpAuthProvider = withNoOpAuthProvider(normalized); + normalized.authProvider ??= new BearerAuthProvider(normalizedWithNoOpAuthProvider); + return normalized; +} + +function withNoOpAuthProvider( + options: NormalizedClientOptions, +): NormalizedClientOptionsWithAuth { + return { + ...options, + authProvider: new core.NoOpAuthProvider(), + }; +} diff --git a/src/Client.ts b/src/Client.ts index bdbba22c..8db0d729 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -1,198 +1,198 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as environments from "./environments"; -import * as core from "./core"; -import { Admins } from "./api/resources/admins/client/Client"; -import { Articles } from "./api/resources/articles/client/Client"; -import { HelpCenters } from "./api/resources/helpCenters/client/Client"; -import { Companies } from "./api/resources/companies/client/Client"; -import { Contacts } from "./api/resources/contacts/client/Client"; -import { Notes } from "./api/resources/notes/client/Client"; -import { Tags } from "./api/resources/tags/client/Client"; -import { Conversations } from "./api/resources/conversations/client/Client"; -import { DataAttributes } from "./api/resources/dataAttributes/client/Client"; -import { Events } from "./api/resources/events/client/Client"; -import { DataExport } from "./api/resources/dataExport/client/Client"; -import { Messages } from "./api/resources/messages/client/Client"; -import { Segments } from "./api/resources/segments/client/Client"; -import { SubscriptionTypes } from "./api/resources/subscriptionTypes/client/Client"; -import { PhoneCallRedirects } from "./api/resources/phoneCallRedirects/client/Client"; -import { Teams } from "./api/resources/teams/client/Client"; -import { TicketTypes } from "./api/resources/ticketTypes/client/Client"; -import { Tickets } from "./api/resources/tickets/client/Client"; -import { Visitors } from "./api/resources/visitors/client/Client"; -import { News } from "./api/resources/news/client/Client"; -import { Unstable } from "./api/resources/unstable/client/Client"; +// This file was auto-generated by Fern from our API Definition. + +import { AdminsClient } from "./api/resources/admins/client/Client.js"; +import { AiContentClient } from "./api/resources/aiContent/client/Client.js"; +import { ArticlesClient } from "./api/resources/articles/client/Client.js"; +import { AwayStatusReasonsClient } from "./api/resources/awayStatusReasons/client/Client.js"; +import { CallsClient } from "./api/resources/calls/client/Client.js"; +import { CompaniesClient } from "./api/resources/companies/client/Client.js"; +import { ContactsClient } from "./api/resources/contacts/client/Client.js"; +import { ConversationsClient } from "./api/resources/conversations/client/Client.js"; +import { CustomChannelEventsClient } from "./api/resources/customChannelEvents/client/Client.js"; +import { CustomObjectInstancesClient } from "./api/resources/customObjectInstances/client/Client.js"; +import { DataAttributesClient } from "./api/resources/dataAttributes/client/Client.js"; +import { DataExportClient } from "./api/resources/dataExport/client/Client.js"; +import { EventsClient } from "./api/resources/events/client/Client.js"; +import { ExportClient } from "./api/resources/export/client/Client.js"; +import { HelpCentersClient } from "./api/resources/helpCenters/client/Client.js"; +import { InternalArticlesClient } from "./api/resources/internalArticles/client/Client.js"; +import { JobsClient } from "./api/resources/jobs/client/Client.js"; +import { MessagesClient } from "./api/resources/messages/client/Client.js"; +import { NewsClient } from "./api/resources/news/client/Client.js"; +import { NotesClient } from "./api/resources/notes/client/Client.js"; +import { PhoneCallRedirectsClient } from "./api/resources/phoneCallRedirects/client/Client.js"; +import { SegmentsClient } from "./api/resources/segments/client/Client.js"; +import { SubscriptionTypesClient } from "./api/resources/subscriptionTypes/client/Client.js"; +import { TagsClient } from "./api/resources/tags/client/Client.js"; +import { TeamsClient } from "./api/resources/teams/client/Client.js"; +import { TicketStatesClient } from "./api/resources/ticketStates/client/Client.js"; +import { TicketsClient } from "./api/resources/tickets/client/Client.js"; +import { TicketTypesClient } from "./api/resources/ticketTypes/client/Client.js"; +import { UnstableClient } from "./api/resources/unstable/client/Client.js"; +import { VisitorsClient } from "./api/resources/visitors/client/Client.js"; +import type { BaseClientOptions, BaseRequestOptions } from "./BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "./BaseClient.js"; export declare namespace IntercomClient { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } - - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } export class IntercomClient { - protected _admins: Admins | undefined; - protected _articles: Articles | undefined; - protected _helpCenters: HelpCenters | undefined; - protected _companies: Companies | undefined; - protected _contacts: Contacts | undefined; - protected _notes: Notes | undefined; - protected _tags: Tags | undefined; - protected _conversations: Conversations | undefined; - protected _dataAttributes: DataAttributes | undefined; - protected _events: Events | undefined; - protected _dataExport: DataExport | undefined; - protected _messages: Messages | undefined; - protected _segments: Segments | undefined; - protected _subscriptionTypes: SubscriptionTypes | undefined; - protected _phoneCallRedirects: PhoneCallRedirects | undefined; - protected _teams: Teams | undefined; - protected _ticketTypes: TicketTypes | undefined; - protected _tickets: Tickets | undefined; - protected _visitors: Visitors | undefined; - protected _news: News | undefined; - protected _unstable: Unstable | undefined; + protected readonly _options: NormalizedClientOptionsWithAuth; + protected _admins: AdminsClient | undefined; + protected _aiContent: AiContentClient | undefined; + protected _articles: ArticlesClient | undefined; + protected _awayStatusReasons: AwayStatusReasonsClient | undefined; + protected _export: ExportClient | undefined; + protected _dataExport: DataExportClient | undefined; + protected _helpCenters: HelpCentersClient | undefined; + protected _internalArticles: InternalArticlesClient | undefined; + protected _companies: CompaniesClient | undefined; + protected _contacts: ContactsClient | undefined; + protected _notes: NotesClient | undefined; + protected _tags: TagsClient | undefined; + protected _conversations: ConversationsClient | undefined; + protected _customChannelEvents: CustomChannelEventsClient | undefined; + protected _customObjectInstances: CustomObjectInstancesClient | undefined; + protected _dataAttributes: DataAttributesClient | undefined; + protected _events: EventsClient | undefined; + protected _jobs: JobsClient | undefined; + protected _messages: MessagesClient | undefined; + protected _segments: SegmentsClient | undefined; + protected _subscriptionTypes: SubscriptionTypesClient | undefined; + protected _phoneCallRedirects: PhoneCallRedirectsClient | undefined; + protected _calls: CallsClient | undefined; + protected _teams: TeamsClient | undefined; + protected _ticketStates: TicketStatesClient | undefined; + protected _ticketTypes: TicketTypesClient | undefined; + protected _tickets: TicketsClient | undefined; + protected _visitors: VisitorsClient | undefined; + protected _news: NewsClient | undefined; + protected _unstable: UnstableClient | undefined; + + constructor(options: IntercomClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + public get admins(): AdminsClient { + return (this._admins ??= new AdminsClient(this._options)); + } - constructor(protected readonly _options: IntercomClient.Options = {}) {} + public get aiContent(): AiContentClient { + return (this._aiContent ??= new AiContentClient(this._options)); + } + + public get articles(): ArticlesClient { + return (this._articles ??= new ArticlesClient(this._options)); + } + + public get awayStatusReasons(): AwayStatusReasonsClient { + return (this._awayStatusReasons ??= new AwayStatusReasonsClient(this._options)); + } + + public get export(): ExportClient { + return (this._export ??= new ExportClient(this._options)); + } + + public get dataExport(): DataExportClient { + return (this._dataExport ??= new DataExportClient(this._options)); + } + + public get helpCenters(): HelpCentersClient { + return (this._helpCenters ??= new HelpCentersClient(this._options)); + } + + public get internalArticles(): InternalArticlesClient { + return (this._internalArticles ??= new InternalArticlesClient(this._options)); + } + + public get companies(): CompaniesClient { + return (this._companies ??= new CompaniesClient(this._options)); + } - public get admins(): Admins { - return (this._admins ??= new Admins(this._options)); + public get contacts(): ContactsClient { + return (this._contacts ??= new ContactsClient(this._options)); } - public get articles(): Articles { - return (this._articles ??= new Articles(this._options)); + public get notes(): NotesClient { + return (this._notes ??= new NotesClient(this._options)); } - public get helpCenters(): HelpCenters { - return (this._helpCenters ??= new HelpCenters(this._options)); + public get tags(): TagsClient { + return (this._tags ??= new TagsClient(this._options)); } - public get companies(): Companies { - return (this._companies ??= new Companies(this._options)); + public get conversations(): ConversationsClient { + return (this._conversations ??= new ConversationsClient(this._options)); } - public get contacts(): Contacts { - return (this._contacts ??= new Contacts(this._options)); + public get customChannelEvents(): CustomChannelEventsClient { + return (this._customChannelEvents ??= new CustomChannelEventsClient(this._options)); } - public get notes(): Notes { - return (this._notes ??= new Notes(this._options)); + public get customObjectInstances(): CustomObjectInstancesClient { + return (this._customObjectInstances ??= new CustomObjectInstancesClient(this._options)); } - public get tags(): Tags { - return (this._tags ??= new Tags(this._options)); + public get dataAttributes(): DataAttributesClient { + return (this._dataAttributes ??= new DataAttributesClient(this._options)); } - public get conversations(): Conversations { - return (this._conversations ??= new Conversations(this._options)); + public get events(): EventsClient { + return (this._events ??= new EventsClient(this._options)); } - public get dataAttributes(): DataAttributes { - return (this._dataAttributes ??= new DataAttributes(this._options)); + public get jobs(): JobsClient { + return (this._jobs ??= new JobsClient(this._options)); } - public get events(): Events { - return (this._events ??= new Events(this._options)); + public get messages(): MessagesClient { + return (this._messages ??= new MessagesClient(this._options)); } - public get dataExport(): DataExport { - return (this._dataExport ??= new DataExport(this._options)); + public get segments(): SegmentsClient { + return (this._segments ??= new SegmentsClient(this._options)); } - public get messages(): Messages { - return (this._messages ??= new Messages(this._options)); + public get subscriptionTypes(): SubscriptionTypesClient { + return (this._subscriptionTypes ??= new SubscriptionTypesClient(this._options)); } - public get segments(): Segments { - return (this._segments ??= new Segments(this._options)); + public get phoneCallRedirects(): PhoneCallRedirectsClient { + return (this._phoneCallRedirects ??= new PhoneCallRedirectsClient(this._options)); } - public get subscriptionTypes(): SubscriptionTypes { - return (this._subscriptionTypes ??= new SubscriptionTypes(this._options)); + public get calls(): CallsClient { + return (this._calls ??= new CallsClient(this._options)); } - public get phoneCallRedirects(): PhoneCallRedirects { - return (this._phoneCallRedirects ??= new PhoneCallRedirects(this._options)); + public get teams(): TeamsClient { + return (this._teams ??= new TeamsClient(this._options)); } - public get teams(): Teams { - return (this._teams ??= new Teams(this._options)); + public get ticketStates(): TicketStatesClient { + return (this._ticketStates ??= new TicketStatesClient(this._options)); } - public get ticketTypes(): TicketTypes { - return (this._ticketTypes ??= new TicketTypes(this._options)); + public get ticketTypes(): TicketTypesClient { + return (this._ticketTypes ??= new TicketTypesClient(this._options)); } - public get tickets(): Tickets { - return (this._tickets ??= new Tickets(this._options)); + public get tickets(): TicketsClient { + return (this._tickets ??= new TicketsClient(this._options)); } - public get visitors(): Visitors { - return (this._visitors ??= new Visitors(this._options)); + public get visitors(): VisitorsClient { + return (this._visitors ??= new VisitorsClient(this._options)); } - public get news(): News { - return (this._news ??= new News(this._options)); + public get news(): NewsClient { + return (this._news ??= new NewsClient(this._options)); } - public get unstable(): Unstable { - return (this._unstable ??= new Unstable(this._options)); + public get unstable(): UnstableClient { + return (this._unstable ??= new UnstableClient(this._options)); } } diff --git a/src/api/errors/BadRequestError.ts b/src/api/errors/BadRequestError.ts index 6d3e423f..90b9567c 100644 --- a/src/api/errors/BadRequestError.ts +++ b/src/api/errors/BadRequestError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../errors/index"; -import * as core from "../../core"; +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; export class BadRequestError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/errors/ForbiddenError.ts b/src/api/errors/ForbiddenError.ts index 45a3327c..3d3e38f8 100644 --- a/src/api/errors/ForbiddenError.ts +++ b/src/api/errors/ForbiddenError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../errors/index"; -import * as Intercom from "../index"; -import * as core from "../../core"; +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; +import type * as Intercom from "../index.js"; export class ForbiddenError extends errors.IntercomError { constructor(body: Intercom.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/errors/NotFoundError.ts b/src/api/errors/NotFoundError.ts index e99cdf65..e097f867 100644 --- a/src/api/errors/NotFoundError.ts +++ b/src/api/errors/NotFoundError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../errors/index"; -import * as core from "../../core"; +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; export class NotFoundError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/errors/TooManyRequestsError.ts b/src/api/errors/TooManyRequestsError.ts new file mode 100644 index 00000000..713f4ece --- /dev/null +++ b/src/api/errors/TooManyRequestsError.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; +import type * as Intercom from "../index.js"; + +export class TooManyRequestsError extends errors.IntercomError { + constructor(body: Intercom.Error_, rawResponse?: core.RawResponse) { + super({ + message: "TooManyRequestsError", + statusCode: 429, + body: body, + rawResponse: rawResponse, + }); + Object.setPrototypeOf(this, TooManyRequestsError.prototype); + } +} diff --git a/src/api/errors/UnauthorizedError.ts b/src/api/errors/UnauthorizedError.ts index 0cafa7ae..16bbd3af 100644 --- a/src/api/errors/UnauthorizedError.ts +++ b/src/api/errors/UnauthorizedError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../errors/index"; -import * as Intercom from "../index"; -import * as core from "../../core"; +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; +import type * as Intercom from "../index.js"; export class UnauthorizedError extends errors.IntercomError { constructor(body: Intercom.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/errors/UnprocessableEntityError.ts b/src/api/errors/UnprocessableEntityError.ts index 7bb55289..ab175870 100644 --- a/src/api/errors/UnprocessableEntityError.ts +++ b/src/api/errors/UnprocessableEntityError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../errors/index"; -import * as core from "../../core"; +import type * as core from "../../core/index.js"; +import * as errors from "../../errors/index.js"; export class UnprocessableEntityError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/errors/index.ts b/src/api/errors/index.ts index f81dc80f..a8a67c9f 100644 --- a/src/api/errors/index.ts +++ b/src/api/errors/index.ts @@ -1,5 +1,6 @@ -export * from "./UnauthorizedError"; -export * from "./NotFoundError"; -export * from "./BadRequestError"; -export * from "./ForbiddenError"; -export * from "./UnprocessableEntityError"; +export * from "./BadRequestError.js"; +export * from "./ForbiddenError.js"; +export * from "./NotFoundError.js"; +export * from "./TooManyRequestsError.js"; +export * from "./UnauthorizedError.js"; +export * from "./UnprocessableEntityError.js"; diff --git a/src/api/index.ts b/src/api/index.ts index fefdd8f9..f847ea3d 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,4 +1,4 @@ -export * from "./resources"; -export * from "./types"; -export * from "./errors"; -export { IntercomVersion } from "./version"; +export * from "./errors/index.js"; +export * from "./resources/index.js"; +export * from "./types/index.js"; +export type { IntercomVersion } from "./version.js"; diff --git a/src/api/resources/admins/client/Client.ts b/src/api/resources/admins/client/Client.ts index 007cc89c..f836356f 100644 --- a/src/api/resources/admins/client/Client.ts +++ b/src/api/resources/admins/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Admins { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace AdminsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Admins */ -export class Admins { - constructor(protected readonly _options: Admins.Options = {}) {} +export class AdminsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AdminsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * @@ -83,45 +33,45 @@ export class Admins { * > * > If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk. * - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.admins.identify() */ - public identify(requestOptions?: Admins.RequestOptions): core.HttpResponsePromise { + public identify( + requestOptions?: AdminsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__identify(requestOptions)); } private async __identify( - requestOptions?: Admins.RequestOptions, - ): Promise> { + requestOptions?: AdminsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "me", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.AdminWithApp, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.AdminWithApp | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -132,83 +82,80 @@ export class Admins { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /me."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/me"); } /** * You can set an Admin as away for the Inbox. * * @param {Intercom.ConfigureAwayAdminRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * + * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.admins.away({ - * admin_id: "admin_id", + * admin_id: 1, + * away_mode_enabled: true, + * away_mode_reassign: true, + * away_status_reason_id: 12345 + * }) + * + * @example + * await client.admins.away({ + * admin_id: 1, * away_mode_enabled: true, * away_mode_reassign: true * }) */ public away( request: Intercom.ConfigureAwayAdminRequest, - requestOptions?: Admins.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: AdminsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__away(request, requestOptions)); } private async __away( request: Intercom.ConfigureAwayAdminRequest, - requestOptions?: Admins.RequestOptions, - ): Promise> { + requestOptions?: AdminsClient.RequestOptions, + ): Promise> { const { admin_id: adminId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `admins/${encodeURIComponent(adminId)}/away`, + `admins/${core.url.encodePathParam(adminId)}/away`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Admin, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Admin | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); case 401: throw new Intercom.UnauthorizedError( _response.error.body as Intercom.Error_, @@ -225,28 +172,14 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /admins/{admin_id}/away."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/admins/{admin_id}/away"); } /** * You can get a log of activities by all admins in an app. * * @param {Intercom.ListAllActivityLogsRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -258,47 +191,44 @@ export class Admins { */ public listAllActivityLogs( request: Intercom.ListAllActivityLogsRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAllActivityLogs(request, requestOptions)); } private async __listAllActivityLogs( request: Intercom.ListAllActivityLogsRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { const { created_at_after: createdAtAfter, created_at_before: createdAtBefore } = request; const _queryParams: Record = {}; - _queryParams["created_at_after"] = createdAtAfter; + _queryParams.created_at_after = createdAtAfter; if (createdAtBefore != null) { - _queryParams["created_at_before"] = createdAtBefore; + _queryParams.created_at_before = createdAtBefore; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "admins/activity_logs", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ActivityLogList, rawResponse: _response.rawResponse }; @@ -320,62 +250,48 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins/activity_logs."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins/activity_logs"); } /** * You can fetch a list of admins for a given workspace. * - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.admins.list() */ - public list(requestOptions?: Admins.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: AdminsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } - private async __list(requestOptions?: Admins.RequestOptions): Promise> { + private async __list( + requestOptions?: AdminsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "admins", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.AdminList, rawResponse: _response.rawResponse }; @@ -397,76 +313,60 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins"); } /** * You can retrieve the details of a single admin. * * @param {Intercom.FindAdminRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.admins.find({ - * admin_id: "123" + * admin_id: 1 * }) */ public find( request: Intercom.FindAdminRequest, - requestOptions?: Admins.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: AdminsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindAdminRequest, - requestOptions?: Admins.RequestOptions, - ): Promise> { + requestOptions?: AdminsClient.RequestOptions, + ): Promise> { const { admin_id: adminId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `admins/${encodeURIComponent(adminId)}`, + `admins/${core.url.encodePathParam(adminId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Admin, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Admin | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -487,32 +387,6 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins/{admin_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins/{admin_id}"); } } diff --git a/src/api/resources/admins/client/index.ts b/src/api/resources/admins/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/admins/client/index.ts +++ b/src/api/resources/admins/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/admins/client/requests/ConfigureAwayAdminRequest.ts b/src/api/resources/admins/client/requests/ConfigureAwayAdminRequest.ts index 524d1a23..0e21602b 100644 --- a/src/api/resources/admins/client/requests/ConfigureAwayAdminRequest.ts +++ b/src/api/resources/admins/client/requests/ConfigureAwayAdminRequest.ts @@ -1,36 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * admin_id: "admin_id", + * admin_id: 1, * away_mode_enabled: true, - * away_mode_reassign: true + * away_mode_reassign: true, + * away_status_reason_id: 12345 * } * * @example * { - * admin_id: "admin_id", + * admin_id: 1, * away_mode_enabled: true, * away_mode_reassign: true * } * * @example * { - * admin_id: "admin_id", + * admin_id: 1, * away_mode_enabled: true, * away_mode_reassign: true * } */ export interface ConfigureAwayAdminRequest { - /** - * The unique identifier of a given admin - */ - admin_id: string; + /** The unique identifier of a given admin */ + admin_id: number; /** Set to "true" to change the status of the admin to away. */ away_mode_enabled: boolean; /** Set to "true" to assign any new conversation replies to your default inbox. */ away_mode_reassign: boolean; + /** The unique identifier of the away status reason */ + away_status_reason_id?: number; } diff --git a/src/api/resources/admins/client/requests/FindAdminRequest.ts b/src/api/resources/admins/client/requests/FindAdminRequest.ts index 85d66282..46f8a13f 100644 --- a/src/api/resources/admins/client/requests/FindAdminRequest.ts +++ b/src/api/resources/admins/client/requests/FindAdminRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * admin_id: "123" + * admin_id: 1 * } */ export interface FindAdminRequest { - /** - * The unique identifier of a given admin - */ - admin_id: string; + /** The unique identifier of a given admin */ + admin_id: number; } diff --git a/src/api/resources/admins/client/requests/ListAllActivityLogsRequest.ts b/src/api/resources/admins/client/requests/ListAllActivityLogsRequest.ts index 1379e86e..b52e406b 100644 --- a/src/api/resources/admins/client/requests/ListAllActivityLogsRequest.ts +++ b/src/api/resources/admins/client/requests/ListAllActivityLogsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface ListAllActivityLogsRequest { - /** - * The start date that you request data for. It must be formatted as a UNIX timestamp. - */ + /** The start date that you request data for. It must be formatted as a UNIX timestamp. */ created_at_after: string; - /** - * The end date that you request data for. It must be formatted as a UNIX timestamp. - */ + /** The end date that you request data for. It must be formatted as a UNIX timestamp. */ created_at_before?: string; } diff --git a/src/api/resources/admins/client/requests/index.ts b/src/api/resources/admins/client/requests/index.ts index bf3a8602..9d853cb4 100644 --- a/src/api/resources/admins/client/requests/index.ts +++ b/src/api/resources/admins/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type ConfigureAwayAdminRequest } from "./ConfigureAwayAdminRequest"; -export { type ListAllActivityLogsRequest } from "./ListAllActivityLogsRequest"; -export { type FindAdminRequest } from "./FindAdminRequest"; +export type { ConfigureAwayAdminRequest } from "./ConfigureAwayAdminRequest.js"; +export type { FindAdminRequest } from "./FindAdminRequest.js"; +export type { ListAllActivityLogsRequest } from "./ListAllActivityLogsRequest.js"; diff --git a/src/api/resources/admins/index.ts b/src/api/resources/admins/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/admins/index.ts +++ b/src/api/resources/admins/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/admins/types/Admin.ts b/src/api/resources/admins/types/Admin.ts index 33266da0..957fee42 100644 --- a/src/api/resources/admins/types/Admin.ts +++ b/src/api/resources/admins/types/Admin.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Admins are teammate accounts that have access to a workspace. */ export interface Admin { /** String representing the object's type. Always has the value `admin`. */ - type?: "admin"; + type?: string; /** The id representing the admin. */ id: string; /** The name of the admin. */ @@ -17,11 +15,13 @@ export interface Admin { /** The email of the admin. */ email: string; /** The job title of the admin. */ - job_title: string; + job_title?: string; /** Identifies if this admin is currently set in away mode. */ away_mode_enabled: boolean; /** Identifies if this admin is set to automatically reassign new conversations to the apps default inbox. */ away_mode_reassign: boolean; + /** The unique identifier of the away status reason */ + away_status_reason_id?: number; /** Identifies if this admin has a paid inbox seat to restrict/allow features that require them. */ has_inbox_seat: boolean; /** This object represents the avatar associated with the admin. */ diff --git a/src/api/resources/admins/types/index.ts b/src/api/resources/admins/types/index.ts index c950b2eb..838f94f4 100644 --- a/src/api/resources/admins/types/index.ts +++ b/src/api/resources/admins/types/index.ts @@ -1 +1 @@ -export * from "./Admin"; +export * from "./Admin.js"; diff --git a/src/api/resources/aiAgent/index.ts b/src/api/resources/aiAgent/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/aiAgent/index.ts +++ b/src/api/resources/aiAgent/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/aiAgent/types/AiAgent.ts b/src/api/resources/aiAgent/types/AiAgent.ts index af7c7974..19ae094e 100644 --- a/src/api/resources/aiAgent/types/AiAgent.ts +++ b/src/api/resources/aiAgent/types/AiAgent.ts @@ -1,33 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Data related to AI Agent involvement in the conversation. */ export interface AiAgent { /** The type of the source that triggered AI Agent involvement in the conversation. */ - source_type: AiAgent.SourceType; + source_type?: AiAgent.SourceType; /** The title of the source that triggered AI Agent involvement in the conversation. If this is `essentials_plan_setup` then it will return `null`. */ source_title?: string; /** The type of the last answer delivered by AI Agent. If no answer was delivered then this will return `null` */ - last_answer_type?: string; + last_answer_type?: AiAgent.LastAnswerType; /** The resolution state of AI Agent. If no AI or custom answer has been delivered then this will return `null`. */ - resolution_state?: string; + resolution_state?: AiAgent.ResolutionState; /** The customer satisfaction rating given to AI Agent, from 1-5. */ rating?: number; /** The customer satisfaction rating remark given to AI Agent. */ rating_remark?: string; + /** The time when the AI agent rating was created. */ + created_at?: number; + /** The time when the AI agent rating was last updated. */ + updated_at?: number; content_sources?: Intercom.ContentSourcesList; } export namespace AiAgent { - /** - * The type of the source that triggered AI Agent involvement in the conversation. - */ - export type SourceType = "essentials_plan_setup" | "profile" | "workflow" | "workflow_preview" | "fin_preview"; + /** The type of the source that triggered AI Agent involvement in the conversation. */ export const SourceType = { EssentialsPlanSetup: "essentials_plan_setup", Profile: "profile", @@ -35,4 +34,19 @@ export namespace AiAgent { WorkflowPreview: "workflow_preview", FinPreview: "fin_preview", } as const; + export type SourceType = (typeof SourceType)[keyof typeof SourceType]; + /** The type of the last answer delivered by AI Agent. If no answer was delivered then this will return `null` */ + export const LastAnswerType = { + AiAnswer: "ai_answer", + CustomAnswer: "custom_answer", + } as const; + export type LastAnswerType = (typeof LastAnswerType)[keyof typeof LastAnswerType]; + /** The resolution state of AI Agent. If no AI or custom answer has been delivered then this will return `null`. */ + export const ResolutionState = { + AssumedResolution: "assumed_resolution", + ConfirmedResolution: "confirmed_resolution", + RoutedToTeam: "routed_to_team", + Abandoned: "abandoned", + } as const; + export type ResolutionState = (typeof ResolutionState)[keyof typeof ResolutionState]; } diff --git a/src/api/resources/aiAgent/types/index.ts b/src/api/resources/aiAgent/types/index.ts index 05de312f..27ef772f 100644 --- a/src/api/resources/aiAgent/types/index.ts +++ b/src/api/resources/aiAgent/types/index.ts @@ -1 +1 @@ -export * from "./AiAgent"; +export * from "./AiAgent.js"; diff --git a/src/api/resources/aiContent/client/Client.ts b/src/api/resources/aiContent/client/Client.ts new file mode 100644 index 00000000..2beabc07 --- /dev/null +++ b/src/api/resources/aiContent/client/Client.ts @@ -0,0 +1,776 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace AiContentClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * With the AI Content APIs, you can create and manage External Pages and Content Import Sources for your Fin Content Library. + * + *   + * + * *External Pages* are pages that you want Fin to be able to answer questions about. The API for External Pages is a great way to ingest into your Fin Content Library pages that are not publicly accessible and hence can't be crawled by Intercom. + * + *   + * + * *Content Import Sources* are the sources of those pages, and they are used to determine the default audience for the pages (configured via the UI). You should create a Content Import Source for each source of External Pages that you want to ingest into your Fin Content Library. + * + *   + * + * You can then iterate through the content from that source via its API and POST it to the External Pages endpoint. That endpoint has an *external_id* parameter which allows you to specify the identifier from the source. The endpoint will then either create a new External Page or update an existing one as appropriate.", + */ +export class AiContentClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AiContentClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can retrieve a list of all content import sources for a workspace. + * + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.listContentImportSources() + */ + public listContentImportSources( + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listContentImportSources(requestOptions)); + } + + private async __listContentImportSources( + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "ai/content_import_sources", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ContentImportSourcesList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/content_import_sources"); + } + + /** + * You can create a new content import source by sending a POST request to this endpoint. + * + * @param {Intercom.CreateContentImportSourceRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.createContentImportSource({ + * url: "https://www.example.com" + * }) + */ + public createContentImportSource( + request: Intercom.CreateContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createContentImportSource(request, requestOptions)); + } + + private async __createContentImportSource( + request: Intercom.CreateContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "ai/content_import_sources", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: { ...request, sync_behavior: "api" }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ContentImportSource, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ai/content_import_sources"); + } + + /** + * @param {Intercom.GetContentImportSourceRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.getContentImportSource({ + * source_id: "source_id" + * }) + */ + public getContentImportSource( + request: Intercom.GetContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getContentImportSource(request, requestOptions)); + } + + private async __getContentImportSource( + request: Intercom.GetContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { source_id: sourceId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/content_import_sources/${core.url.encodePathParam(sourceId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ContentImportSource, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/ai/content_import_sources/{source_id}", + ); + } + + /** + * You can update an existing content import source. + * + * @param {Intercom.UpdateContentImportSourceRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.updateContentImportSource({ + * source_id: "source_id", + * sync_behavior: "api", + * url: "https://www.example.com" + * }) + */ + public updateContentImportSource( + request: Intercom.UpdateContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateContentImportSource(request, requestOptions)); + } + + private async __updateContentImportSource( + request: Intercom.UpdateContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { source_id: sourceId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/content_import_sources/${core.url.encodePathParam(sourceId)}`, + ), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: _body, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ContentImportSource, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/ai/content_import_sources/{source_id}", + ); + } + + /** + * You can delete a content import source by making a DELETE request this endpoint. This will also delete all external pages that were imported from this source. + * + * @param {Intercom.DeleteContentImportSourceRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.deleteContentImportSource({ + * source_id: "source_id" + * }) + */ + public deleteContentImportSource( + request: Intercom.DeleteContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteContentImportSource(request, requestOptions)); + } + + private async __deleteContentImportSource( + request: Intercom.DeleteContentImportSourceRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { source_id: sourceId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/content_import_sources/${core.url.encodePathParam(sourceId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: undefined, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/ai/content_import_sources/{source_id}", + ); + } + + /** + * You can retrieve a list of all external pages for a workspace. + * + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.listExternalPages() + */ + public listExternalPages( + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listExternalPages(requestOptions)); + } + + private async __listExternalPages( + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "ai/external_pages", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ExternalPagesList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/external_pages"); + } + + /** + * You can create a new external page by sending a POST request to this endpoint. If an external page already exists with the specified source_id and external_id, it will be updated instead. + * + * @param {Intercom.CreateExternalPageRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.createExternalPage({ + * title: "Test", + * html: "

Test

", + * url: "https://www.example.com", + * source_id: 44, + * external_id: "abc1234" + * }) + */ + public createExternalPage( + request: Intercom.CreateExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createExternalPage(request, requestOptions)); + } + + private async __createExternalPage( + request: Intercom.CreateExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "ai/external_pages", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: { ...request, locale: "en" }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ExternalPage, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ai/external_pages"); + } + + /** + * You can retrieve an external page. + * + * @param {Intercom.GetExternalPageRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.getExternalPage({ + * page_id: "page_id" + * }) + */ + public getExternalPage( + request: Intercom.GetExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getExternalPage(request, requestOptions)); + } + + private async __getExternalPage( + request: Intercom.GetExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { page_id: pageId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/external_pages/${core.url.encodePathParam(pageId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ExternalPage, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/external_pages/{page_id}"); + } + + /** + * You can update an existing external page (if it was created via the API). + * + * @param {Intercom.UpdateExternalPageRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.updateExternalPage({ + * page_id: "page_id", + * title: "Test", + * html: "

Test

", + * url: "https://www.example.com", + * source_id: 47, + * external_id: "5678" + * }) + */ + public updateExternalPage( + request: Intercom.UpdateExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateExternalPage(request, requestOptions)); + } + + private async __updateExternalPage( + request: Intercom.UpdateExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { page_id: pageId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/external_pages/${core.url.encodePathParam(pageId)}`, + ), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: { ..._body, locale: "en" }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ExternalPage, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/ai/external_pages/{page_id}"); + } + + /** + * Sending a DELETE request for an external page will remove it from the content library UI and from being used for AI answers. + * + * @param {Intercom.DeleteExternalPageRequest} request + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.aiContent.deleteExternalPage({ + * page_id: "page_id" + * }) + */ + public deleteExternalPage( + request: Intercom.DeleteExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteExternalPage(request, requestOptions)); + } + + private async __deleteExternalPage( + request: Intercom.DeleteExternalPageRequest, + requestOptions?: AiContentClient.RequestOptions, + ): Promise> { + const { page_id: pageId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `ai/external_pages/${core.url.encodePathParam(pageId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ExternalPage, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/ai/external_pages/{page_id}", + ); + } +} diff --git a/src/api/resources/aiContent/client/index.ts b/src/api/resources/aiContent/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/aiContent/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts b/src/api/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts new file mode 100644 index 00000000..f487b162 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts @@ -0,0 +1,23 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * url: "https://www.example.com" + * } + */ +export interface CreateContentImportSourceRequest { + /** The status of the content import source. */ + status?: CreateContentImportSourceRequest.Status; + /** The URL of the content import source. */ + url: string; +} + +export namespace CreateContentImportSourceRequest { + /** The status of the content import source. */ + export const Status = { + Active: "active", + Deactivated: "deactivated", + } as const; + export type Status = (typeof Status)[keyof typeof Status]; +} diff --git a/src/api/resources/aiContent/client/requests/CreateExternalPageRequest.ts b/src/api/resources/aiContent/client/requests/CreateExternalPageRequest.ts new file mode 100644 index 00000000..c4f5e914 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/CreateExternalPageRequest.ts @@ -0,0 +1,28 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * title: "Test", + * html: "

Test

", + * url: "https://www.example.com", + * source_id: 44, + * external_id: "abc1234" + * } + */ +export interface CreateExternalPageRequest { + /** The title of the external page. */ + title: string; + /** The body of the external page in HTML. */ + html: string; + /** The URL of the external page. This will be used by Fin to link end users to the page it based its answer on. When a URL is not present, Fin will not reference the source. */ + url?: string; + /** Whether the external page should be used to answer questions by AI Agent. Will not default when updating an existing external page. */ + ai_agent_availability?: boolean; + /** Whether the external page should be used to answer questions by AI Copilot. Will not default when updating an existing external page. */ + ai_copilot_availability?: boolean; + /** The unique identifier for the source of the external page which was given by Intercom. Every external page must be associated with a Content Import Source which represents the place it comes from and from which it inherits a default audience (configured in the UI). For a new source, make a POST request to the Content Import Source endpoint and an ID for the source will be returned in the response. */ + source_id: number; + /** The identifier for the external page which was given by the source. Must be unique for the source. */ + external_id: string; +} diff --git a/src/api/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts b/src/api/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts new file mode 100644 index 00000000..4e3cd384 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * source_id: "source_id" + * } + */ +export interface DeleteContentImportSourceRequest { + /** The unique identifier for the content import source which is given by Intercom. */ + source_id: string; +} diff --git a/src/api/resources/aiContent/client/requests/DeleteExternalPageRequest.ts b/src/api/resources/aiContent/client/requests/DeleteExternalPageRequest.ts new file mode 100644 index 00000000..600b878a --- /dev/null +++ b/src/api/resources/aiContent/client/requests/DeleteExternalPageRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * page_id: "page_id" + * } + */ +export interface DeleteExternalPageRequest { + /** The unique identifier for the external page which is given by Intercom. */ + page_id: string; +} diff --git a/src/api/resources/aiContent/client/requests/GetContentImportSourceRequest.ts b/src/api/resources/aiContent/client/requests/GetContentImportSourceRequest.ts new file mode 100644 index 00000000..9fc6e88a --- /dev/null +++ b/src/api/resources/aiContent/client/requests/GetContentImportSourceRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * source_id: "source_id" + * } + */ +export interface GetContentImportSourceRequest { + /** The unique identifier for the content import source which is given by Intercom. */ + source_id: string; +} diff --git a/src/api/resources/aiContent/client/requests/GetExternalPageRequest.ts b/src/api/resources/aiContent/client/requests/GetExternalPageRequest.ts new file mode 100644 index 00000000..3255d445 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/GetExternalPageRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * page_id: "page_id" + * } + */ +export interface GetExternalPageRequest { + /** The unique identifier for the external page which is given by Intercom. */ + page_id: string; +} diff --git a/src/api/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts b/src/api/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts new file mode 100644 index 00000000..4debce37 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts @@ -0,0 +1,36 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * source_id: "source_id", + * sync_behavior: "api", + * url: "https://www.example.com" + * } + */ +export interface UpdateContentImportSourceRequest { + /** The unique identifier for the content import source which is given by Intercom. */ + source_id: string; + /** If you intend to create or update External Pages via the API, this should be set to `api`. You can not change the value to or from api. */ + sync_behavior: UpdateContentImportSourceRequest.SyncBehavior; + /** The status of the content import source. */ + status?: UpdateContentImportSourceRequest.Status; + /** The URL of the content import source. This may only be different from the existing value if the sync behavior is API. */ + url: string; +} + +export namespace UpdateContentImportSourceRequest { + /** If you intend to create or update External Pages via the API, this should be set to `api`. You can not change the value to or from api. */ + export const SyncBehavior = { + Api: "api", + Automated: "automated", + Manual: "manual", + } as const; + export type SyncBehavior = (typeof SyncBehavior)[keyof typeof SyncBehavior]; + /** The status of the content import source. */ + export const Status = { + Active: "active", + Deactivated: "deactivated", + } as const; + export type Status = (typeof Status)[keyof typeof Status]; +} diff --git a/src/api/resources/aiContent/client/requests/UpdateExternalPageRequest.ts b/src/api/resources/aiContent/client/requests/UpdateExternalPageRequest.ts new file mode 100644 index 00000000..75d703c3 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/UpdateExternalPageRequest.ts @@ -0,0 +1,29 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * page_id: "page_id", + * title: "Test", + * html: "

Test

", + * url: "https://www.example.com", + * source_id: 47, + * external_id: "5678" + * } + */ +export interface UpdateExternalPageRequest { + /** The unique identifier for the external page which is given by Intercom. */ + page_id: string; + /** The title of the external page. */ + title: string; + /** The body of the external page in HTML. */ + html: string; + /** The URL of the external page. This will be used by Fin to link end users to the page it based its answer on. */ + url: string; + /** Whether the external page should be used to answer questions by Fin. */ + fin_availability?: boolean; + /** The unique identifier for the source of the external page which was given by Intercom. Every external page must be associated with a Content Import Source which represents the place it comes from and from which it inherits a default audience (configured in the UI). For a new source, make a POST request to the Content Import Source endpoint and an ID for the source will be returned in the response. */ + source_id: number; + /** The identifier for the external page which was given by the source. Must be unique for the source. */ + external_id?: string; +} diff --git a/src/api/resources/aiContent/client/requests/index.ts b/src/api/resources/aiContent/client/requests/index.ts new file mode 100644 index 00000000..2c010829 --- /dev/null +++ b/src/api/resources/aiContent/client/requests/index.ts @@ -0,0 +1,8 @@ +export type { CreateContentImportSourceRequest } from "./CreateContentImportSourceRequest.js"; +export type { CreateExternalPageRequest } from "./CreateExternalPageRequest.js"; +export type { DeleteContentImportSourceRequest } from "./DeleteContentImportSourceRequest.js"; +export type { DeleteExternalPageRequest } from "./DeleteExternalPageRequest.js"; +export type { GetContentImportSourceRequest } from "./GetContentImportSourceRequest.js"; +export type { GetExternalPageRequest } from "./GetExternalPageRequest.js"; +export type { UpdateContentImportSourceRequest } from "./UpdateContentImportSourceRequest.js"; +export type { UpdateExternalPageRequest } from "./UpdateExternalPageRequest.js"; diff --git a/src/api/resources/aiContent/index.ts b/src/api/resources/aiContent/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/aiContent/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/aiContent/types/ContentImportSource.ts b/src/api/resources/aiContent/types/ContentImportSource.ts new file mode 100644 index 00000000..e65d8d1a --- /dev/null +++ b/src/api/resources/aiContent/types/ContentImportSource.ts @@ -0,0 +1,39 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * An external source for External Pages that you add to your Fin Content Library. + */ +export interface ContentImportSource { + /** Always external_page */ + type: "content_import_source"; + /** The unique identifier for the content import source which is given by Intercom. */ + id: number; + /** The time when the content import source was last synced. */ + last_synced_at: number; + /** If you intend to create or update External Pages via the API, this should be set to `api`. */ + sync_behavior: ContentImportSource.SyncBehavior; + /** The status of the content import source. */ + status: ContentImportSource.Status; + /** The URL of the root of the external source. */ + url: string; + /** The time when the content import source was created. */ + created_at: number; + /** The time when the content import source was last updated. */ + updated_at: number; +} + +export namespace ContentImportSource { + /** If you intend to create or update External Pages via the API, this should be set to `api`. */ + export const SyncBehavior = { + Api: "api", + Automatic: "automatic", + Manual: "manual", + } as const; + export type SyncBehavior = (typeof SyncBehavior)[keyof typeof SyncBehavior]; + /** The status of the content import source. */ + export const Status = { + Active: "active", + Deactivated: "deactivated", + } as const; + export type Status = (typeof Status)[keyof typeof Status]; +} diff --git a/src/api/resources/aiContent/types/ContentImportSourcesList.ts b/src/api/resources/aiContent/types/ContentImportSourcesList.ts new file mode 100644 index 00000000..8e7018fe --- /dev/null +++ b/src/api/resources/aiContent/types/ContentImportSourcesList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * This will return a list of the content import sources for the App. + */ +export interface ContentImportSourcesList { + /** The type of the object - `list`. */ + type?: "list"; + pages?: Intercom.PagesLink; + /** A count of the total number of content import sources. */ + total_count?: number; + /** An array of Content Import Source objects */ + data?: Intercom.ContentImportSource[]; +} diff --git a/src/api/resources/aiContent/types/ExternalPage.ts b/src/api/resources/aiContent/types/ExternalPage.ts new file mode 100644 index 00000000..97afb31c --- /dev/null +++ b/src/api/resources/aiContent/types/ExternalPage.ts @@ -0,0 +1,35 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * External pages that you have added to your Fin Content Library. + */ +export interface ExternalPage { + /** Always external_page */ + type: "external_page"; + /** The unique identifier for the external page which is given by Intercom. */ + id: string; + /** The title of the external page. */ + title: string; + /** The body of the external page in HTML. */ + html: string; + /** The URL of the external page. This will be used by Fin to link end users to the page it based its answer on. */ + url?: string; + /** Whether the external page should be used to answer questions by AI Agent. */ + ai_agent_availability: boolean; + /** Whether the external page should be used to answer questions by AI Copilot. */ + ai_copilot_availability: boolean; + /** Deprecated. Use ai_agent_availability and ai_copilot_availability instead. */ + fin_availability?: boolean; + /** Always en */ + locale: "en"; + /** The unique identifier for the source of the external page which was given by Intercom. Every external page must be associated with a Content Import Source which represents the place it comes from and from which it inherits a default audience (configured in the UI). For a new source, make a POST request to the Content Import Source endpoint and an ID for the source will be returned in the response. */ + source_id: number; + /** The identifier for the external page which was given by the source. Must be unique for the source. */ + external_id: string; + /** The time when the external page was created. */ + created_at: number; + /** The time when the external page was last updated. */ + updated_at: number; + /** The time when the external page was last ingested. */ + last_ingested_at: number; +} diff --git a/src/api/resources/aiContent/types/ExternalPagesList.ts b/src/api/resources/aiContent/types/ExternalPagesList.ts new file mode 100644 index 00000000..ec5273ca --- /dev/null +++ b/src/api/resources/aiContent/types/ExternalPagesList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * This will return a list of external pages for the App. + */ +export interface ExternalPagesList { + /** The type of the object - `list`. */ + type?: "list"; + pages?: Intercom.PagesLink; + /** A count of the total number of external pages. */ + total_count?: number; + /** An array of External Page objects */ + data?: Intercom.ExternalPage[]; +} diff --git a/src/api/resources/aiContent/types/index.ts b/src/api/resources/aiContent/types/index.ts new file mode 100644 index 00000000..4a084844 --- /dev/null +++ b/src/api/resources/aiContent/types/index.ts @@ -0,0 +1,4 @@ +export * from "./ContentImportSource.js"; +export * from "./ContentImportSourcesList.js"; +export * from "./ExternalPage.js"; +export * from "./ExternalPagesList.js"; diff --git a/src/api/resources/aiContentSource/index.ts b/src/api/resources/aiContentSource/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/aiContentSource/index.ts +++ b/src/api/resources/aiContentSource/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/aiContentSource/types/ContentSource.ts b/src/api/resources/aiContentSource/types/ContentSource.ts index 15fd382f..7013e220 100644 --- a/src/api/resources/aiContentSource/types/ContentSource.ts +++ b/src/api/resources/aiContentSource/types/ContentSource.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The content source used by AI Agent in the conversation. */ export interface ContentSource { /** The type of the content source. */ - content_type: "custom_answer"; + content_type?: "custom_answer"; /** The internal URL linking to the content source for teammates. */ - url: string; + url?: string; /** The title of the content source. */ - title: string; + title?: string; /** The ISO 639 language code of the content source. */ - locale: string; + locale?: string; } diff --git a/src/api/resources/aiContentSource/types/index.ts b/src/api/resources/aiContentSource/types/index.ts index 68047f7e..190780ca 100644 --- a/src/api/resources/aiContentSource/types/index.ts +++ b/src/api/resources/aiContentSource/types/index.ts @@ -1 +1 @@ -export * from "./ContentSource"; +export * from "./ContentSource.js"; diff --git a/src/api/resources/articles/client/Client.ts b/src/api/resources/articles/client/Client.ts index 78948f01..e101ba3d 100644 --- a/src/api/resources/articles/client/Client.ts +++ b/src/api/resources/articles/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Articles { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ArticlesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Articles */ -export class Articles { - constructor(protected readonly _options: Articles.Options = {}) {} +export class ArticlesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ArticlesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. @@ -83,7 +33,7 @@ export class Articles { * > Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first. * * @param {Intercom.ListArticlesRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -92,44 +42,40 @@ export class Articles { */ public async list( request: Intercom.ListArticlesRequest = {}, - requestOptions?: Articles.RequestOptions, - ): Promise> { + requestOptions?: ArticlesClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.ListArticlesRequest): Promise> => { const { page, per_page: perPage } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ArticleList, rawResponse: _response.rawResponse }; @@ -149,26 +95,12 @@ export class Articles { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles"); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.data ?? []).length > 0, @@ -184,7 +116,7 @@ export class Articles { * You can create a new article by making a POST request to `https://api.intercom.io/articles`. * * @param {Intercom.CreateArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -194,17 +126,16 @@ export class Articles { * title: "Thanks for everything", * description: "Description of the Article", * body: "Body of the Article", - * author_id: 991267407, + * author_id: 991267497, * state: "published", * parent_id: 145, * parent_type: "collection", * translated_content: { * fr: { - * type: "article_content", * title: "Merci pour tout", * description: "Description de l'article", * body: "Corps de l'article", - * author_id: 991267407, + * author_id: 991267497, * state: "published" * } * } @@ -220,41 +151,41 @@ export class Articles { * }) */ public create( - request: Intercom.CreateArticleRequest, - requestOptions?: Articles.RequestOptions, + request?: Intercom.CreateArticleRequest, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( - request: Intercom.CreateArticleRequest, - requestOptions?: Articles.RequestOptions, + request?: Intercom.CreateArticleRequest, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Article, rawResponse: _response.rawResponse }; @@ -278,73 +209,57 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /articles."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/articles"); } /** * You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`. * * @param {Intercom.FindArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.articles.find({ - * article_id: "123" + * article_id: 1 * }) */ public find( request: Intercom.FindArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { article_id: articleId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `articles/${encodeURIComponent(articleId)}`, + `articles/${core.url.encodePathParam(articleId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Article, rawResponse: _response.rawResponse }; @@ -368,76 +283,62 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles/{article_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles/{article_id}"); } /** * You can update the details of a single article by making a PUT request to `https://api.intercom.io/articles/`. * * @param {Intercom.UpdateArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.articles.update({ - * article_id: "123", + * article_id: 1, * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

" * }) */ public update( request: Intercom.UpdateArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { article_id: articleId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `articles/${encodeURIComponent(articleId)}`, + `articles/${core.url.encodePathParam(articleId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Article, rawResponse: _response.rawResponse }; @@ -461,73 +362,57 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /articles/{article_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/articles/{article_id}"); } /** * You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`. * * @param {Intercom.DeleteArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.articles.delete({ - * article_id: "123" + * article_id: 1 * }) */ public delete( request: Intercom.DeleteArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.DeleteArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { article_id: articleId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `articles/${encodeURIComponent(articleId)}`, + `articles/${core.url.encodePathParam(articleId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DeletedArticleObject, rawResponse: _response.rawResponse }; @@ -551,94 +436,79 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /articles/{article_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/articles/{article_id}"); } /** * You can search for articles by making a GET request to `https://api.intercom.io/articles/search`. * * @param {Intercom.SearchArticlesRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.articles.search({ * phrase: "Getting started", - * state: "published" + * state: "published", + * help_center_id: 1, + * highlight: true * }) */ public search( request: Intercom.SearchArticlesRequest = {}, - requestOptions?: Articles.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: ArticlesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); } private async __search( request: Intercom.SearchArticlesRequest = {}, - requestOptions?: Articles.RequestOptions, - ): Promise> { + requestOptions?: ArticlesClient.RequestOptions, + ): Promise> { const { phrase, state, help_center_id: helpCenterId, highlight } = request; const _queryParams: Record = {}; if (phrase != null) { - _queryParams["phrase"] = phrase; + _queryParams.phrase = phrase; } if (state != null) { - _queryParams["state"] = state; + _queryParams.state = state; } if (helpCenterId != null) { - _queryParams["help_center_id"] = helpCenterId.toString(); + _queryParams.help_center_id = helpCenterId.toString(); } if (highlight != null) { - _queryParams["highlight"] = highlight.toString(); + _queryParams.highlight = highlight.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles/search", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.SearchArticlesResponse, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.ArticleSearchResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -657,32 +527,6 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles/search"); } } diff --git a/src/api/resources/articles/client/index.ts b/src/api/resources/articles/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/articles/client/index.ts +++ b/src/api/resources/articles/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/articles/client/requests/DeleteArticleRequest.ts b/src/api/resources/articles/client/requests/DeleteArticleRequest.ts index cfc44703..43cfd9e2 100644 --- a/src/api/resources/articles/client/requests/DeleteArticleRequest.ts +++ b/src/api/resources/articles/client/requests/DeleteArticleRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * article_id: "123" + * article_id: 1 * } */ export interface DeleteArticleRequest { - /** - * The unique identifier for the article which is given by Intercom. - */ - article_id: string; + /** The unique identifier for the article which is given by Intercom. */ + article_id: number; } diff --git a/src/api/resources/articles/client/requests/FindArticleRequest.ts b/src/api/resources/articles/client/requests/FindArticleRequest.ts index 29e6bc18..b333b0d8 100644 --- a/src/api/resources/articles/client/requests/FindArticleRequest.ts +++ b/src/api/resources/articles/client/requests/FindArticleRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * article_id: "123" + * article_id: 1 * } */ export interface FindArticleRequest { - /** - * The unique identifier for the article which is given by Intercom. - */ - article_id: string; + /** The unique identifier for the article which is given by Intercom. */ + article_id: number; } diff --git a/src/api/resources/articles/client/requests/ListArticlesRequest.ts b/src/api/resources/articles/client/requests/ListArticlesRequest.ts index 03a1e4d4..598bdacf 100644 --- a/src/api/resources/articles/client/requests/ListArticlesRequest.ts +++ b/src/api/resources/articles/client/requests/ListArticlesRequest.ts @@ -1,18 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * {} */ export interface ListArticlesRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/articles/client/requests/SearchArticlesRequest.ts b/src/api/resources/articles/client/requests/SearchArticlesRequest.ts index 7c07777d..3416dd98 100644 --- a/src/api/resources/articles/client/requests/SearchArticlesRequest.ts +++ b/src/api/resources/articles/client/requests/SearchArticlesRequest.ts @@ -1,29 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * phrase: "Getting started", - * state: "published" + * state: "published", + * help_center_id: 1, + * highlight: true * } */ export interface SearchArticlesRequest { - /** - * The phrase within your articles to search for. - */ + /** The phrase within your articles to search for. */ phrase?: string; - /** - * The state of the Articles returned. One of `published`, `draft` or `all`. - */ + /** The state of the Articles returned. One of `published`, `draft` or `all`. */ state?: string; - /** - * The ID of the Help Center to search in. - */ + /** The ID of the Help Center to search in. */ help_center_id?: number; - /** - * Return a highlighted version of the matching content within your articles. Refer to the response schema for more details. - */ + /** Return a highlighted version of the matching content within your articles. Refer to the response schema for more details. */ highlight?: boolean; } diff --git a/src/api/resources/articles/client/requests/UpdateArticleRequest.ts b/src/api/resources/articles/client/requests/UpdateArticleRequest.ts index cb814947..36209811 100644 --- a/src/api/resources/articles/client/requests/UpdateArticleRequest.ts +++ b/src/api/resources/articles/client/requests/UpdateArticleRequest.ts @@ -1,29 +1,25 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example * { - * article_id: "123", + * article_id: 1, * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

" * } * * @example * { - * article_id: "123", + * article_id: 1, * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

" * } */ export interface UpdateArticleRequest { - /** - * The unique identifier for the article which is given by Intercom. - */ - article_id: string; + /** The unique identifier for the article which is given by Intercom. */ + article_id: number; /** The title of the article.For multilingual articles, this will be the title of the default language's content. */ title?: string; /** The description of the article. For multilingual articles, this will be the description of the default language's content. */ @@ -37,25 +33,15 @@ export interface UpdateArticleRequest { /** The id of the article's parent collection or section. An article without this field stands alone. */ parent_id?: string; /** The type of parent, which can either be a `collection` or `section`. */ - parent_type?: UpdateArticleRequest.ParentType; + parent_type?: string; translated_content?: Intercom.ArticleTranslatedContent; } export namespace UpdateArticleRequest { - /** - * Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. - */ - export type State = "published" | "draft"; + /** Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. */ export const State = { Published: "published", Draft: "draft", } as const; - /** - * The type of parent, which can either be a `collection` or `section`. - */ - export type ParentType = "collection" | "section"; - export const ParentType = { - Collection: "collection", - Section: "section", - } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/articles/client/requests/index.ts b/src/api/resources/articles/client/requests/index.ts index 48ca8171..9376442d 100644 --- a/src/api/resources/articles/client/requests/index.ts +++ b/src/api/resources/articles/client/requests/index.ts @@ -1,6 +1,5 @@ -export { type ListArticlesRequest } from "./ListArticlesRequest"; -export { type CreateArticleRequest } from "./CreateArticleRequest"; -export { type FindArticleRequest } from "./FindArticleRequest"; -export { type UpdateArticleRequest } from "./UpdateArticleRequest"; -export { type DeleteArticleRequest } from "./DeleteArticleRequest"; -export { type SearchArticlesRequest } from "./SearchArticlesRequest"; +export type { DeleteArticleRequest } from "./DeleteArticleRequest.js"; +export type { FindArticleRequest } from "./FindArticleRequest.js"; +export type { ListArticlesRequest } from "./ListArticlesRequest.js"; +export type { SearchArticlesRequest } from "./SearchArticlesRequest.js"; +export type { UpdateArticleRequest } from "./UpdateArticleRequest.js"; diff --git a/src/api/resources/articles/index.ts b/src/api/resources/articles/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/articles/index.ts +++ b/src/api/resources/articles/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/articles/types/Article.ts b/src/api/resources/articles/types/Article.ts index 4328ff6c..02667c69 100644 --- a/src/api/resources/articles/types/Article.ts +++ b/src/api/resources/articles/types/Article.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The Articles API is a central place to gather all information and take actions on your articles. Articles can live within collections and sections, or alternatively they can stand alone. diff --git a/src/api/resources/articles/types/ArticleListItem.ts b/src/api/resources/articles/types/ArticleListItem.ts index 1c180206..426c862a 100644 --- a/src/api/resources/articles/types/ArticleListItem.ts +++ b/src/api/resources/articles/types/ArticleListItem.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The data returned about your articles when you list them. @@ -37,17 +35,15 @@ export interface ArticleListItem { /** The type of parent, which can either be a `collection` or `section`. */ parent_type?: string; /** The default locale of the help center. This field is only returned for multilingual help centers. */ - default_locale: string; - translated_content: Intercom.ArticleTranslatedContent; + default_locale?: string; + translated_content?: Intercom.ArticleTranslatedContent; } export namespace ArticleListItem { - /** - * Whether the article is `published` or is a `draft`. For multilingual articles, this will be the state of the default language's content. - */ - export type State = "published" | "draft"; + /** Whether the article is `published` or is a `draft`. For multilingual articles, this will be the state of the default language's content. */ export const State = { Published: "published", Draft: "draft", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/articles/types/ArticleSearchHighlights.ts b/src/api/resources/articles/types/ArticleSearchHighlights.ts index 0dd36d50..c80f22fa 100644 --- a/src/api/resources/articles/types/ArticleSearchHighlights.ts +++ b/src/api/resources/articles/types/ArticleSearchHighlights.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The highlighted results of an Article search. In the examples provided my search query is always "my query". */ export interface ArticleSearchHighlights { /** The ID of the corresponding article. */ - article_id: string; + article_id?: string; /** An Article title highlighted. */ - highlighted_title: ArticleSearchHighlights.HighlightedTitle.Item[]; + highlighted_title?: ArticleSearchHighlights.HighlightedTitle.Item[]; /** An Article description and body text highlighted. */ - highlighted_summary: ArticleSearchHighlights.HighlightedSummary.Item[][]; + highlighted_summary?: ArticleSearchHighlights.HighlightedSummary.Item[][]; } export namespace ArticleSearchHighlights { @@ -29,14 +27,12 @@ export namespace ArticleSearchHighlights { } export namespace Item { - /** - * The type of text - `highlight` or `plain`. - */ - export type Type = "highlight" | "plain"; + /** The type of text - `highlight` or `plain`. */ export const Type = { Highlight: "highlight", Plain: "plain", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } @@ -54,14 +50,12 @@ export namespace ArticleSearchHighlights { } export namespace Item { - /** - * The type of text - `highlight` or `plain`. - */ - export type Type = "highlight" | "plain"; + /** The type of text - `highlight` or `plain`. */ export const Type = { Highlight: "highlight", Plain: "plain", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } } diff --git a/src/api/resources/articles/types/SearchArticlesResponse.ts b/src/api/resources/articles/types/ArticleSearchResponse.ts similarity index 66% rename from src/api/resources/articles/types/SearchArticlesResponse.ts rename to src/api/resources/articles/types/ArticleSearchResponse.ts index dbf3330a..349062a8 100644 --- a/src/api/resources/articles/types/SearchArticlesResponse.ts +++ b/src/api/resources/articles/types/ArticleSearchResponse.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The results of an Article search */ -export interface SearchArticlesResponse { +export interface ArticleSearchResponse { /** The type of the object - `list`. */ - type: "list"; + type?: "list"; /** The total number of Articles matching the search query */ - total_count: number; + total_count?: number; /** An object containing the results of the search. */ - data: SearchArticlesResponse.Data; + data?: ArticleSearchResponse.Data; pages?: Intercom.CursorPages; } -export namespace SearchArticlesResponse { +export namespace ArticleSearchResponse { /** * An object containing the results of the search. */ diff --git a/src/api/resources/articles/types/InternalArticle.ts b/src/api/resources/articles/types/InternalArticle.ts new file mode 100644 index 00000000..dec37b5f --- /dev/null +++ b/src/api/resources/articles/types/InternalArticle.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * The Internal Articles API is a central place to gather all information and take actions on your internal articles. + */ +export type InternalArticle = Intercom.InternalArticleListItem; diff --git a/src/api/resources/articles/types/index.ts b/src/api/resources/articles/types/index.ts index a9b4ea42..ac1a15f9 100644 --- a/src/api/resources/articles/types/index.ts +++ b/src/api/resources/articles/types/index.ts @@ -1,4 +1,5 @@ -export * from "./Article"; -export * from "./ArticleListItem"; -export * from "./ArticleSearchHighlights"; -export * from "./SearchArticlesResponse"; +export * from "./Article.js"; +export * from "./ArticleListItem.js"; +export * from "./ArticleSearchHighlights.js"; +export * from "./ArticleSearchResponse.js"; +export * from "./InternalArticle.js"; diff --git a/src/api/resources/awayStatusReasons/client/Client.ts b/src/api/resources/awayStatusReasons/client/Client.ts new file mode 100644 index 00000000..22df5064 --- /dev/null +++ b/src/api/resources/awayStatusReasons/client/Client.ts @@ -0,0 +1,92 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace AwayStatusReasonsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Away Status Reasons + */ +export class AwayStatusReasonsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AwayStatusReasonsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Returns a list of all away status reasons configured for the workspace, including deleted ones. + * + * @param {AwayStatusReasonsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.awayStatusReasons.listAwayStatusReasons() + */ + public listAwayStatusReasons( + requestOptions?: AwayStatusReasonsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listAwayStatusReasons(requestOptions)); + } + + private async __listAwayStatusReasons( + requestOptions?: AwayStatusReasonsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "away_status_reasons", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.AwayStatusReason[], rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/away_status_reasons"); + } +} diff --git a/src/api/resources/awayStatusReasons/client/index.ts b/src/api/resources/awayStatusReasons/client/index.ts new file mode 100644 index 00000000..cb0ff5c3 --- /dev/null +++ b/src/api/resources/awayStatusReasons/client/index.ts @@ -0,0 +1 @@ +export {}; diff --git a/src/api/resources/awayStatusReasons/index.ts b/src/api/resources/awayStatusReasons/index.ts new file mode 100644 index 00000000..914b8c3c --- /dev/null +++ b/src/api/resources/awayStatusReasons/index.ts @@ -0,0 +1 @@ +export * from "./client/index.js"; diff --git a/src/api/resources/calls/client/Client.ts b/src/api/resources/calls/client/Client.ts new file mode 100644 index 00000000..956fcfa5 --- /dev/null +++ b/src/api/resources/calls/client/Client.ts @@ -0,0 +1,405 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace CallsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Calls + */ +export class CallsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CallsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Retrieve a paginated list of calls. + * + * @param {Intercom.ListCallsRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.calls.listCalls({ + * page: 1, + * per_page: 1 + * }) + */ + public listCalls( + request: Intercom.ListCallsRequest = {}, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listCalls(request, requestOptions)); + } + + private async __listCalls( + request: Intercom.ListCallsRequest = {}, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { page, per_page: perPage } = request; + const _queryParams: Record = {}; + if (page != null) { + _queryParams.page = page.toString(); + } + + if (perPage != null) { + _queryParams.per_page = perPage.toString(); + } + + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "calls", + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.CallList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls"); + } + + /** + * Retrieve a single call by id. + * + * @param {Intercom.ShowCallRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.calls.showCall({ + * call_id: "call_id" + * }) + */ + public showCall( + request: Intercom.ShowCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCall(request, requestOptions)); + } + + private async __showCall( + request: Intercom.ShowCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { call_id: callId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(callId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.Call, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{call_id}"); + } + + /** + * Redirects to a signed URL for the call's recording if it exists. + * + * @param {Intercom.ShowCallRecordingRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.calls.showCallRecording({ + * call_id: "call_id" + * }) + */ + public showCallRecording( + request: Intercom.ShowCallRecordingRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCallRecording(request, requestOptions)); + } + + private async __showCallRecording( + request: Intercom.ShowCallRecordingRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { call_id: callId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(callId)}/recording`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: undefined, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{call_id}/recording"); + } + + /** + * Returns the transcript for the specified call as a downloadable text file. + * + * @param {Intercom.ShowCallTranscriptRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.calls.showCallTranscript({ + * call_id: "call_id" + * }) + */ + public showCallTranscript( + request: Intercom.ShowCallTranscriptRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCallTranscript(request, requestOptions)); + } + + private async __showCallTranscript( + request: Intercom.ShowCallTranscriptRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { call_id: callId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(callId)}/transcript`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + responseType: "text", + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as string, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{call_id}/transcript"); + } + + /** + * Retrieve calls by a list of conversation ids and include transcripts when available. + * A maximum of 20 `conversation_ids` can be provided. If none are provided or more than 20 are provided, a 400 error is returned. + * + * @param {Intercom.ListCallsWithTranscriptsRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.calls.listCallsWithTranscripts({ + * conversation_ids: ["64619700005694", "64619700005695"] + * }) + */ + public listCallsWithTranscripts( + request: Intercom.ListCallsWithTranscriptsRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listCallsWithTranscripts(request, requestOptions)); + } + + private async __listCallsWithTranscripts( + request: Intercom.ListCallsWithTranscriptsRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "calls/search", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.ListCallsWithTranscriptsResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/calls/search"); + } +} diff --git a/src/api/resources/calls/client/index.ts b/src/api/resources/calls/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/calls/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/calls/client/requests/ListCallsRequest.ts b/src/api/resources/calls/client/requests/ListCallsRequest.ts new file mode 100644 index 00000000..74c29012 --- /dev/null +++ b/src/api/resources/calls/client/requests/ListCallsRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * page: 1, + * per_page: 1 + * } + */ +export interface ListCallsRequest { + /** The page of results to fetch. Defaults to first page */ + page?: number; + /** How many results to display per page. Defaults to 25. Max 25. */ + per_page?: number; +} diff --git a/src/api/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts b/src/api/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts new file mode 100644 index 00000000..92d644c1 --- /dev/null +++ b/src/api/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * conversation_ids: ["64619700005694", "64619700005695"] + * } + */ +export interface ListCallsWithTranscriptsRequest { + /** A list of conversation ids to fetch calls for. Maximum 20. */ + conversation_ids: string[]; +} diff --git a/src/api/resources/calls/client/requests/ShowCallRecordingRequest.ts b/src/api/resources/calls/client/requests/ShowCallRecordingRequest.ts new file mode 100644 index 00000000..7b9543df --- /dev/null +++ b/src/api/resources/calls/client/requests/ShowCallRecordingRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * call_id: "call_id" + * } + */ +export interface ShowCallRecordingRequest { + /** The id of the call */ + call_id: string; +} diff --git a/src/api/resources/calls/client/requests/ShowCallRequest.ts b/src/api/resources/calls/client/requests/ShowCallRequest.ts new file mode 100644 index 00000000..52c4cd8c --- /dev/null +++ b/src/api/resources/calls/client/requests/ShowCallRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * call_id: "call_id" + * } + */ +export interface ShowCallRequest { + /** The id of the call to retrieve */ + call_id: string; +} diff --git a/src/api/resources/calls/client/requests/ShowCallTranscriptRequest.ts b/src/api/resources/calls/client/requests/ShowCallTranscriptRequest.ts new file mode 100644 index 00000000..9c2bbe4e --- /dev/null +++ b/src/api/resources/calls/client/requests/ShowCallTranscriptRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * call_id: "call_id" + * } + */ +export interface ShowCallTranscriptRequest { + /** The id of the call */ + call_id: string; +} diff --git a/src/api/resources/calls/client/requests/index.ts b/src/api/resources/calls/client/requests/index.ts new file mode 100644 index 00000000..08b2eb9c --- /dev/null +++ b/src/api/resources/calls/client/requests/index.ts @@ -0,0 +1,5 @@ +export type { ListCallsRequest } from "./ListCallsRequest.js"; +export type { ListCallsWithTranscriptsRequest } from "./ListCallsWithTranscriptsRequest.js"; +export type { ShowCallRecordingRequest } from "./ShowCallRecordingRequest.js"; +export type { ShowCallRequest } from "./ShowCallRequest.js"; +export type { ShowCallTranscriptRequest } from "./ShowCallTranscriptRequest.js"; diff --git a/src/api/resources/calls/index.ts b/src/api/resources/calls/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/calls/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/calls/types/Call.ts b/src/api/resources/calls/types/Call.ts new file mode 100644 index 00000000..33b20803 --- /dev/null +++ b/src/api/resources/calls/types/Call.ts @@ -0,0 +1,42 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * Represents a phone call in Intercom + */ +export interface Call { + /** String representing the object's type. Always has the value `call`. */ + type?: string; + /** The id of the call. */ + id?: string; + /** The id of the conversation associated with the call, if any. */ + conversation_id?: string; + /** The id of the admin associated with the call, if any. */ + admin_id?: string; + /** The id of the contact associated with the call, if any. */ + contact_id?: string; + /** The current state of the call. */ + state?: string; + initiated_at?: Intercom.Datetime; + answered_at?: Intercom.Datetime; + ended_at?: Intercom.Datetime; + created_at?: Intercom.Datetime; + updated_at?: Intercom.Datetime; + /** API URL to download or redirect to the call recording if available. */ + recording_url?: string; + /** API URL to download or redirect to the call transcript if available. */ + transcription_url?: string; + /** The type of call. */ + call_type?: string; + /** The direction of the call. */ + direction?: string; + /** The reason for the call end, if applicable. */ + ended_reason?: string; + /** The phone number involved in the call, in E.164 format. */ + phone?: string; + /** API URL to the AI Agent (Fin) call recording if available. */ + fin_recording_url?: string; + /** API URL to the AI Agent (Fin) call transcript if available. */ + fin_transcription_url?: string; +} diff --git a/src/api/resources/calls/types/ListCallsWithTranscriptsResponse.ts b/src/api/resources/calls/types/ListCallsWithTranscriptsResponse.ts new file mode 100644 index 00000000..f37c83bc --- /dev/null +++ b/src/api/resources/calls/types/ListCallsWithTranscriptsResponse.ts @@ -0,0 +1,21 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ListCallsWithTranscriptsResponse { + type?: string; + data?: ListCallsWithTranscriptsResponse.Data.Item[]; +} + +export namespace ListCallsWithTranscriptsResponse { + export type Data = Data.Item[]; + + export namespace Data { + export interface Item extends Intercom.Call { + /** The call transcript if available, otherwise an empty array. */ + transcript?: Record[]; + /** The status of the transcript if available. */ + transcript_status?: string; + } + } +} diff --git a/src/api/resources/calls/types/index.ts b/src/api/resources/calls/types/index.ts new file mode 100644 index 00000000..a7b7c7f7 --- /dev/null +++ b/src/api/resources/calls/types/index.ts @@ -0,0 +1,2 @@ +export * from "./Call.js"; +export * from "./ListCallsWithTranscriptsResponse.js"; diff --git a/src/api/resources/companies/client/Client.ts b/src/api/resources/companies/client/Client.ts index 5ac7d49b..db9cb03e 100644 --- a/src/api/resources/companies/client/Client.ts +++ b/src/api/resources/companies/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Companies { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace CompaniesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Companies */ -export class Companies { - constructor(protected readonly _options: Companies.Options = {}) {} +export class CompaniesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CompaniesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a single company by passing in `company_id` or `name`. @@ -89,7 +39,7 @@ export class Companies { * `https://api.intercom.io/companies?segment_id={segment_id}` * * @param {Intercom.RetrieveCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -99,71 +49,70 @@ export class Companies { * name: "my company", * company_id: "12345", * tag_id: "678910", - * segment_id: "98765" + * segment_id: "98765", + * page: 1, + * per_page: 1 * }) */ public retrieve( request: Intercom.RetrieveCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieve(request, requestOptions)); } private async __retrieve( request: Intercom.RetrieveCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { name, company_id: companyId, tag_id: tagId, segment_id: segmentId, page, per_page: perPage } = request; const _queryParams: Record = {}; if (name != null) { - _queryParams["name"] = name; + _queryParams.name = name; } if (companyId != null) { - _queryParams["company_id"] = companyId; + _queryParams.company_id = companyId; } if (tagId != null) { - _queryParams["tag_id"] = tagId; + _queryParams.tag_id = tagId; } if (segmentId != null) { - _queryParams["segment_id"] = segmentId; + _queryParams.segment_id = segmentId; } if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.CompaniesRetrieveResponse, rawResponse: _response.rawResponse }; @@ -187,21 +136,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies"); } /** @@ -216,7 +151,7 @@ export class Companies { * {% /admonition %} * * @param {Intercom.CreateOrUpdateCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -232,41 +167,41 @@ export class Companies { * await client.companies.createOrUpdate() */ public createOrUpdate( - request: Intercom.CreateOrUpdateCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + request?: Intercom.CreateOrUpdateCompanyRequest, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createOrUpdate(request, requestOptions)); } private async __createOrUpdate( - request: Intercom.CreateOrUpdateCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + request?: Intercom.CreateOrUpdateCompanyRequest, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Company, rawResponse: _response.rawResponse }; @@ -290,28 +225,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/companies"); } /** * You can fetch a single company. * * @param {Intercom.FindCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -323,40 +244,38 @@ export class Companies { */ public find( request: Intercom.FindCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { company_id: companyId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(companyId)}`, + `companies/${core.url.encodePathParam(companyId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Company, rawResponse: _response.rawResponse }; @@ -380,21 +299,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/{company_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/{company_id}"); } /** @@ -405,52 +310,63 @@ export class Companies { * {% /admonition %} * * @param {Intercom.UpdateCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.companies.update({ - * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" + * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + * body: { + * name: "my company", + * website: "http://www.mycompany.com/" + * } + * }) + * + * @example + * await client.companies.update({ + * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + * body: {} * }) */ public update( request: Intercom.UpdateCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { - const { company_id: companyId } = request; + const { company_id: companyId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(companyId)}`, + `companies/${core.url.encodePathParam(companyId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: _body != null ? _body : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Company, rawResponse: _response.rawResponse }; @@ -474,28 +390,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /companies/{company_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/companies/{company_id}"); } /** * You can delete a single company. * * @param {Intercom.DeleteCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -507,40 +409,38 @@ export class Companies { */ public delete( request: Intercom.DeleteCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.DeleteCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { company_id: companyId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(companyId)}`, + `companies/${core.url.encodePathParam(companyId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DeletedCompanyObject, rawResponse: _response.rawResponse }; @@ -564,28 +464,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /companies/{company_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/companies/{company_id}"); } /** * You can fetch a list of all contacts that belong to a company. * * @param {Intercom.ListAttachedContactsRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -597,50 +483,38 @@ export class Companies { */ public listAttachedContacts( request: Intercom.ListAttachedContactsRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedContacts(request, requestOptions)); } private async __listAttachedContacts( request: Intercom.ListAttachedContactsRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { - const { company_id: companyId, page, per_page: perPage } = request; - const _queryParams: Record = {}; - if (page != null) { - _queryParams["page"] = page.toString(); - } - - if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); - } - + const { company_id: companyId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(companyId)}/contacts`, + `companies/${core.url.encodePathParam(companyId)}/contacts`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.CompanyAttachedContacts, rawResponse: _response.rawResponse }; @@ -664,30 +538,19 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /companies/{company_id}/contacts.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/companies/{company_id}/contacts", + ); } /** * You can fetch a list of all segments that belong to a company. * * @param {Intercom.ListSegmentsAttachedToCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -699,40 +562,38 @@ export class Companies { */ public listAttachedSegments( request: Intercom.ListSegmentsAttachedToCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedSegments(request, requestOptions)); } private async __listAttachedSegments( request: Intercom.ListSegmentsAttachedToCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { company_id: companyId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(companyId)}/segments`, + `companies/${core.url.encodePathParam(companyId)}/segments`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.CompanyAttachedSegments, rawResponse: _response.rawResponse }; @@ -756,23 +617,12 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /companies/{company_id}/segments.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/companies/{company_id}/segments", + ); } /** @@ -787,58 +637,56 @@ export class Companies { * {% /admonition %} * * @param {Intercom.ListCompaniesRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.companies.list({ + * page: 1, + * per_page: 1, * order: "desc" * }) */ public async list( request: Intercom.ListCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, - ): Promise> { + requestOptions?: CompaniesClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.ListCompaniesRequest): Promise> => { const { page, per_page: perPage, order } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (order != null) { - _queryParams["order"] = order; + _queryParams.order = order; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies/list", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.CompanyList, rawResponse: _response.rawResponse }; @@ -858,26 +706,12 @@ export class Companies { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /companies/list."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/companies/list"); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.data ?? []).length > 0, @@ -907,53 +741,56 @@ export class Companies { * {% /admonition %} * * @param {Intercom.ScrollCompaniesRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example - * await client.companies.scroll() + * await client.companies.scroll({ + * scroll_param: "scroll_param" + * }) */ public async scroll( request: Intercom.ScrollCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, - ): Promise> { + requestOptions?: CompaniesClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( - async (request: Intercom.ScrollCompaniesRequest): Promise> => { + async ( + request: Intercom.ScrollCompaniesRequest, + ): Promise> => { const { scroll_param: scrollParam } = request; const _queryParams: Record = {}; if (scrollParam != null) { - _queryParams["scroll_param"] = scrollParam; + _queryParams.scroll_param = scrollParam; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies/scroll", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.CompanyScroll, rawResponse: _response.rawResponse }; + return { + data: _response.body as Intercom.CompanyScroll | undefined, + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { switch (_response.error.statusCode) { @@ -970,28 +807,16 @@ export class Companies { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/scroll."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/scroll"); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.scroll_param != null, + hasNextPage: (response) => + response?.scroll_param != null && + !(typeof response?.scroll_param === "string" && response?.scroll_param === ""), getItems: (response) => response?.data ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "scroll_param", response?.scroll_param)); @@ -1003,7 +828,7 @@ export class Companies { * You can attach a company to a single contact. * * @param {Intercom.AttachContactToCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -1012,7 +837,7 @@ export class Companies { * @example * await client.companies.attachContact({ * contact_id: "contact_id", - * id: "667d608d8a68186f43bafd70" + * id: "6762f09a1bb69f9f2193bb34" * }) * * @example @@ -1029,41 +854,41 @@ export class Companies { */ public attachContact( request: Intercom.AttachContactToCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachContact(request, requestOptions)); } private async __attachContact( request: Intercom.AttachContactToCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/companies`, + `contacts/${core.url.encodePathParam(contactId)}/companies`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Company, rawResponse: _response.rawResponse }; @@ -1089,30 +914,19 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/companies.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/contacts/{contact_id}/companies", + ); } /** * You can detach a company from a single contact. * * @param {Intercom.DetachContactFromCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -1125,40 +939,38 @@ export class Companies { */ public detachContact( request: Intercom.DetachContactFromCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachContact(request, requestOptions)); } private async __detachContact( request: Intercom.DetachContactFromCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { contact_id: contactId, company_id: companyId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/companies/${encodeURIComponent(companyId)}`, + `contacts/${core.url.encodePathParam(contactId)}/companies/${core.url.encodePathParam(companyId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Company, rawResponse: _response.rawResponse }; @@ -1182,34 +994,11 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/companies/{company_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/companies/{company_id}", + ); } } diff --git a/src/api/resources/companies/client/index.ts b/src/api/resources/companies/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/companies/client/index.ts +++ b/src/api/resources/companies/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/companies/client/requests/AttachContactToCompanyRequest.ts b/src/api/resources/companies/client/requests/AttachContactToCompanyRequest.ts index 17a7d4b3..95995f1a 100644 --- a/src/api/resources/companies/client/requests/AttachContactToCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/AttachContactToCompanyRequest.ts @@ -1,12 +1,10 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * contact_id: "contact_id", - * id: "667d608d8a68186f43bafd70" + * id: "6762f09a1bb69f9f2193bb34" * } * * @example @@ -22,9 +20,7 @@ * } */ export interface AttachContactToCompanyRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; /** The unique identifier for the company which is given by Intercom */ id: string; diff --git a/src/api/resources/companies/client/requests/DeleteCompanyRequest.ts b/src/api/resources/companies/client/requests/DeleteCompanyRequest.ts index 907c4032..89d10288 100644 --- a/src/api/resources/companies/client/requests/DeleteCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/DeleteCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; } diff --git a/src/api/resources/companies/client/requests/DetachContactFromCompanyRequest.ts b/src/api/resources/companies/client/requests/DetachContactFromCompanyRequest.ts index 9264bac5..6b35eccd 100644 --- a/src/api/resources/companies/client/requests/DetachContactFromCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/DetachContactFromCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DetachContactFromCompanyRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; } diff --git a/src/api/resources/companies/client/requests/FindCompanyRequest.ts b/src/api/resources/companies/client/requests/FindCompanyRequest.ts index ca707798..6be81172 100644 --- a/src/api/resources/companies/client/requests/FindCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/FindCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; } diff --git a/src/api/resources/companies/client/requests/ListAttachedContactsRequest.ts b/src/api/resources/companies/client/requests/ListAttachedContactsRequest.ts index af7ff8a7..544f392f 100644 --- a/src/api/resources/companies/client/requests/ListAttachedContactsRequest.ts +++ b/src/api/resources/companies/client/requests/ListAttachedContactsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,16 +7,6 @@ * } */ export interface ListAttachedContactsRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; - /** - * The page of results to fetch. Defaults to first page - */ - page?: number; - /** - * How many results to return per page. Defaults to 15 - */ - per_page?: number; } diff --git a/src/api/resources/companies/client/requests/ListCompaniesRequest.ts b/src/api/resources/companies/client/requests/ListCompaniesRequest.ts index 3d097dd4..ff355c19 100644 --- a/src/api/resources/companies/client/requests/ListCompaniesRequest.ts +++ b/src/api/resources/companies/client/requests/ListCompaniesRequest.ts @@ -1,24 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { + * page: 1, + * per_page: 1, * order: "desc" * } */ export interface ListCompaniesRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to return per page. Defaults to 15 - */ + /** How many results to return per page. Defaults to 15 */ per_page?: number; - /** - * `asc` or `desc`. Return the companies in ascending or descending order. Defaults to desc - */ + /** `asc` or `desc`. Return the companies in ascending or descending order. Defaults to desc */ order?: string; } diff --git a/src/api/resources/companies/client/requests/ListSegmentsAttachedToCompanyRequest.ts b/src/api/resources/companies/client/requests/ListSegmentsAttachedToCompanyRequest.ts index 6c640aea..36c2e57f 100644 --- a/src/api/resources/companies/client/requests/ListSegmentsAttachedToCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/ListSegmentsAttachedToCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListSegmentsAttachedToCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; } diff --git a/src/api/resources/companies/client/requests/RetrieveCompanyRequest.ts b/src/api/resources/companies/client/requests/RetrieveCompanyRequest.ts index 557a2e00..a3314297 100644 --- a/src/api/resources/companies/client/requests/RetrieveCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/RetrieveCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -8,32 +6,22 @@ * name: "my company", * company_id: "12345", * tag_id: "678910", - * segment_id: "98765" + * segment_id: "98765", + * page: 1, + * per_page: 1 * } */ export interface RetrieveCompanyRequest { - /** - * The `name` of the company to filter by. - */ + /** The `name` of the company to filter by. */ name?: string; - /** - * The `company_id` of the company to filter by. - */ + /** The `company_id` of the company to filter by. */ company_id?: string; - /** - * The `tag_id` of the company to filter by. - */ + /** The `tag_id` of the company to filter by. */ tag_id?: string; - /** - * The `segment_id` of the company to filter by. - */ + /** The `segment_id` of the company to filter by. */ segment_id?: string; - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/companies/client/requests/ScrollCompaniesRequest.ts b/src/api/resources/companies/client/requests/ScrollCompaniesRequest.ts index f5233617..56661c7f 100644 --- a/src/api/resources/companies/client/requests/ScrollCompaniesRequest.ts +++ b/src/api/resources/companies/client/requests/ScrollCompaniesRequest.ts @@ -1,14 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * scroll_param: "scroll_param" + * } */ export interface ScrollCompaniesRequest { - /** - * - */ + /** */ scroll_param?: string; } diff --git a/src/api/resources/companies/client/requests/UpdateCompanyRequest.ts b/src/api/resources/companies/client/requests/UpdateCompanyRequest.ts index bcd76db2..6bb331ec 100644 --- a/src/api/resources/companies/client/requests/UpdateCompanyRequest.ts +++ b/src/api/resources/companies/client/requests/UpdateCompanyRequest.ts @@ -1,16 +1,25 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; /** * @example * { - * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" + * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + * body: { + * name: "my company", + * website: "http://www.mycompany.com/" + * } + * } + * + * @example + * { + * company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + * body: {} * } */ export interface UpdateCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ company_id: string; + body?: Intercom.UpdateCompanyRequestBody; } diff --git a/src/api/resources/companies/client/requests/index.ts b/src/api/resources/companies/client/requests/index.ts index 6e45efe4..3c6204dc 100644 --- a/src/api/resources/companies/client/requests/index.ts +++ b/src/api/resources/companies/client/requests/index.ts @@ -1,11 +1,10 @@ -export { type RetrieveCompanyRequest } from "./RetrieveCompanyRequest"; -export { type CreateOrUpdateCompanyRequest } from "./CreateOrUpdateCompanyRequest"; -export { type FindCompanyRequest } from "./FindCompanyRequest"; -export { type UpdateCompanyRequest } from "./UpdateCompanyRequest"; -export { type DeleteCompanyRequest } from "./DeleteCompanyRequest"; -export { type ListAttachedContactsRequest } from "./ListAttachedContactsRequest"; -export { type ListSegmentsAttachedToCompanyRequest } from "./ListSegmentsAttachedToCompanyRequest"; -export { type ListCompaniesRequest } from "./ListCompaniesRequest"; -export { type ScrollCompaniesRequest } from "./ScrollCompaniesRequest"; -export { type AttachContactToCompanyRequest } from "./AttachContactToCompanyRequest"; -export { type DetachContactFromCompanyRequest } from "./DetachContactFromCompanyRequest"; +export type { AttachContactToCompanyRequest } from "./AttachContactToCompanyRequest.js"; +export type { DeleteCompanyRequest } from "./DeleteCompanyRequest.js"; +export type { DetachContactFromCompanyRequest } from "./DetachContactFromCompanyRequest.js"; +export type { FindCompanyRequest } from "./FindCompanyRequest.js"; +export type { ListAttachedContactsRequest } from "./ListAttachedContactsRequest.js"; +export type { ListCompaniesRequest } from "./ListCompaniesRequest.js"; +export type { ListSegmentsAttachedToCompanyRequest } from "./ListSegmentsAttachedToCompanyRequest.js"; +export type { RetrieveCompanyRequest } from "./RetrieveCompanyRequest.js"; +export type { ScrollCompaniesRequest } from "./ScrollCompaniesRequest.js"; +export type { UpdateCompanyRequest } from "./UpdateCompanyRequest.js"; diff --git a/src/api/resources/companies/index.ts b/src/api/resources/companies/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/companies/index.ts +++ b/src/api/resources/companies/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/companies/types/CompaniesRetrieveResponse.ts b/src/api/resources/companies/types/CompaniesRetrieveResponse.ts index fbe90f3f..97513a72 100644 --- a/src/api/resources/companies/types/CompaniesRetrieveResponse.ts +++ b/src/api/resources/companies/types/CompaniesRetrieveResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type CompaniesRetrieveResponse = | Intercom.CompaniesRetrieveResponse.Company diff --git a/src/api/resources/companies/types/Company.ts b/src/api/resources/companies/types/Company.ts index 2de7fd36..cb26b686 100644 --- a/src/api/resources/companies/types/Company.ts +++ b/src/api/resources/companies/types/Company.ts @@ -1,13 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Companies allow you to represent organizations using your product. Each company will have its own description and be associated with contacts. You can fetch, create, update and list companies. */ export interface Company { + /** Value is `company` */ + type?: "company"; /** The Intercom defined id representing the company. */ id: string; /** The name of the company. */ @@ -18,19 +18,19 @@ export interface Company { /** The company id you have defined for the company. */ company_id: string; /** The time the company was created by you. */ - remote_created_at: number; + remote_created_at?: number; /** The time the company was added in Intercom. */ created_at: number; /** The last time the company was updated. */ updated_at: number; /** The time the company last recorded making a request. */ - last_request_at: number; + last_request_at?: number; /** The number of employees in the company. */ - size: number; + size?: number; /** The URL for the company website. */ - website: string; + website?: string; /** The industry that the company operates in. */ - industry: string; + industry?: string; /** How much revenue the company generates for your business. */ monthly_spend: number; /** How many sessions the company has recorded. */ @@ -48,7 +48,7 @@ export interface Company { export namespace Company { export interface Plan { /** Value is always "plan" */ - type?: "plan"; + type?: string; /** The id of the plan */ id?: string; /** The name of the plan */ diff --git a/src/api/resources/companies/types/index.ts b/src/api/resources/companies/types/index.ts index 66af316a..7e2092d3 100644 --- a/src/api/resources/companies/types/index.ts +++ b/src/api/resources/companies/types/index.ts @@ -1,2 +1,2 @@ -export * from "./CompaniesRetrieveResponse"; -export * from "./Company"; +export * from "./CompaniesRetrieveResponse.js"; +export * from "./Company.js"; diff --git a/src/api/resources/contacts/client/Client.ts b/src/api/resources/contacts/client/Client.ts index 894de6c9..f5ec64f4 100644 --- a/src/api/resources/contacts/client/Client.ts +++ b/src/api/resources/contacts/client/Client.ts @@ -1,98 +1,50 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; - -export declare namespace Contacts { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } +export declare namespace ContactsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your contacts */ -export class Contacts { - constructor(protected readonly _options: Contacts.Options = {}) {} +export class ContactsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ContactsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of companies that are associated to a contact. * * @param {Intercom.ListAttachedCompaniesRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.contacts.listAttachedCompanies({ - * contact_id: "63a07ddf05a32042dffac965" + * contact_id: "63a07ddf05a32042dffac965", + * page: 1, + * per_page: 1 * }) */ public async listAttachedCompanies( request: Intercom.ListAttachedCompaniesRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async ( request: Intercom.ListAttachedCompaniesRequest, @@ -100,37 +52,33 @@ export class Contacts { const { contact_id: contactId, page, per_page: perPage } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/companies`, + `contacts/${core.url.encodePathParam(contactId)}/companies`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -155,28 +103,17 @@ export class Contacts { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/companies.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/companies", + ); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.companies ?? []).length > 0, @@ -192,7 +129,7 @@ export class Contacts { * You can fetch a list of segments that are associated to a contact. * * @param {Intercom.ListSegmentsAttachedToContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -204,40 +141,38 @@ export class Contacts { */ public listAttachedSegments( request: Intercom.ListSegmentsAttachedToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedSegments(request, requestOptions)); } private async __listAttachedSegments( request: Intercom.ListSegmentsAttachedToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/segments`, + `contacts/${core.url.encodePathParam(contactId)}/segments`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactSegments, rawResponse: _response.rawResponse }; @@ -261,23 +196,12 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/segments.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/segments", + ); } /** @@ -290,7 +214,7 @@ export class Contacts { * 2.Opt-in subscription types that the user has opted-in to receiving. * * @param {Intercom.ListAttachedSubscriptionsRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -302,40 +226,38 @@ export class Contacts { */ public listAttachedSubscriptions( request: Intercom.ListAttachedSubscriptionsRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedSubscriptions(request, requestOptions)); } private async __listAttachedSubscriptions( request: Intercom.ListAttachedSubscriptionsRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.SubscriptionTypeList, rawResponse: _response.rawResponse }; @@ -359,23 +281,12 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/subscriptions.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/subscriptions", + ); } /** @@ -388,7 +299,7 @@ export class Contacts { * This will return a subscription type model for the subscription type that was added to the contact. * * @param {Intercom.AttachSubscriptionToContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -409,41 +320,41 @@ export class Contacts { */ public attachSubscription( request: Intercom.AttachSubscriptionToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachSubscription(request, requestOptions)); } private async __attachSubscription( request: Intercom.AttachSubscriptionToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.SubscriptionType, rawResponse: _response.rawResponse }; @@ -467,30 +378,19 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/subscriptions.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/contacts/{contact_id}/subscriptions", + ); } /** * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. * * @param {Intercom.DetachSubscriptionFromContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -503,40 +403,38 @@ export class Contacts { */ public detachSubscription( request: Intercom.DetachSubscriptionFromContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachSubscription(request, requestOptions)); } private async __detachSubscription( request: Intercom.DetachSubscriptionFromContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId, subscription_id: subscriptionId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions/${encodeURIComponent(subscriptionId)}`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions/${core.url.encodePathParam(subscriptionId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.SubscriptionType, rawResponse: _response.rawResponse }; @@ -560,30 +458,19 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/subscriptions/{subscription_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/subscriptions/{subscription_id}", + ); } /** * You can fetch a list of all tags that are attached to a specific contact. * * @param {Intercom.ListTagsAttachedToContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -595,40 +482,38 @@ export class Contacts { */ public listAttachedTags( request: Intercom.ListTagsAttachedToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedTags(request, requestOptions)); } private async __listAttachedTags( request: Intercom.ListTagsAttachedToContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags`, + `contacts/${core.url.encodePathParam(contactId)}/tags`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TagList, rawResponse: _response.rawResponse }; @@ -652,28 +537,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{contact_id}/tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{contact_id}/tags"); } /** * You can fetch the details of a single contact. * * @param {Intercom.FindContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -684,43 +555,41 @@ export class Contacts { */ public find( request: Intercom.FindContactRequest, - requestOptions?: Contacts.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindContactRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}`, + `contacts/${core.url.encodePathParam(contactId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Contact, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.ContactsFindResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -739,28 +608,20 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{contact_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{contact_id}"); } /** * You can update an existing contact (ie. user or lead). * + * {% admonition type="info" %} + * This endpoint handles both **contact updates** and **custom object associations**. + * + * See _`update a contact with an association to a custom object instance`_ in the request/response examples to see the custom object association format. + * {% /admonition %} + * * @param {Intercom.UpdateContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -770,47 +631,57 @@ export class Contacts { * email: "joebloggs@intercom.io", * name: "joe bloggs" * }) + * + * @example + * await client.contacts.update({ + * contact_id: "63a07ddf05a32042dffac965", + * custom_attributes: { + * "order": [ + * "21" + * ] + * } + * }) */ public update( request: Intercom.UpdateContactRequest, - requestOptions?: Contacts.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateContactRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}`, + `contacts/${core.url.encodePathParam(contactId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Contact, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.ContactsUpdateResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -829,28 +700,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /contacts/{contact_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/contacts/{contact_id}"); } /** * You can delete a single contact. * * @param {Intercom.DeleteContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -861,40 +718,38 @@ export class Contacts { */ public delete( request: Intercom.DeleteContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.DeleteContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}`, + `contacts/${core.url.encodePathParam(contactId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactDeleted, rawResponse: _response.rawResponse }; @@ -916,76 +771,65 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /contacts/{contact_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/contacts/{contact_id}"); } /** * You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`. * * @param {Intercom.MergeContactsRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.contacts.mergeLeadInUser({ - * from: "667d60ac8a68186f43bafdbb", - * into: "667d60ac8a68186f43bafdbc" + * from: "6762f0d51bb69f9f2193bb7f", + * into: "6762f0d51bb69f9f2193bb80" * }) */ public mergeLeadInUser( - request: Intercom.MergeContactsRequest, - requestOptions?: Contacts.RequestOptions, - ): core.HttpResponsePromise { + request: Intercom.MergeContactsRequest = {}, + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__mergeLeadInUser(request, requestOptions)); } private async __mergeLeadInUser( - request: Intercom.MergeContactsRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + request: Intercom.MergeContactsRequest = {}, + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts/merge", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Contact, rawResponse: _response.rawResponse }; + return { + data: _response.body as Intercom.ContactsMergeLeadInUserResponse, + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { @@ -1004,21 +848,7 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/merge."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/merge"); } /** @@ -1123,7 +953,7 @@ export class Contacts { * | $ | String | Ends With | * * @param {Intercom.SearchRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -1144,36 +974,35 @@ export class Contacts { */ public async search( request: Intercom.SearchRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.SearchRequest): Promise> => { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactList, rawResponse: _response.rawResponse }; @@ -1193,28 +1022,19 @@ export class Contacts { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/search"); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.pages?.next?.starting_after != null, + hasNextPage: (response) => + response?.pages?.next?.starting_after != null && + !( + typeof response?.pages?.next?.starting_after === "string" && + response?.pages?.next?.starting_after === "" + ), getItems: (response) => response?.data ?? [], loadPage: (response) => { return list( @@ -1232,7 +1052,7 @@ export class Contacts { * {% /admonition %} * * @param {Intercom.ListContactsRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -1241,47 +1061,43 @@ export class Contacts { */ public async list( request: Intercom.ListContactsRequest = {}, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.ListContactsRequest): Promise> => { const { page, per_page: perPage, starting_after: startingAfter } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (startingAfter != null) { - _queryParams["starting_after"] = startingAfter; + _queryParams.starting_after = startingAfter; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactList, rawResponse: _response.rawResponse }; @@ -1301,28 +1117,19 @@ export class Contacts { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts"); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.pages?.next?.starting_after != null, + hasNextPage: (response) => + response?.pages?.next?.starting_after != null && + !( + typeof response?.pages?.next?.starting_after === "string" && + response?.pages?.next?.starting_after === "" + ), getItems: (response) => response?.data ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "starting_after", response?.pages?.next?.starting_after)); @@ -1334,7 +1141,7 @@ export class Contacts { * You can create a new contact (ie. user or lead). * * @param {Intercom.CreateContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -1345,43 +1152,43 @@ export class Contacts { */ public create( request: Intercom.CreateContactRequest, - requestOptions?: Contacts.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateContactRequest, - requestOptions?: Contacts.RequestOptions, - ): Promise> { + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Contact, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.ContactsCreateResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -1400,28 +1207,93 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts"); + } + + /** + * You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads. + * + * @param {Intercom.ShowContactByExternalIdRequest} request + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.contacts.showContactByExternalId({ + * external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27" + * }) + */ + public showContactByExternalId( + request: Intercom.ShowContactByExternalIdRequest, + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showContactByExternalId(request, requestOptions)); + } + + private async __showContactByExternalId( + request: Intercom.ShowContactByExternalIdRequest, + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { + const { external_id: externalId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `contacts/find_by_external_id/${core.url.encodePathParam(externalId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.ShowContactByExternalIdResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/find_by_external_id/{external_id}", + ); } /** * You can archive a single contact. * * @param {Intercom.ArchiveContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.contacts.archive({ @@ -1430,40 +1302,38 @@ export class Contacts { */ public archive( request: Intercom.ArchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__archive(request, requestOptions)); } private async __archive( request: Intercom.ArchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/archive`, + `contacts/${core.url.encodePathParam(contactId)}/archive`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactArchived, rawResponse: _response.rawResponse }; @@ -1477,30 +1347,19 @@ export class Contacts { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/archive.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/contacts/{contact_id}/archive", + ); } /** * You can unarchive a single contact. * * @param {Intercom.UnarchiveContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.contacts.unarchive({ @@ -1509,40 +1368,38 @@ export class Contacts { */ public unarchive( request: Intercom.UnarchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__unarchive(request, requestOptions)); } private async __unarchive( request: Intercom.UnarchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/unarchive`, + `contacts/${core.url.encodePathParam(contactId)}/unarchive`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.ContactUnarchived, rawResponse: _response.rawResponse }; @@ -1556,34 +1413,72 @@ export class Contacts { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/unarchive.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/contacts/{contact_id}/unarchive", + ); + } + + /** + * Block a single contact.
**Note:** conversations of the contact will also be archived during the process.
More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs) + * + * @param {Intercom.BlockContactRequest} request + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @example + * await client.contacts.blockContact({ + * contact_id: "63a07ddf05a32042dffac965" + * }) + */ + public blockContact( + request: Intercom.BlockContactRequest, + requestOptions?: ContactsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__blockContact(request, requestOptions)); } - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { + private async __blockContact( + request: Intercom.BlockContactRequest, + requestOptions?: ContactsClient.RequestOptions, + ): Promise> { + const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `contacts/${core.url.encodePathParam(contactId)}/block`, + ), + method: "POST", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ContactBlocked, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, }); } - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{contact_id}/block"); } } diff --git a/src/api/resources/contacts/client/index.ts b/src/api/resources/contacts/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/contacts/client/index.ts +++ b/src/api/resources/contacts/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/contacts/client/requests/ArchiveContactRequest.ts b/src/api/resources/contacts/client/requests/ArchiveContactRequest.ts index 1e5452c4..9a3380a0 100644 --- a/src/api/resources/contacts/client/requests/ArchiveContactRequest.ts +++ b/src/api/resources/contacts/client/requests/ArchiveContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ArchiveContactRequest { - /** - * id - */ + /** contact_id */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/AttachSubscriptionToContactRequest.ts b/src/api/resources/contacts/client/requests/AttachSubscriptionToContactRequest.ts index 6433e324..8bd134af 100644 --- a/src/api/resources/contacts/client/requests/AttachSubscriptionToContactRequest.ts +++ b/src/api/resources/contacts/client/requests/AttachSubscriptionToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,9 +23,7 @@ * } */ export interface AttachSubscriptionToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; /** The unique identifier for the subscription which is given by Intercom */ id: string; diff --git a/src/api/resources/contacts/client/requests/BlockContactRequest.ts b/src/api/resources/contacts/client/requests/BlockContactRequest.ts new file mode 100644 index 00000000..538c9a21 --- /dev/null +++ b/src/api/resources/contacts/client/requests/BlockContactRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * contact_id: "63a07ddf05a32042dffac965" + * } + */ +export interface BlockContactRequest { + /** contact_id */ + contact_id: string; +} diff --git a/src/api/resources/contacts/client/requests/DeleteContactRequest.ts b/src/api/resources/contacts/client/requests/DeleteContactRequest.ts index 559cfeb9..42fb1445 100644 --- a/src/api/resources/contacts/client/requests/DeleteContactRequest.ts +++ b/src/api/resources/contacts/client/requests/DeleteContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteContactRequest { - /** - * id - */ + /** contact_id */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/DetachSubscriptionFromContactRequest.ts b/src/api/resources/contacts/client/requests/DetachSubscriptionFromContactRequest.ts index 081c1459..d5a9e4e3 100644 --- a/src/api/resources/contacts/client/requests/DetachSubscriptionFromContactRequest.ts +++ b/src/api/resources/contacts/client/requests/DetachSubscriptionFromContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DetachSubscriptionFromContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the subscription type which is given by Intercom - */ + /** The unique identifier for the subscription type which is given by Intercom */ subscription_id: string; } diff --git a/src/api/resources/contacts/client/requests/FindContactRequest.ts b/src/api/resources/contacts/client/requests/FindContactRequest.ts index 3eed3e85..a73c27ad 100644 --- a/src/api/resources/contacts/client/requests/FindContactRequest.ts +++ b/src/api/resources/contacts/client/requests/FindContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindContactRequest { - /** - * id - */ + /** contact_id */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/ListAttachedCompaniesRequest.ts b/src/api/resources/contacts/client/requests/ListAttachedCompaniesRequest.ts index 5c1f5caa..bf57a734 100644 --- a/src/api/resources/contacts/client/requests/ListAttachedCompaniesRequest.ts +++ b/src/api/resources/contacts/client/requests/ListAttachedCompaniesRequest.ts @@ -1,24 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * contact_id: "63a07ddf05a32042dffac965" + * contact_id: "63a07ddf05a32042dffac965", + * page: 1, + * per_page: 1 * } */ export interface ListAttachedCompaniesRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/contacts/client/requests/ListAttachedSubscriptionsRequest.ts b/src/api/resources/contacts/client/requests/ListAttachedSubscriptionsRequest.ts index 3ab3f449..12dce4dd 100644 --- a/src/api/resources/contacts/client/requests/ListAttachedSubscriptionsRequest.ts +++ b/src/api/resources/contacts/client/requests/ListAttachedSubscriptionsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListAttachedSubscriptionsRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/ListContactsRequest.ts b/src/api/resources/contacts/client/requests/ListContactsRequest.ts index b67a189f..779b4121 100644 --- a/src/api/resources/contacts/client/requests/ListContactsRequest.ts +++ b/src/api/resources/contacts/client/requests/ListContactsRequest.ts @@ -1,22 +1,14 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * {} */ export interface ListContactsRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; - /** - * String used to get the next page of conversations. - */ + /** String used to get the next page of conversations. */ starting_after?: string; } diff --git a/src/api/resources/contacts/client/requests/ListSegmentsAttachedToContactRequest.ts b/src/api/resources/contacts/client/requests/ListSegmentsAttachedToContactRequest.ts index b120b483..f2fe1a11 100644 --- a/src/api/resources/contacts/client/requests/ListSegmentsAttachedToContactRequest.ts +++ b/src/api/resources/contacts/client/requests/ListSegmentsAttachedToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListSegmentsAttachedToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/ListTagsAttachedToContactRequest.ts b/src/api/resources/contacts/client/requests/ListTagsAttachedToContactRequest.ts index 632002f6..1d62aa60 100644 --- a/src/api/resources/contacts/client/requests/ListTagsAttachedToContactRequest.ts +++ b/src/api/resources/contacts/client/requests/ListTagsAttachedToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListTagsAttachedToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/MergeContactsRequest.ts b/src/api/resources/contacts/client/requests/MergeContactsRequest.ts index 704efeb1..520d7f83 100644 --- a/src/api/resources/contacts/client/requests/MergeContactsRequest.ts +++ b/src/api/resources/contacts/client/requests/MergeContactsRequest.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * from: "667d60ac8a68186f43bafdbb", - * into: "667d60ac8a68186f43bafdbc" + * from: "6762f0d51bb69f9f2193bb7f", + * into: "6762f0d51bb69f9f2193bb80" * } */ export interface MergeContactsRequest { /** The unique identifier for the contact to merge away from. Must be a lead. */ - from: string; + from?: string; /** The unique identifier for the contact to merge into. Must be a user. */ - into: string; + into?: string; } diff --git a/src/api/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts b/src/api/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts new file mode 100644 index 00000000..d6f2b0d8 --- /dev/null +++ b/src/api/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27" + * } + */ +export interface ShowContactByExternalIdRequest { + /** The external ID of the user that you want to retrieve */ + external_id: string; +} diff --git a/src/api/resources/contacts/client/requests/UnarchiveContactRequest.ts b/src/api/resources/contacts/client/requests/UnarchiveContactRequest.ts index f014d7d2..76ecc8e1 100644 --- a/src/api/resources/contacts/client/requests/UnarchiveContactRequest.ts +++ b/src/api/resources/contacts/client/requests/UnarchiveContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface UnarchiveContactRequest { - /** - * id - */ + /** contact_id */ contact_id: string; } diff --git a/src/api/resources/contacts/client/requests/UpdateContactRequest.ts b/src/api/resources/contacts/client/requests/UpdateContactRequest.ts index 109178e2..3f048efd 100644 --- a/src/api/resources/contacts/client/requests/UpdateContactRequest.ts +++ b/src/api/resources/contacts/client/requests/UpdateContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,11 +7,19 @@ * email: "joebloggs@intercom.io", * name: "joe bloggs" * } + * + * @example + * { + * contact_id: "63a07ddf05a32042dffac965", + * custom_attributes: { + * "order": [ + * "21" + * ] + * } + * } */ export interface UpdateContactRequest { - /** - * id - */ + /** id */ contact_id: string; /** The role of the contact. */ role?: string; diff --git a/src/api/resources/contacts/client/requests/index.ts b/src/api/resources/contacts/client/requests/index.ts index 1e895632..60cacd37 100644 --- a/src/api/resources/contacts/client/requests/index.ts +++ b/src/api/resources/contacts/client/requests/index.ts @@ -1,13 +1,15 @@ -export { type ListAttachedCompaniesRequest } from "./ListAttachedCompaniesRequest"; -export { type ListSegmentsAttachedToContactRequest } from "./ListSegmentsAttachedToContactRequest"; -export { type ListAttachedSubscriptionsRequest } from "./ListAttachedSubscriptionsRequest"; -export { type AttachSubscriptionToContactRequest } from "./AttachSubscriptionToContactRequest"; -export { type DetachSubscriptionFromContactRequest } from "./DetachSubscriptionFromContactRequest"; -export { type ListTagsAttachedToContactRequest } from "./ListTagsAttachedToContactRequest"; -export { type FindContactRequest } from "./FindContactRequest"; -export { type UpdateContactRequest } from "./UpdateContactRequest"; -export { type DeleteContactRequest } from "./DeleteContactRequest"; -export { type MergeContactsRequest } from "./MergeContactsRequest"; -export { type ListContactsRequest } from "./ListContactsRequest"; -export { type ArchiveContactRequest } from "./ArchiveContactRequest"; -export { type UnarchiveContactRequest } from "./UnarchiveContactRequest"; +export type { ArchiveContactRequest } from "./ArchiveContactRequest.js"; +export type { AttachSubscriptionToContactRequest } from "./AttachSubscriptionToContactRequest.js"; +export type { BlockContactRequest } from "./BlockContactRequest.js"; +export type { DeleteContactRequest } from "./DeleteContactRequest.js"; +export type { DetachSubscriptionFromContactRequest } from "./DetachSubscriptionFromContactRequest.js"; +export type { FindContactRequest } from "./FindContactRequest.js"; +export type { ListAttachedCompaniesRequest } from "./ListAttachedCompaniesRequest.js"; +export type { ListAttachedSubscriptionsRequest } from "./ListAttachedSubscriptionsRequest.js"; +export type { ListContactsRequest } from "./ListContactsRequest.js"; +export type { ListSegmentsAttachedToContactRequest } from "./ListSegmentsAttachedToContactRequest.js"; +export type { ListTagsAttachedToContactRequest } from "./ListTagsAttachedToContactRequest.js"; +export type { MergeContactsRequest } from "./MergeContactsRequest.js"; +export type { ShowContactByExternalIdRequest } from "./ShowContactByExternalIdRequest.js"; +export type { UnarchiveContactRequest } from "./UnarchiveContactRequest.js"; +export type { UpdateContactRequest } from "./UpdateContactRequest.js"; diff --git a/src/api/resources/contacts/index.ts b/src/api/resources/contacts/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/contacts/index.ts +++ b/src/api/resources/contacts/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/contacts/types/Contact.ts b/src/api/resources/contacts/types/Contact.ts index a9bed2d3..7c6e6305 100644 --- a/src/api/resources/contacts/types/Contact.ts +++ b/src/api/resources/contacts/types/Contact.ts @@ -1,45 +1,41 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** - * Contact are the objects that represent your leads and users in Intercom. + * Contacts represent your leads and users in Intercom. */ export interface Contact { /** The type of object. */ type?: "contact"; /** The unique identifier for the contact which is given by Intercom. */ - id: string; + id?: string; /** The unique identifier for the contact which is provided by the Client. */ external_id?: string; /** The id of the workspace which the contact belongs to. */ - workspace_id: string; + workspace_id?: string; /** The role of the contact. */ - role: string; + role?: string; /** The contact's email. */ email?: string; /** The contact's email domain. */ email_domain?: string; /** The contacts phone. */ phone?: string; - /** The contacts phone number normalized to the E164 format */ - formatted_phone?: string; /** The contacts name. */ name?: string; /** The id of an admin that has been assigned account ownership of the contact. */ owner_id?: number; /** Whether the contact has had an email sent to them hard bounce. */ - has_hard_bounced: boolean; + has_hard_bounced?: boolean; /** Whether the contact has marked an email sent to them as spam. */ - marked_email_as_spam: boolean; + marked_email_as_spam?: boolean; /** Whether the contact is unsubscribed from emails. */ - unsubscribed_from_emails: boolean; + unsubscribed_from_emails?: boolean; /** (UNIX timestamp) The time when the contact was created. */ - created_at: number; + created_at?: number; /** (UNIX timestamp) The time when the contact was last updated. */ - updated_at: number; + updated_at?: number; /** (UNIX timestamp) The time specified for when a contact signed up. */ signed_up_at?: number; /** (UNIX timestamp) The time when the contact was last seen (either where the Intercom Messenger was installed or when specified manually). */ @@ -93,6 +89,6 @@ export interface Contact { tags?: Intercom.ContactTags; notes?: Intercom.ContactNotes; companies?: Intercom.ContactCompanies; - location: Intercom.ContactLocation; - social_profiles: Intercom.ContactSocialProfiles; + location?: Intercom.ContactLocation; + social_profiles?: Intercom.ContactSocialProfiles; } diff --git a/src/api/resources/contacts/types/ContactsCreateResponse.ts b/src/api/resources/contacts/types/ContactsCreateResponse.ts new file mode 100644 index 00000000..c124d661 --- /dev/null +++ b/src/api/resources/contacts/types/ContactsCreateResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ContactsCreateResponse extends Intercom.Contact { + /** If the user has enabled push messaging. */ + enabled_push_messaging?: boolean; +} diff --git a/src/api/resources/contacts/types/ContactsFindResponse.ts b/src/api/resources/contacts/types/ContactsFindResponse.ts new file mode 100644 index 00000000..96ff7ff5 --- /dev/null +++ b/src/api/resources/contacts/types/ContactsFindResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ContactsFindResponse extends Intercom.Contact { + /** If the user has enabled push messaging. */ + enabled_push_messaging?: boolean; +} diff --git a/src/api/resources/contacts/types/ContactsMergeLeadInUserResponse.ts b/src/api/resources/contacts/types/ContactsMergeLeadInUserResponse.ts new file mode 100644 index 00000000..95ca8cfb --- /dev/null +++ b/src/api/resources/contacts/types/ContactsMergeLeadInUserResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ContactsMergeLeadInUserResponse extends Intercom.Contact { + /** If the user has enabled push messaging. */ + enabled_push_messaging?: boolean; +} diff --git a/src/api/resources/contacts/types/ContactsUpdateResponse.ts b/src/api/resources/contacts/types/ContactsUpdateResponse.ts new file mode 100644 index 00000000..736895ee --- /dev/null +++ b/src/api/resources/contacts/types/ContactsUpdateResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ContactsUpdateResponse extends Intercom.Contact { + /** If the user has enabled push messaging. */ + enabled_push_messaging?: boolean; +} diff --git a/src/api/resources/contacts/types/ShowContactByExternalIdResponse.ts b/src/api/resources/contacts/types/ShowContactByExternalIdResponse.ts new file mode 100644 index 00000000..c6dbf5c1 --- /dev/null +++ b/src/api/resources/contacts/types/ShowContactByExternalIdResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +export interface ShowContactByExternalIdResponse extends Intercom.Contact { + /** If the user has enabled push messaging. */ + enabled_push_messaging?: boolean; +} diff --git a/src/api/resources/contacts/types/index.ts b/src/api/resources/contacts/types/index.ts index b538eafc..adc73bae 100644 --- a/src/api/resources/contacts/types/index.ts +++ b/src/api/resources/contacts/types/index.ts @@ -1 +1,6 @@ -export * from "./Contact"; +export * from "./Contact.js"; +export * from "./ContactsCreateResponse.js"; +export * from "./ContactsFindResponse.js"; +export * from "./ContactsMergeLeadInUserResponse.js"; +export * from "./ContactsUpdateResponse.js"; +export * from "./ShowContactByExternalIdResponse.js"; diff --git a/src/api/resources/conversations/client/Client.ts b/src/api/resources/conversations/client/Client.ts index d24ccbfd..af9f6fc0 100644 --- a/src/api/resources/conversations/client/Client.ts +++ b/src/api/resources/conversations/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Conversations { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ConversationsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Conversations */ -export class Conversations { - constructor(protected readonly _options: Conversations.Options = {}) {} +export class ConversationsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ConversationsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all conversations. @@ -85,62 +35,58 @@ export class Conversations { * {% /admonition %} * * @param {Intercom.ListConversationsRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} * * @example - * await client.conversations.list() + * await client.conversations.list({ + * per_page: 1, + * starting_after: "starting_after" + * }) */ public async list( request: Intercom.ListConversationsRequest = {}, - requestOptions?: Conversations.RequestOptions, - ): Promise> { + requestOptions?: ConversationsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async ( request: Intercom.ListConversationsRequest, - ): Promise> => { + ): Promise> => { const { per_page: perPage, starting_after: startingAfter } = request; const _queryParams: Record = {}; if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (startingAfter != null) { - _queryParams["starting_after"] = startingAfter; + _queryParams.starting_after = startingAfter; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { - data: _response.body as Intercom.PaginatedConversationResponse, - rawResponse: _response.rawResponse, - }; + return { data: _response.body as Intercom.ConversationList, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { switch (_response.error.statusCode) { @@ -162,28 +108,19 @@ export class Conversations { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /conversations."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/conversations"); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.pages?.next?.starting_after != null, + hasNextPage: (response) => + response?.pages?.next?.starting_after != null && + !( + typeof response?.pages?.next?.starting_after === "string" && + response?.pages?.next?.starting_after === "" + ), getItems: (response) => response?.conversations ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "starting_after", response?.pages?.next?.starting_after)); @@ -202,8 +139,9 @@ export class Conversations { * * This will return the Message model that has been created. * + * * @param {Intercom.CreateConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -213,7 +151,7 @@ export class Conversations { * await client.conversations.create({ * from: { * type: "user", - * id: "667d60d18a68186f43bafddd" + * id: "6762f11b1bb69f9f2193bba3" * }, * body: "Hello there" * }) @@ -229,40 +167,40 @@ export class Conversations { */ public create( request: Intercom.CreateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Message, rawResponse: _response.rawResponse }; @@ -288,21 +226,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations"); } /** @@ -318,7 +242,7 @@ export class Conversations { * For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671). * * @param {Intercom.FindConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -327,51 +251,57 @@ export class Conversations { * @example * await client.conversations.find({ * conversation_id: "123", - * display_as: "plaintext" + * display_as: "plaintext", + * include_translations: true * }) */ public find( request: Intercom.FindConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { - const { conversation_id: conversationId, display_as: displayAs } = request; + const { + conversation_id: conversationId, + display_as: displayAs, + include_translations: includeTranslations, + } = request; const _queryParams: Record = {}; if (displayAs != null) { - _queryParams["display_as"] = displayAs; + _queryParams.display_as = displayAs; + } + + if (includeTranslations != null) { + _queryParams.include_translations = includeTranslations.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}`, + `conversations/${core.url.encodePathParam(conversationId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -397,23 +327,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /conversations/{conversation_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/conversations/{conversation_id}", + ); } /** @@ -424,8 +343,15 @@ export class Conversations { * If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. * {% /admonition %} * + * {% admonition type="info" %} + * This endpoint handles both **conversation updates** and **custom object associations**. + * + * See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format. + * {% /admonition %} + * + * * @param {Intercom.UpdateConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -433,58 +359,67 @@ export class Conversations { * * @example * await client.conversations.update({ - * conversation_id: "123", + * conversation_id: "conversation_id", * display_as: "plaintext", * read: true, + * title: "new conversation title", * custom_attributes: { * "issue_type": "Billing", * "priority": "High" * } * }) + * + * @example + * await client.conversations.update({ + * conversation_id: "conversation_id", + * display_as: "plaintext", + * custom_attributes: { + * "order": {} + * } + * }) */ public update( request: Intercom.UpdateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, display_as: displayAs, ..._body } = request; const _queryParams: Record = {}; if (displayAs != null) { - _queryParams["display_as"] = displayAs; + _queryParams.display_as = displayAs; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}`, + `conversations/${core.url.encodePathParam(conversationId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", - queryParameters: _queryParams, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -510,23 +445,91 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /conversations/{conversation_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/conversations/{conversation_id}", + ); + } + + /** + * You can delete a single conversation. + * + * @param {Intercom.DeleteConversationRequest} request + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.ForbiddenError} + * + * @example + * await client.conversations.deleteConversation({ + * conversation_id: 1 + * }) + */ + public deleteConversation( + request: Intercom.DeleteConversationRequest, + requestOptions?: ConversationsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteConversation(request, requestOptions)); + } + + private async __deleteConversation( + request: Intercom.DeleteConversationRequest, + requestOptions?: ConversationsClient.RequestOptions, + ): Promise> { + const { conversation_id: conversationId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `conversations/${core.url.encodePathParam(conversationId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.ConversationDeleted, rawResponse: _response.rawResponse }; } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 403: + throw new Intercom.ForbiddenError(_response.error.body as Intercom.Error_, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/conversations/{conversation_id}", + ); } /** @@ -551,7 +554,7 @@ export class Conversations { * * ### Accepted Fields * - * Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). + * Most keys listed in the conversation model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foorbar"`). * The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. * * | Field | Type | @@ -631,7 +634,7 @@ export class Conversations { * | $ | String | Ends With | * * @param {Intercom.SearchRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.conversations.search({ @@ -650,44 +653,38 @@ export class Conversations { */ public async search( request: Intercom.SearchRequest, - requestOptions?: Conversations.RequestOptions, - ): Promise> { + requestOptions?: ConversationsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( - async ( - request: Intercom.SearchRequest, - ): Promise> => { + async (request: Intercom.SearchRequest): Promise> => { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { - data: _response.body as Intercom.PaginatedConversationResponse, - rawResponse: _response.rawResponse, - }; + return { data: _response.body as Intercom.ConversationList, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { throw new errors.IntercomError({ @@ -696,30 +693,24 @@ export class Conversations { rawResponse: _response.rawResponse, }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/search.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/search", + ); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.pages?.next?.starting_after != null, + hasNextPage: (response) => + response?.pages?.next?.starting_after != null && + !( + typeof response?.pages?.next?.starting_after === "string" && + response?.pages?.next?.starting_after === "" + ), getItems: (response) => response?.conversations ?? [], loadPage: (response) => { return list( @@ -733,7 +724,7 @@ export class Conversations { * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. * * @param {Intercom.ReplyToConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -746,7 +737,7 @@ export class Conversations { * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f18a68186f43bafdf4" + * intercom_user_id: "6762f1571bb69f9f2193bbbb" * } * }) * @@ -765,10 +756,31 @@ export class Conversations { * await client.conversations.reply({ * conversation_id: "123 or \"last\"", * body: { + * message_type: "quick_reply", + * type: "admin", + * admin_id: "3156780", + * reply_options: [{ + * text: "Yes", + * uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" + * }, { + * text: "No", + * uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6" + * }] + * } + * }) + * + * @example + * await client.conversations.reply({ + * conversation_id: "123 or \"last\"", + * body: { * message_type: "comment", * type: "user", - * body: "Thanks again :)", - * intercom_user_id: "667d60f78a68186f43bafdf7" + * body: "body", + * reply_options: [{ + * text: "Yes", + * uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" + * }], + * intercom_user_id: "6762f1621bb69f9f2193bbbe" * } * }) * @@ -779,47 +791,47 @@ export class Conversations { * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f98a68186f43bafdf8" + * intercom_user_id: "6762f1661bb69f9f2193bbbf" * } * }) */ public reply( request: Intercom.ReplyToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__reply(request, requestOptions)); } private async __reply( request: Intercom.ReplyToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/reply`, + `conversations/${core.url.encodePathParam(conversationId)}/reply`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -845,23 +857,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/reply.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/reply", + ); } /** @@ -872,7 +873,7 @@ export class Conversations { * - Assign a conversation to an admin and/or team. * * @param {Intercom.ManageConversationPartsRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -920,41 +921,41 @@ export class Conversations { */ public manage( request: Intercom.ManageConversationPartsRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__manage(request, requestOptions)); } private async __manage( request: Intercom.ManageConversationPartsRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/parts`, + `conversations/${core.url.encodePathParam(conversationId)}/parts`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -980,124 +981,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/parts.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - /** - * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} - * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. - * {% /admonition %} - * You can let a conversation be automatically assigned following assignment rules. - * {% admonition type="warning" name="When using workflows" %} - * It is not possible to use this endpoint with Workflows. - * {% /admonition %} - * - * @param {Intercom.AutoAssignConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. - * - * @throws {@link Intercom.UnauthorizedError} - * @throws {@link Intercom.ForbiddenError} - * @throws {@link Intercom.NotFoundError} - * - * @example - * await client.conversations.runAssignmentRules({ - * conversation_id: "123" - * }) - */ - public runAssignmentRules( - request: Intercom.AutoAssignConversationRequest, - requestOptions?: Conversations.RequestOptions, - ): core.HttpResponsePromise { - return core.HttpResponsePromise.fromPromise(this.__runAssignmentRules(request, requestOptions)); - } - - private async __runAssignmentRules( - request: Intercom.AutoAssignConversationRequest, - requestOptions?: Conversations.RequestOptions, - ): Promise> { - const { conversation_id: conversationId } = request; - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/run_assignment_rules`, - ), - method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; - } - - if (_response.error.reason === "status-code") { - switch (_response.error.statusCode) { - case 401: - throw new Intercom.UnauthorizedError( - _response.error.body as Intercom.Error_, - _response.rawResponse, - ); - case 403: - throw new Intercom.ForbiddenError(_response.error.body as Intercom.Error_, _response.rawResponse); - case 404: - throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); - default: - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - rawResponse: _response.rawResponse, - }); - } - } - - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/run_assignment_rules.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/parts", + ); } /** @@ -1107,8 +996,9 @@ export class Conversations { * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. * {% /admonition %} * + * * @param {Intercom.AttachContactToConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -1119,7 +1009,7 @@ export class Conversations { * conversation_id: "123", * admin_id: "12345", * customer: { - * intercom_user_id: "667d61168a68186f43bafe0d" + * intercom_user_id: "6762f19b1bb69f9f2193bbd4" * } * }) * @@ -1128,47 +1018,47 @@ export class Conversations { * conversation_id: "123", * admin_id: "12345", * customer: { - * intercom_user_id: "667d61188a68186f43bafe0e" + * intercom_user_id: "6762f19e1bb69f9f2193bbd5" * } * }) */ public attachContactAsAdmin( request: Intercom.AttachContactToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachContactAsAdmin(request, requestOptions)); } private async __attachContactAsAdmin( request: Intercom.AttachContactToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/customers`, + `conversations/${core.url.encodePathParam(conversationId)}/customers`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -1194,23 +1084,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/customers.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/customers", + ); } /** @@ -1220,8 +1099,9 @@ export class Conversations { * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. * {% /admonition %} * + * * @param {Intercom.DetachContactFromConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.ForbiddenError} @@ -1237,41 +1117,41 @@ export class Conversations { */ public detachContactAsAdmin( request: Intercom.DetachContactFromConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachContactAsAdmin(request, requestOptions)); } private async __detachContactAsAdmin( request: Intercom.DetachContactFromConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/customers/${encodeURIComponent(contactId)}`, + `conversations/${core.url.encodePathParam(conversationId)}/customers/${core.url.encodePathParam(contactId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -1299,23 +1179,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /conversations/{conversation_id}/customers/{contact_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/conversations/{conversation_id}/customers/{contact_id}", + ); } /** @@ -1325,8 +1194,9 @@ export class Conversations { * If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. * {% /admonition %} * + * * @param {Intercom.RedactConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -1347,40 +1217,40 @@ export class Conversations { */ public redactConversationPart( request: Intercom.RedactConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__redactConversationPart(request, requestOptions)); } private async __redactConversationPart( request: Intercom.RedactConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations/redact", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; @@ -1404,83 +1274,69 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations/redact."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/redact"); } /** * You can convert a conversation to a ticket. * * @param {Intercom.ConvertConversationToTicketRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * * @example * await client.conversations.convertToTicket({ - * conversation_id: "123", - * ticket_type_id: "79" + * conversation_id: 1, + * ticket_type_id: "53" * }) * * @example * await client.conversations.convertToTicket({ - * conversation_id: "123", - * ticket_type_id: "80" + * conversation_id: 1, + * ticket_type_id: "54" * }) */ public convertToTicket( request: Intercom.ConvertConversationToTicketRequest, - requestOptions?: Conversations.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: ConversationsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__convertToTicket(request, requestOptions)); } private async __convertToTicket( request: Intercom.ConvertConversationToTicketRequest, - requestOptions?: Conversations.RequestOptions, - ): Promise> { + requestOptions?: ConversationsClient.RequestOptions, + ): Promise> { const { conversation_id: conversationId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/convert`, + `conversations/${core.url.encodePathParam(conversationId)}/convert`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Ticket, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Ticket | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -1496,34 +1352,99 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/convert.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/convert", + ); + } + + /** + * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} + * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. + * {% /admonition %} + * You can let a conversation be automatically assigned following assignment rules. + * {% admonition type="warning" name="When using workflows" %} + * It is not possible to use this endpoint with Workflows. + * {% /admonition %} + * + * @param {Intercom.AutoAssignConversationRequest} request + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.ForbiddenError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.conversations.runAssignmentRules({ + * conversation_id: "123" + * }) + */ + public runAssignmentRules( + request: Intercom.AutoAssignConversationRequest, + requestOptions?: ConversationsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__runAssignmentRules(request, requestOptions)); } - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); + private async __runAssignmentRules( + request: Intercom.AutoAssignConversationRequest, + requestOptions?: ConversationsClient.RequestOptions, + ): Promise> { + const { conversation_id: conversationId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `conversations/${core.url.encodePathParam(conversationId)}/run_assignment_rules`, + ), + method: "POST", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.Conversation, rawResponse: _response.rawResponse }; } - return `Bearer ${bearer}`; + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 403: + throw new Intercom.ForbiddenError(_response.error.body as Intercom.Error_, _response.rawResponse); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/run_assignment_rules", + ); } } diff --git a/src/api/resources/conversations/client/index.ts b/src/api/resources/conversations/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/conversations/client/index.ts +++ b/src/api/resources/conversations/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/conversations/client/requests/AttachContactToConversationRequest.ts b/src/api/resources/conversations/client/requests/AttachContactToConversationRequest.ts index 852c6c2f..26b7dd3a 100644 --- a/src/api/resources/conversations/client/requests/AttachContactToConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/AttachContactToConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example @@ -10,7 +8,7 @@ import * as Intercom from "../../../../index"; * conversation_id: "123", * admin_id: "12345", * customer: { - * intercom_user_id: "667d61168a68186f43bafe0d" + * intercom_user_id: "6762f19b1bb69f9f2193bbd4" * } * } * @@ -19,14 +17,12 @@ import * as Intercom from "../../../../index"; * conversation_id: "123", * admin_id: "12345", * customer: { - * intercom_user_id: "667d61188a68186f43bafe0e" + * intercom_user_id: "6762f19e1bb69f9f2193bbd5" * } * } */ export interface AttachContactToConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ conversation_id: string; /** The `id` of the admin who is adding the new participant. */ admin_id?: string; diff --git a/src/api/resources/conversations/client/requests/AutoAssignConversationRequest.ts b/src/api/resources/conversations/client/requests/AutoAssignConversationRequest.ts index b5f6e0c6..a5a03bdc 100644 --- a/src/api/resources/conversations/client/requests/AutoAssignConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/AutoAssignConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface AutoAssignConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ conversation_id: string; } diff --git a/src/api/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts b/src/api/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts index ce9e3abc..c5593cee 100644 --- a/src/api/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts +++ b/src/api/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts @@ -1,27 +1,23 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example * { - * conversation_id: "123", - * ticket_type_id: "79" + * conversation_id: 1, + * ticket_type_id: "53" * } * * @example * { - * conversation_id: "123", - * ticket_type_id: "80" + * conversation_id: 1, + * ticket_type_id: "54" * } */ export interface ConvertConversationToTicketRequest { - /** - * The id of the conversation to target - */ - conversation_id: string; + /** The id of the conversation to target */ + conversation_id: number; /** The ID of the type of ticket you want to convert the conversation to */ ticket_type_id: string; attributes?: Intercom.TicketRequestCustomAttributes; diff --git a/src/api/resources/conversations/client/requests/CreateConversationRequest.ts b/src/api/resources/conversations/client/requests/CreateConversationRequest.ts index 4c82a814..0f8bcd9a 100644 --- a/src/api/resources/conversations/client/requests/CreateConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/CreateConversationRequest.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * from: { * type: "user", - * id: "667d60d18a68186f43bafddd" + * id: "6762f11b1bb69f9f2193bba3" * }, * body: "Hello there" * } @@ -38,14 +36,12 @@ export namespace CreateConversationRequest { } export namespace From { - /** - * The role associated to the contact - user or lead. - */ - export type Type = "lead" | "user" | "contact"; + /** The role associated to the contact - user or lead. */ export const Type = { Lead: "lead", User: "user", Contact: "contact", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } diff --git a/src/api/resources/conversations/client/requests/DeleteConversationRequest.ts b/src/api/resources/conversations/client/requests/DeleteConversationRequest.ts new file mode 100644 index 00000000..a5bf5e64 --- /dev/null +++ b/src/api/resources/conversations/client/requests/DeleteConversationRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * conversation_id: 1 + * } + */ +export interface DeleteConversationRequest { + /** id */ + conversation_id: number; +} diff --git a/src/api/resources/conversations/client/requests/DetachContactFromConversationRequest.ts b/src/api/resources/conversations/client/requests/DetachContactFromConversationRequest.ts index e245b23d..415bfae9 100644 --- a/src/api/resources/conversations/client/requests/DetachContactFromConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/DetachContactFromConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -32,13 +30,9 @@ * } */ export interface DetachContactFromConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ conversation_id: string; - /** - * The identifier for the contact as given by Intercom. - */ + /** The identifier for the contact as given by Intercom. */ contact_id: string; /** The `id` of the admin who is performing the action. */ admin_id: string; diff --git a/src/api/resources/conversations/client/requests/FindConversationRequest.ts b/src/api/resources/conversations/client/requests/FindConversationRequest.ts index 094cfa53..c80a7032 100644 --- a/src/api/resources/conversations/client/requests/FindConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/FindConversationRequest.ts @@ -1,21 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * conversation_id: "123", - * display_as: "plaintext" + * display_as: "plaintext", + * include_translations: true * } */ export interface FindConversationRequest { - /** - * The id of the conversation to target - */ + /** The id of the conversation to target */ conversation_id: string; - /** - * Set to plaintext to retrieve conversation messages in plain text. - */ + /** Set to plaintext to retrieve conversation messages in plain text. */ display_as?: string; + /** If set to true, conversation parts will be translated to the detected language of the conversation. */ + include_translations?: boolean; } diff --git a/src/api/resources/conversations/client/requests/ListConversationsRequest.ts b/src/api/resources/conversations/client/requests/ListConversationsRequest.ts index f3c7f741..4908f563 100644 --- a/src/api/resources/conversations/client/requests/ListConversationsRequest.ts +++ b/src/api/resources/conversations/client/requests/ListConversationsRequest.ts @@ -1,18 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * per_page: 1, + * starting_after: "starting_after" + * } */ export interface ListConversationsRequest { - /** - * How many results per page - */ + /** How many results per page */ per_page?: number; - /** - * String used to get the next page of conversations. - */ + /** String used to get the next page of conversations. */ starting_after?: string; } diff --git a/src/api/resources/conversations/client/requests/ManageConversationPartsRequest.ts b/src/api/resources/conversations/client/requests/ManageConversationPartsRequest.ts index 48c245e7..a16fe3ec 100644 --- a/src/api/resources/conversations/client/requests/ManageConversationPartsRequest.ts +++ b/src/api/resources/conversations/client/requests/ManageConversationPartsRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example @@ -56,9 +54,7 @@ import * as Intercom from "../../../../index"; * } */ export interface ManageConversationPartsRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ conversation_id: string; body: Intercom.ConversationsManageRequestBody; } diff --git a/src/api/resources/conversations/client/requests/ReplyToConversationRequest.ts b/src/api/resources/conversations/client/requests/ReplyToConversationRequest.ts index e9ae5970..9ef917d8 100644 --- a/src/api/resources/conversations/client/requests/ReplyToConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/ReplyToConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example @@ -12,7 +10,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f18a68186f43bafdf4" + * intercom_user_id: "6762f1571bb69f9f2193bbbb" * } * } * @@ -31,10 +29,31 @@ import * as Intercom from "../../../../index"; * { * conversation_id: "123 or \"last\"", * body: { + * message_type: "quick_reply", + * type: "admin", + * admin_id: "3156780", + * reply_options: [{ + * text: "Yes", + * uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" + * }, { + * text: "No", + * uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6" + * }] + * } + * } + * + * @example + * { + * conversation_id: "123 or \"last\"", + * body: { * message_type: "comment", * type: "user", - * body: "Thanks again :)", - * intercom_user_id: "667d60f78a68186f43bafdf7" + * body: "body", + * reply_options: [{ + * text: "Yes", + * uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" + * }], + * intercom_user_id: "6762f1621bb69f9f2193bbbe" * } * } * @@ -45,7 +64,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f98a68186f43bafdf8" + * intercom_user_id: "6762f1661bb69f9f2193bbbf" * } * } * @@ -56,7 +75,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f18a68186f43bafdf4" + * intercom_user_id: "6762f1571bb69f9f2193bbbb" * } * } * @@ -67,7 +86,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f18a68186f43bafdf4" + * intercom_user_id: "6762f1571bb69f9f2193bbbb" * } * } * @@ -78,14 +97,12 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d60f18a68186f43bafdf4" + * intercom_user_id: "6762f1571bb69f9f2193bbbb" * } * } */ export interface ReplyToConversationRequest { - /** - * The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation - */ + /** The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation */ conversation_id: string; body: Intercom.ReplyConversationRequest; } diff --git a/src/api/resources/conversations/client/requests/UpdateConversationRequest.ts b/src/api/resources/conversations/client/requests/UpdateConversationRequest.ts index 0590a00c..164ecefe 100644 --- a/src/api/resources/conversations/client/requests/UpdateConversationRequest.ts +++ b/src/api/resources/conversations/client/requests/UpdateConversationRequest.ts @@ -1,15 +1,14 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example * { - * conversation_id: "123", + * conversation_id: "conversation_id", * display_as: "plaintext", * read: true, + * title: "new conversation title", * custom_attributes: { * "issue_type": "Billing", * "priority": "High" @@ -18,9 +17,19 @@ import * as Intercom from "../../../../index"; * * @example * { - * conversation_id: "123", + * conversation_id: "conversation_id", + * display_as: "plaintext", + * custom_attributes: { + * "order": {} + * } + * } + * + * @example + * { + * conversation_id: "conversation_id", * display_as: "plaintext", * read: true, + * title: "new conversation title", * custom_attributes: { * "issue_type": "Billing", * "priority": "High" @@ -28,15 +37,15 @@ import * as Intercom from "../../../../index"; * } */ export interface UpdateConversationRequest { - /** - * The id of the conversation to target - */ + /** The id of the conversation to target */ conversation_id: string; - /** - * Set to plaintext to retrieve conversation messages in plain text. - */ + /** Set to plaintext to retrieve conversation messages in plain text. */ display_as?: string; /** Mark a conversation as read within Intercom. */ read?: boolean; + /** The title given to the conversation */ + title?: string; custom_attributes?: Intercom.CustomAttributes; + /** The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. Set to nil to remove company. */ + company_id?: string; } diff --git a/src/api/resources/conversations/client/requests/index.ts b/src/api/resources/conversations/client/requests/index.ts index fa317731..dbe79ca7 100644 --- a/src/api/resources/conversations/client/requests/index.ts +++ b/src/api/resources/conversations/client/requests/index.ts @@ -1,10 +1,11 @@ -export { type ListConversationsRequest } from "./ListConversationsRequest"; -export { type CreateConversationRequest } from "./CreateConversationRequest"; -export { type FindConversationRequest } from "./FindConversationRequest"; -export { type UpdateConversationRequest } from "./UpdateConversationRequest"; -export { type ReplyToConversationRequest } from "./ReplyToConversationRequest"; -export { type ManageConversationPartsRequest } from "./ManageConversationPartsRequest"; -export { type AutoAssignConversationRequest } from "./AutoAssignConversationRequest"; -export { type AttachContactToConversationRequest } from "./AttachContactToConversationRequest"; -export { type DetachContactFromConversationRequest } from "./DetachContactFromConversationRequest"; -export { type ConvertConversationToTicketRequest } from "./ConvertConversationToTicketRequest"; +export type { AttachContactToConversationRequest } from "./AttachContactToConversationRequest.js"; +export type { AutoAssignConversationRequest } from "./AutoAssignConversationRequest.js"; +export type { ConvertConversationToTicketRequest } from "./ConvertConversationToTicketRequest.js"; +export type { CreateConversationRequest } from "./CreateConversationRequest.js"; +export type { DeleteConversationRequest } from "./DeleteConversationRequest.js"; +export type { DetachContactFromConversationRequest } from "./DetachContactFromConversationRequest.js"; +export type { FindConversationRequest } from "./FindConversationRequest.js"; +export type { ListConversationsRequest } from "./ListConversationsRequest.js"; +export type { ManageConversationPartsRequest } from "./ManageConversationPartsRequest.js"; +export type { ReplyToConversationRequest } from "./ReplyToConversationRequest.js"; +export type { UpdateConversationRequest } from "./UpdateConversationRequest.js"; diff --git a/src/api/resources/conversations/index.ts b/src/api/resources/conversations/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/conversations/index.ts +++ b/src/api/resources/conversations/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/conversations/types/Conversation.ts b/src/api/resources/conversations/types/Conversation.ts index 3e08c1b6..95606d03 100644 --- a/src/api/resources/conversations/types/Conversation.ts +++ b/src/api/resources/conversations/types/Conversation.ts @@ -1,45 +1,45 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Conversations are how you can communicate with users in Intercom. They are created when a contact replies to an outbound message, or when one admin directly sends a message to a single contact. */ export interface Conversation { /** Always conversation. */ - type?: "conversation"; + type?: string; /** The id representing the conversation. */ - id: string; + id?: string; /** The title given to the conversation. */ title?: string; /** The time the conversation was created. */ - created_at: number; + created_at?: number; /** The last time the conversation was updated. */ - updated_at: number; + updated_at?: number; /** The last time a Contact responded to an Admin. In other words, the time a customer started waiting for a response. Set to null if last reply is from an Admin. */ waiting_since?: number; /** If set this is the time in the future when this conversation will be marked as open. i.e. it will be in a snoozed state until this time. i.e. it will be in a snoozed state until this time. */ snoozed_until?: number; /** Indicates whether a conversation is open (true) or closed (false). */ - open: boolean; + open?: boolean; /** Can be set to "open", "closed" or "snoozed". */ - state: Conversation.State; + state?: Conversation.State; /** Indicates whether a conversation has been read. */ - read: boolean; + read?: boolean; /** If marked as priority, it will return priority or else not_priority. */ priority?: Conversation.Priority; /** The id of the admin assigned to the conversation. If it's not assigned to an admin it will return null. */ admin_assignee_id?: number; /** The id of the team assigned to the conversation. If it's not assigned to a team it will return null. */ team_assignee_id?: string; + /** The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. */ + company_id?: string; tags?: Intercom.Tags; conversation_rating?: Intercom.ConversationRating; - source: Intercom.ConversationSource; - contacts: Intercom.ConversationContacts; - teammates: Intercom.ConversationTeammates; - custom_attributes: Intercom.CustomAttributes; + source?: Intercom.ConversationSource; + contacts?: Intercom.ConversationContacts; + teammates?: Intercom.ConversationTeammates; + custom_attributes?: Intercom.CustomAttributes; first_contact_reply?: Intercom.ConversationFirstContactReply; sla_applied?: Intercom.SlaApplied; statistics?: Intercom.ConversationStatistics; @@ -51,21 +51,17 @@ export interface Conversation { } export namespace Conversation { - /** - * Can be set to "open", "closed" or "snoozed". - */ - export type State = "open" | "closed" | "snoozed"; + /** Can be set to "open", "closed" or "snoozed". */ export const State = { Open: "open", Closed: "closed", Snoozed: "snoozed", } as const; - /** - * If marked as priority, it will return priority or else not_priority. - */ - export type Priority = "priority" | "not_priority"; + export type State = (typeof State)[keyof typeof State]; + /** If marked as priority, it will return priority or else not_priority. */ export const Priority = { Priority: "priority", NotPriority: "not_priority", } as const; + export type Priority = (typeof Priority)[keyof typeof Priority]; } diff --git a/src/api/resources/conversations/types/ConversationsManageRequestBody.ts b/src/api/resources/conversations/types/ConversationsManageRequestBody.ts index 232eb1e2..7a8ef883 100644 --- a/src/api/resources/conversations/types/ConversationsManageRequestBody.ts +++ b/src/api/resources/conversations/types/ConversationsManageRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type ConversationsManageRequestBody = | Intercom.ConversationsManageRequestBody.Close diff --git a/src/api/resources/conversations/types/index.ts b/src/api/resources/conversations/types/index.ts index 7ff13377..062aeafd 100644 --- a/src/api/resources/conversations/types/index.ts +++ b/src/api/resources/conversations/types/index.ts @@ -1,2 +1,2 @@ -export * from "./ConversationsManageRequestBody"; -export * from "./Conversation"; +export * from "./Conversation.js"; +export * from "./ConversationsManageRequestBody.js"; diff --git a/src/api/resources/customChannelEvents/client/Client.ts b/src/api/resources/customChannelEvents/client/Client.ts new file mode 100644 index 00000000..4ba0127c --- /dev/null +++ b/src/api/resources/customChannelEvents/client/Client.ts @@ -0,0 +1,423 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace CustomChannelEventsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * With the "Custom Channel" integration, you can bring Fin and Intercom capabilities to your own platform via API, enabling powerful custom integrations. + * + * Intercom treats your integration like any other Intercom channel, allowing your application and Intercom to exchange events seamlessly. This makes it possible, for example, for your users to interact with Fin directly within your own application’s UI. + * + * > **Note:** "Fin over API" is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. + */ +export class CustomChannelEventsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CustomChannelEventsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration. + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. + * + * @param {Intercom.CustomChannelBaseEvent} request + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * @throws {@link Intercom.UnprocessableEntityError} + * + * @example + * await client.customChannelEvents.notifyNewConversation({ + * event_id: "event_id", + * external_conversation_id: "external_conversation_id", + * contact: { + * type: "user", + * external_id: "external_id" + * } + * }) + */ + public notifyNewConversation( + request: Intercom.CustomChannelBaseEvent, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__notifyNewConversation(request, requestOptions)); + } + + private async __notifyNewConversation( + request: Intercom.CustomChannelBaseEvent, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "custom_channel_events/notify_new_conversation", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomChannelNotificationResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + case 422: + throw new Intercom.UnprocessableEntityError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_new_conversation", + ); + } + + /** + * Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations. + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. + * + * @param {Intercom.NotifyNewMessageRequest} request + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * @throws {@link Intercom.UnprocessableEntityError} + * + * @example + * await client.customChannelEvents.notifyNewMessage({ + * body: "body", + * event_id: "event_id", + * external_conversation_id: "external_conversation_id", + * contact: { + * type: "user", + * external_id: "external_id" + * } + * }) + */ + public notifyNewMessage( + request: Intercom.NotifyNewMessageRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__notifyNewMessage(request, requestOptions)); + } + + private async __notifyNewMessage( + request: Intercom.NotifyNewMessageRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "custom_channel_events/notify_new_message", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomChannelNotificationResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + case 422: + throw new Intercom.UnprocessableEntityError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_new_message", + ); + } + + /** + * Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations. + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. + * + * @param {Intercom.NotifyQuickReplySelectedRequest} request + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * @throws {@link Intercom.UnprocessableEntityError} + * + * @example + * await client.customChannelEvents.notifyQuickReplySelected({ + * event_id: "evt_67890", + * external_conversation_id: "conv_13579", + * contact: { + * type: "user", + * external_id: "user_003", + * name: "Alice Example", + * email: "alice@example.com" + * }, + * quick_reply_option_id: "1234" + * }) + */ + public notifyQuickReplySelected( + request: Intercom.NotifyQuickReplySelectedRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__notifyQuickReplySelected(request, requestOptions)); + } + + private async __notifyQuickReplySelected( + request: Intercom.NotifyQuickReplySelectedRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "custom_channel_events/notify_quick_reply_selected", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomChannelNotificationResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + case 422: + throw new Intercom.UnprocessableEntityError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_quick_reply_selected", + ); + } + + /** + * Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations. + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. + * + * @param {Intercom.NotifyAttributeCollectedRequest} request + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * @throws {@link Intercom.UnprocessableEntityError} + * + * @example + * await client.customChannelEvents.notifyAttributeCollected({ + * attribute: { + * id: "id", + * value: "value" + * }, + * event_id: "event_id", + * external_conversation_id: "external_conversation_id", + * contact: { + * type: "user", + * external_id: "external_id" + * } + * }) + */ + public notifyAttributeCollected( + request: Intercom.NotifyAttributeCollectedRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__notifyAttributeCollected(request, requestOptions)); + } + + private async __notifyAttributeCollected( + request: Intercom.NotifyAttributeCollectedRequest, + requestOptions?: CustomChannelEventsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "custom_channel_events/notify_attribute_collected", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomChannelNotificationResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + case 422: + throw new Intercom.UnprocessableEntityError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_attribute_collected", + ); + } +} diff --git a/src/api/resources/customChannelEvents/client/index.ts b/src/api/resources/customChannelEvents/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/customChannelEvents/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts b/src/api/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts new file mode 100644 index 00000000..a4a040d9 --- /dev/null +++ b/src/api/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts @@ -0,0 +1,22 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; + +/** + * @example + * { + * attribute: { + * id: "id", + * value: "value" + * }, + * event_id: "event_id", + * external_conversation_id: "external_conversation_id", + * contact: { + * type: "user", + * external_id: "external_id" + * } + * } + */ +export interface NotifyAttributeCollectedRequest extends Intercom.CustomChannelBaseEvent { + attribute: Intercom.CustomChannelAttribute; +} diff --git a/src/api/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts b/src/api/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts new file mode 100644 index 00000000..7f6483df --- /dev/null +++ b/src/api/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts @@ -0,0 +1,20 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; + +/** + * @example + * { + * body: "body", + * event_id: "event_id", + * external_conversation_id: "external_conversation_id", + * contact: { + * type: "user", + * external_id: "external_id" + * } + * } + */ +export interface NotifyNewMessageRequest extends Intercom.CustomChannelBaseEvent { + /** The message content sent by the user. */ + body: string; +} diff --git a/src/api/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts b/src/api/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts new file mode 100644 index 00000000..e6cec3d9 --- /dev/null +++ b/src/api/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts @@ -0,0 +1,22 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; + +/** + * @example + * { + * event_id: "evt_67890", + * external_conversation_id: "conv_13579", + * contact: { + * type: "user", + * external_id: "user_003", + * name: "Alice Example", + * email: "alice@example.com" + * }, + * quick_reply_option_id: "1234" + * } + */ +export interface NotifyQuickReplySelectedRequest extends Intercom.CustomChannelBaseEvent { + /** Id of the selected quick reply option. */ + quick_reply_option_id: string; +} diff --git a/src/api/resources/customChannelEvents/client/requests/index.ts b/src/api/resources/customChannelEvents/client/requests/index.ts new file mode 100644 index 00000000..702922d9 --- /dev/null +++ b/src/api/resources/customChannelEvents/client/requests/index.ts @@ -0,0 +1,3 @@ +export type { NotifyAttributeCollectedRequest } from "./NotifyAttributeCollectedRequest.js"; +export type { NotifyNewMessageRequest } from "./NotifyNewMessageRequest.js"; +export type { NotifyQuickReplySelectedRequest } from "./NotifyQuickReplySelectedRequest.js"; diff --git a/src/api/resources/customChannelEvents/index.ts b/src/api/resources/customChannelEvents/index.ts new file mode 100644 index 00000000..914b8c3c --- /dev/null +++ b/src/api/resources/customChannelEvents/index.ts @@ -0,0 +1 @@ +export * from "./client/index.js"; diff --git a/src/api/resources/customObjectInstances/client/Client.ts b/src/api/resources/customObjectInstances/client/Client.ts new file mode 100644 index 00000000..0ae03367 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/Client.ts @@ -0,0 +1,462 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace CustomObjectInstancesClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Custom Object instances. + * {% admonition type="warning" name="Permission Requirements" %} + * From now on, to access this endpoint, you need additional permissions. Please head over to the [Developer Hub](https://app.intercom.com/a/apps/_/developer-hub) app package authentication settings to configure the required permissions. + * {% /admonition %} + */ +export class CustomObjectInstancesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CustomObjectInstancesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Fetch a Custom Object Instance by external_id. + * + * @param {Intercom.GetCustomObjectInstancesByExternalIdRequest} request + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.customObjectInstances.getCustomObjectInstancesByExternalId({ + * custom_object_type_identifier: "Order", + * external_id: "external_id" + * }) + */ + public getCustomObjectInstancesByExternalId( + request: Intercom.GetCustomObjectInstancesByExternalIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise( + this.__getCustomObjectInstancesByExternalId(request, requestOptions), + ); + } + + private async __getCustomObjectInstancesByExternalId( + request: Intercom.GetCustomObjectInstancesByExternalIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): Promise> { + const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request; + const _queryParams: Record = {}; + _queryParams.external_id = externalId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomObjectInstance | undefined, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/custom_object_instances/{custom_object_type_identifier}", + ); + } + + /** + * Create or update a custom object instance + * + * @param {Intercom.CreateOrUpdateCustomObjectInstanceRequest} request + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.customObjectInstances.createCustomObjectInstances({ + * custom_object_type_identifier: "Order", + * external_id: "123", + * external_created_at: 1392036272, + * external_updated_at: 1392036272, + * custom_attributes: { + * "order_number": "ORDER-12345", + * "total_amount": "custom_attributes" + * } + * }) + */ + public createCustomObjectInstances( + request: Intercom.CreateOrUpdateCustomObjectInstanceRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createCustomObjectInstances(request, requestOptions)); + } + + private async __createCustomObjectInstances( + request: Intercom.CreateOrUpdateCustomObjectInstanceRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): Promise> { + const { custom_object_type_identifier: customObjectTypeIdentifier, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: _body, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomObjectInstance | undefined, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_object_instances/{custom_object_type_identifier}", + ); + } + + /** + * Delete a single Custom Object instance by external_id. + * + * @param {Intercom.DeleteCustomObjectInstancesByIdRequest} request + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.customObjectInstances.deleteCustomObjectInstancesById({ + * custom_object_type_identifier: "Order", + * external_id: "external_id" + * }) + */ + public deleteCustomObjectInstancesById( + request: Intercom.DeleteCustomObjectInstancesByIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteCustomObjectInstancesById(request, requestOptions)); + } + + private async __deleteCustomObjectInstancesById( + request: Intercom.DeleteCustomObjectInstancesByIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): Promise> { + const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request; + const _queryParams: Record = {}; + _queryParams.external_id = externalId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.CustomObjectInstanceDeleted, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/custom_object_instances/{custom_object_type_identifier}", + ); + } + + /** + * Fetch a Custom Object Instance by id. + * + * @param {Intercom.GetCustomObjectInstancesByIdRequest} request + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.customObjectInstances.getCustomObjectInstancesById({ + * custom_object_type_identifier: "Order", + * custom_object_instance_id: "custom_object_instance_id" + * }) + */ + public getCustomObjectInstancesById( + request: Intercom.GetCustomObjectInstancesByIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getCustomObjectInstancesById(request, requestOptions)); + } + + private async __getCustomObjectInstancesById( + request: Intercom.GetCustomObjectInstancesByIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): Promise> { + const { + custom_object_type_identifier: customObjectTypeIdentifier, + custom_object_instance_id: customObjectInstanceId, + } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(customObjectInstanceId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.CustomObjectInstance | undefined, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/custom_object_instances/{custom_object_type_identifier}/{custom_object_instance_id}", + ); + } + + /** + * Delete a single Custom Object instance using the Intercom defined id. + * + * @param {Intercom.DeleteCustomObjectInstancesByExternalIdRequest} request + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + * custom_object_type_identifier: "Order", + * custom_object_instance_id: "custom_object_instance_id" + * }) + */ + public deleteCustomObjectInstancesByExternalId( + request: Intercom.DeleteCustomObjectInstancesByExternalIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise( + this.__deleteCustomObjectInstancesByExternalId(request, requestOptions), + ); + } + + private async __deleteCustomObjectInstancesByExternalId( + request: Intercom.DeleteCustomObjectInstancesByExternalIdRequest, + requestOptions?: CustomObjectInstancesClient.RequestOptions, + ): Promise> { + const { + custom_object_type_identifier: customObjectTypeIdentifier, + custom_object_instance_id: customObjectInstanceId, + } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(customObjectInstanceId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.CustomObjectInstanceDeleted, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/custom_object_instances/{custom_object_type_identifier}/{custom_object_instance_id}", + ); + } +} diff --git a/src/api/resources/customObjectInstances/client/index.ts b/src/api/resources/customObjectInstances/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts b/src/api/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts new file mode 100644 index 00000000..97fa7ad7 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts @@ -0,0 +1,27 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * custom_object_type_identifier: "Order", + * external_id: "123", + * external_created_at: 1392036272, + * external_updated_at: 1392036272, + * custom_attributes: { + * "order_number": "ORDER-12345", + * "total_amount": "custom_attributes" + * } + * } + */ +export interface CreateOrUpdateCustomObjectInstanceRequest { + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ + custom_object_type_identifier: string; + /** A unique identifier for the Custom Object instance in the external system it originated from. */ + external_id?: string; + /** The time when the Custom Object instance was created in the external system it originated from. */ + external_created_at?: number; + /** The time when the Custom Object instance was last updated in the external system it originated from. */ + external_updated_at?: number; + /** The custom attributes which are set for the Custom Object instance. */ + custom_attributes?: Record; +} diff --git a/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts b/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts new file mode 100644 index 00000000..16385f5b --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * custom_object_type_identifier: "Order", + * custom_object_instance_id: "custom_object_instance_id" + * } + */ +export interface DeleteCustomObjectInstancesByExternalIdRequest { + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ + custom_object_type_identifier: string; + /** The Intercom defined id of the custom object instance */ + custom_object_instance_id: string; +} diff --git a/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts b/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts new file mode 100644 index 00000000..d97bc1ce --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts @@ -0,0 +1,14 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * custom_object_type_identifier: "Order", + * external_id: "external_id" + * } + */ +export interface DeleteCustomObjectInstancesByIdRequest { + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ + custom_object_type_identifier: string; + external_id: string; +} diff --git a/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts b/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts new file mode 100644 index 00000000..2d9d0fe3 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts @@ -0,0 +1,14 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * custom_object_type_identifier: "Order", + * external_id: "external_id" + * } + */ +export interface GetCustomObjectInstancesByExternalIdRequest { + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ + custom_object_type_identifier: string; + external_id: string; +} diff --git a/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts b/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts new file mode 100644 index 00000000..962a1337 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * custom_object_type_identifier: "Order", + * custom_object_instance_id: "custom_object_instance_id" + * } + */ +export interface GetCustomObjectInstancesByIdRequest { + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ + custom_object_type_identifier: string; + /** The id or external_id of the custom object instance */ + custom_object_instance_id: string; +} diff --git a/src/api/resources/customObjectInstances/client/requests/index.ts b/src/api/resources/customObjectInstances/client/requests/index.ts new file mode 100644 index 00000000..07816781 --- /dev/null +++ b/src/api/resources/customObjectInstances/client/requests/index.ts @@ -0,0 +1,5 @@ +export type { CreateOrUpdateCustomObjectInstanceRequest } from "./CreateOrUpdateCustomObjectInstanceRequest.js"; +export type { DeleteCustomObjectInstancesByExternalIdRequest } from "./DeleteCustomObjectInstancesByExternalIdRequest.js"; +export type { DeleteCustomObjectInstancesByIdRequest } from "./DeleteCustomObjectInstancesByIdRequest.js"; +export type { GetCustomObjectInstancesByExternalIdRequest } from "./GetCustomObjectInstancesByExternalIdRequest.js"; +export type { GetCustomObjectInstancesByIdRequest } from "./GetCustomObjectInstancesByIdRequest.js"; diff --git a/src/api/resources/customObjectInstances/index.ts b/src/api/resources/customObjectInstances/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/customObjectInstances/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/customObjectInstances/types/CustomObjectInstance.ts b/src/api/resources/customObjectInstances/types/CustomObjectInstance.ts new file mode 100644 index 00000000..a4363acf --- /dev/null +++ b/src/api/resources/customObjectInstances/types/CustomObjectInstance.ts @@ -0,0 +1,23 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * A Custom Object Instance represents an instance of a custom object type. This allows you to create and set custom attributes to store data about your customers that is not already captured by Intercom. The parent object includes recommended default attributes and you can add your own custom attributes. + */ +export interface CustomObjectInstance { + /** The Intercom defined id representing the custom object instance. */ + id?: string; + /** The id you have defined for the custom object instance. */ + external_id?: string; + /** The time when the Custom Object instance was created in the external system it originated from. */ + external_created_at?: number; + /** The time when the Custom Object instance was last updated in the external system it originated from. */ + external_updated_at?: number; + /** The time the attribute was created as a UTC Unix timestamp */ + created_at?: number; + /** The time the attribute was last updated as a UTC Unix timestamp */ + updated_at?: number; + /** The identifier of the custom object type that defines the structure of the custom object instance. */ + type?: string; + /** The custom attributes you have set on the custom object instance. */ + custom_attributes?: Record; +} diff --git a/src/api/resources/customObjectInstances/types/index.ts b/src/api/resources/customObjectInstances/types/index.ts new file mode 100644 index 00000000..861f9ce5 --- /dev/null +++ b/src/api/resources/customObjectInstances/types/index.ts @@ -0,0 +1 @@ +export * from "./CustomObjectInstance.js"; diff --git a/src/api/resources/dataAttributes/client/Client.ts b/src/api/resources/dataAttributes/client/Client.ts index cd6b4d7e..acff8f55 100644 --- a/src/api/resources/dataAttributes/client/Client.ts +++ b/src/api/resources/dataAttributes/client/Client.ts @@ -1,137 +1,87 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace DataAttributes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace DataAttributesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Data Attributes */ -export class DataAttributes { - constructor(protected readonly _options: DataAttributes.Options = {}) {} +export class DataAttributesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: DataAttributesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. * * @param {Intercom.ListDataAttributesRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example - * await client.dataAttributes.list() + * await client.dataAttributes.list({ + * model: "contact", + * include_archived: true + * }) */ public list( request: Intercom.ListDataAttributesRequest = {}, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); } private async __list( request: Intercom.ListDataAttributesRequest = {}, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { const { model, include_archived: includeArchived } = request; const _queryParams: Record = {}; if (model != null) { - _queryParams["model"] = model; + _queryParams.model = model; } if (includeArchived != null) { - _queryParams["include_archived"] = includeArchived.toString(); + _queryParams.include_archived = includeArchived.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "data_attributes", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataAttributeList, rawResponse: _response.rawResponse }; @@ -153,112 +103,71 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /data_attributes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/data_attributes"); } /** * You can create a data attributes for a `contact` or a `company`. * * @param {Intercom.CreateDataAttributeRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} * * @example * await client.dataAttributes.create({ - * name: "Mithril Shirt", - * model: "company", * data_type: "string" * }) * * @example * await client.dataAttributes.create({ - * name: "The One Ring", - * model: "contact", * data_type: "integer" * }) * * @example * await client.dataAttributes.create({ - * name: "!nv@l!d n@me", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.dataAttributes.create({ - * name: "The One Ring", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.dataAttributes.create({ - * name: "The Second Ring", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.dataAttributes.create({ - * name: "My Data Attribute", - * model: "contact", - * data_type: "string", - * description: "Just a plain old ring", - * options: ["options"] + * options: [{ + * value: "1-10" + * }] * }) */ public create( request: Intercom.CreateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "data_attributes", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataAttribute, rawResponse: _response.rawResponse }; @@ -282,21 +191,7 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /data_attributes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/data_attributes"); } /** @@ -308,7 +203,7 @@ export class DataAttributes { * > It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead. * * @param {Intercom.UpdateDataAttributeRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -317,72 +212,74 @@ export class DataAttributes { * * @example * await client.dataAttributes.update({ - * data_attribute_id: "1", - * archived: false, - * description: "Just a plain old ring", - * options: [{ - * value: "1-10" - * }, { - * value: "11-20" - * }] + * data_attribute_id: 1, + * body: { + * options: [{ + * value: "1-10" + * }, { + * value: "11-20" + * }] + * } * }) * * @example * await client.dataAttributes.update({ - * data_attribute_id: "1", - * archived: false, - * description: "Too few options", - * options: [{ - * value: "value" - * }, { - * value: "value" - * }] + * data_attribute_id: 1, + * body: { + * options: [{ + * value: "1-10" + * }, { + * value: "11-50" + * }] + * } * }) * * @example * await client.dataAttributes.update({ - * data_attribute_id: "1", - * archived: true, - * description: "Trying to archieve" + * data_attribute_id: 1, + * body: { + * "description": "Trying to archieve", + * "archived": true + * } * }) */ public update( request: Intercom.UpdateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { - const { data_attribute_id: dataAttributeId, ..._body } = request; + const { data_attribute_id: dataAttributeId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `data_attributes/${encodeURIComponent(dataAttributeId)}`, + `data_attributes/${core.url.encodePathParam(dataAttributeId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataAttribute, rawResponse: _response.rawResponse }; @@ -410,34 +307,11 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /data_attributes/{data_attribute_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/data_attributes/{data_attribute_id}", + ); } } diff --git a/src/api/resources/dataAttributes/client/index.ts b/src/api/resources/dataAttributes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/dataAttributes/client/index.ts +++ b/src/api/resources/dataAttributes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts b/src/api/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts deleted file mode 100644 index d0856471..00000000 --- a/src/api/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * @example - * { - * name: "Mithril Shirt", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The One Ring", - * model: "contact", - * data_type: "integer" - * } - * - * @example - * { - * name: "!nv@l!d n@me", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The One Ring", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The Second Ring", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "My Data Attribute", - * model: "contact", - * data_type: "string", - * description: "Just a plain old ring", - * options: ["options"] - * } - */ -export interface CreateDataAttributeRequest { - /** The name of the data attribute. */ - name: string; - /** The model that the data attribute belongs to. */ - model: CreateDataAttributeRequest.Model; - /** The type of data stored for this attribute. */ - data_type: CreateDataAttributeRequest.DataType; - /** The readable description you see in the UI for the attribute. */ - description?: string; - /** To create list attributes. Provide a set of hashes with `value` as the key of the options you want to make. `data_type` must be `string`. */ - options?: string[]; - /** Can this attribute be updated by the Messenger */ - messenger_writable?: boolean; -} - -export namespace CreateDataAttributeRequest { - /** - * The model that the data attribute belongs to. - */ - export type Model = "contact" | "company"; - export const Model = { - Contact: "contact", - Company: "company", - } as const; - /** - * The type of data stored for this attribute. - */ - export type DataType = "string" | "integer" | "float" | "boolean" | "datetime" | "date"; - export const DataType = { - String: "string", - Integer: "integer", - Float: "float", - Boolean: "boolean", - Datetime: "datetime", - Date: "date", - } as const; -} diff --git a/src/api/resources/dataAttributes/client/requests/ListDataAttributesRequest.ts b/src/api/resources/dataAttributes/client/requests/ListDataAttributesRequest.ts index 5d9ee979..f90a07a7 100644 --- a/src/api/resources/dataAttributes/client/requests/ListDataAttributesRequest.ts +++ b/src/api/resources/dataAttributes/client/requests/ListDataAttributesRequest.ts @@ -1,20 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example - * {} + * { + * model: "contact", + * include_archived: true + * } */ export interface ListDataAttributesRequest { - /** - * Specify the data attribute model to return. - */ + /** Specify the data attribute model to return. */ model?: Intercom.DataAttributesListRequestModel; - /** - * Include archived attributes in the list. By default we return only non archived data attributes. - */ + /** Include archived attributes in the list. By default we return only non archived data attributes. */ include_archived?: boolean; } diff --git a/src/api/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts b/src/api/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts index 5ea8b95d..4b29b995 100644 --- a/src/api/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts +++ b/src/api/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts @@ -1,72 +1,55 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; /** * @example * { - * data_attribute_id: "1", - * archived: false, - * description: "Just a plain old ring", - * options: [{ - * value: "1-10" - * }, { - * value: "11-20" - * }] + * data_attribute_id: 1, + * body: { + * options: [{ + * value: "1-10" + * }, { + * value: "11-20" + * }] + * } * } * * @example * { - * data_attribute_id: "1", - * archived: false, - * description: "Too few options", - * options: [{ - * value: "value" - * }, { - * value: "value" - * }] + * data_attribute_id: 1, + * body: { + * options: [{ + * value: "1-10" + * }, { + * value: "11-50" + * }] + * } * } * * @example * { - * data_attribute_id: "1", - * archived: false, - * description: "Just a plain old ring", - * options: [{ - * value: "1-10" - * }, { - * value: "11-20" - * }] + * data_attribute_id: 1, + * body: { + * options: [{ + * value: "1-10" + * }, { + * value: "11-20" + * }] + * } * } * * @example * { - * data_attribute_id: "1", - * archived: true, - * description: "Trying to archieve" + * data_attribute_id: 1, + * body: { + * "description": "Trying to archieve", + * "archived": true + * } * } */ export interface UpdateDataAttributeRequest { - /** - * The data attribute id - */ - data_attribute_id: string; - /** Whether the attribute is to be archived or not. */ - archived?: boolean; - /** The readable description you see in the UI for the attribute. */ - description?: string; - /** To create list attributes. Provide a set of hashes with `value` as the key of the options you want to make. `data_type` must be `string`. */ - options?: UpdateDataAttributeRequest.Options.Item[]; - /** Can this attribute be updated by the Messenger */ - messenger_writable?: boolean; -} - -export namespace UpdateDataAttributeRequest { - export type Options = Options.Item[]; - - export namespace Options { - export interface Item { - value: string; - } - } + /** The data attribute id */ + data_attribute_id: number; + body: Intercom.UpdateDataAttributeRequestBody; } diff --git a/src/api/resources/dataAttributes/client/requests/index.ts b/src/api/resources/dataAttributes/client/requests/index.ts index 6a7a0de5..a1a5824f 100644 --- a/src/api/resources/dataAttributes/client/requests/index.ts +++ b/src/api/resources/dataAttributes/client/requests/index.ts @@ -1,3 +1,2 @@ -export { type ListDataAttributesRequest } from "./ListDataAttributesRequest"; -export { type CreateDataAttributeRequest } from "./CreateDataAttributeRequest"; -export { type UpdateDataAttributeRequest } from "./UpdateDataAttributeRequest"; +export type { ListDataAttributesRequest } from "./ListDataAttributesRequest.js"; +export type { UpdateDataAttributeRequest } from "./UpdateDataAttributeRequest.js"; diff --git a/src/api/resources/dataAttributes/index.ts b/src/api/resources/dataAttributes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/dataAttributes/index.ts +++ b/src/api/resources/dataAttributes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/dataAttributes/types/DataAttribute.ts b/src/api/resources/dataAttributes/types/DataAttribute.ts index 1ce04881..a2dbee88 100644 --- a/src/api/resources/dataAttributes/types/DataAttribute.ts +++ b/src/api/resources/dataAttributes/types/DataAttribute.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Data Attributes are metadata used to describe your contact, company and conversation models. These include standard and custom attributes. By using the data attributes endpoint, you can get the global list of attributes for your workspace, as well as create and archive custom attributes. @@ -19,7 +17,7 @@ export interface DataAttribute { /** Readable name of the attribute (i.e. name you see in the UI) */ label: string; /** Readable description of the attribute. */ - description: string; + description?: string; /** The data type of the attribute. */ data_type: DataAttribute.DataType; /** List of predefined options for attribute value. */ @@ -43,18 +41,13 @@ export interface DataAttribute { } export namespace DataAttribute { - /** - * Value is `contact` for user/lead attributes and `company` for company attributes. - */ - export type Model = "contact" | "company"; + /** Value is `contact` for user/lead attributes and `company` for company attributes. */ export const Model = { Contact: "contact", Company: "company", } as const; - /** - * The data type of the attribute. - */ - export type DataType = "string" | "integer" | "float" | "boolean" | "date"; + export type Model = (typeof Model)[keyof typeof Model]; + /** The data type of the attribute. */ export const DataType = { String: "string", Integer: "integer", @@ -62,4 +55,5 @@ export namespace DataAttribute { Boolean: "boolean", Date: "date", } as const; + export type DataType = (typeof DataType)[keyof typeof DataType]; } diff --git a/src/api/resources/dataAttributes/types/DataAttributesListRequestModel.ts b/src/api/resources/dataAttributes/types/DataAttributesListRequestModel.ts index 4c163f30..8c42df63 100644 --- a/src/api/resources/dataAttributes/types/DataAttributesListRequestModel.ts +++ b/src/api/resources/dataAttributes/types/DataAttributesListRequestModel.ts @@ -1,10 +1,9 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -export type DataAttributesListRequestModel = "contact" | "company" | "conversation"; export const DataAttributesListRequestModel = { Contact: "contact", Company: "company", Conversation: "conversation", } as const; +export type DataAttributesListRequestModel = + (typeof DataAttributesListRequestModel)[keyof typeof DataAttributesListRequestModel]; diff --git a/src/api/resources/dataAttributes/types/index.ts b/src/api/resources/dataAttributes/types/index.ts index 70dcfefc..cf0add2c 100644 --- a/src/api/resources/dataAttributes/types/index.ts +++ b/src/api/resources/dataAttributes/types/index.ts @@ -1,2 +1,2 @@ -export * from "./DataAttributesListRequestModel"; -export * from "./DataAttribute"; +export * from "./DataAttribute.js"; +export * from "./DataAttributesListRequestModel.js"; diff --git a/src/api/resources/dataEvents/index.ts b/src/api/resources/dataEvents/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/dataEvents/index.ts +++ b/src/api/resources/dataEvents/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/dataEvents/types/DataEvent.ts b/src/api/resources/dataEvents/types/DataEvent.ts index 124221eb..a88a24e6 100644 --- a/src/api/resources/dataEvents/types/DataEvent.ts +++ b/src/api/resources/dataEvents/types/DataEvent.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Data events are used to notify Intercom of changes to your data. diff --git a/src/api/resources/dataEvents/types/index.ts b/src/api/resources/dataEvents/types/index.ts index 9b28ca3c..0272b738 100644 --- a/src/api/resources/dataEvents/types/index.ts +++ b/src/api/resources/dataEvents/types/index.ts @@ -1 +1 @@ -export * from "./DataEvent"; +export * from "./DataEvent.js"; diff --git a/src/api/resources/dataExport/client/Client.ts b/src/api/resources/dataExport/client/Client.ts index 72d82c09..f9ea23e2 100644 --- a/src/api/resources/dataExport/client/Client.ts +++ b/src/api/resources/dataExport/client/Client.ts @@ -1,79 +1,191 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace DataExport { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace DataExportClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Data Exports */ -export class DataExport { - constructor(protected readonly _options: DataExport.Options = {}) {} +export class DataExportClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: DataExportClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * @param {Intercom.ExportReportingDataRequest} request + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.dataExport.exportReportingData({ + * job_identifier: "job_identifier", + * app_id: "app_id", + * client_id: "client_id" + * }) + */ + public exportReportingData( + request: Intercom.ExportReportingDataRequest, + requestOptions?: DataExportClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__exportReportingData(request, requestOptions)); + } + + private async __exportReportingData( + request: Intercom.ExportReportingDataRequest, + requestOptions?: DataExportClient.RequestOptions, + ): Promise> { + const { job_identifier: jobIdentifier, app_id: appId, client_id: clientId } = request; + const _queryParams: Record = {}; + _queryParams.app_id = appId; + _queryParams.client_id = clientId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `export/reporting_data/${core.url.encodePathParam(jobIdentifier)}`, + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.DataExportExportReportingDataResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/export/reporting_data/{job_identifier}", + ); + } + + /** + * Download the data from a completed reporting data export job. + * + * > Octet header required + * > + * > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint. + * + * @param {Intercom.DownloadReportingDataExportRequest} request + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.dataExport.downloadReportingDataExport({ + * job_identifier: "job_identifier", + * app_id: "app_id" + * }) + */ + public downloadReportingDataExport( + request: Intercom.DownloadReportingDataExportRequest, + requestOptions?: DataExportClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__downloadReportingDataExport(request, requestOptions)); + } + + private async __downloadReportingDataExport( + request: Intercom.DownloadReportingDataExportRequest, + requestOptions?: DataExportClient.RequestOptions, + ): Promise> { + const { job_identifier: jobIdentifier, app_id: appId } = request; + const _queryParams: Record = {}; + _queryParams.app_id = appId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ + Accept: "application/octet-stream", + "Intercom-Version": requestOptions?.version, + }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `download/reporting_data/${core.url.encodePathParam(jobIdentifier)}`, + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: undefined, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/download/reporting_data/{job_identifier}", + ); + } /** * To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. @@ -93,50 +205,50 @@ export class DataExport { * > Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99. * * @param {Intercom.CreateDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.dataExport.create({ - * created_at_after: 1719474967, - * created_at_before: 1719492967 + * created_at_after: 1734519776, + * created_at_before: 1734537776 * }) */ public create( request: Intercom.CreateDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "export/content/data", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse }; @@ -150,21 +262,7 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /export/content/data."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/export/content/data"); } /** @@ -175,7 +273,7 @@ export class DataExport { * > All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available. * * @param {Intercom.FindDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.dataExport.find({ @@ -184,40 +282,38 @@ export class DataExport { */ public find( request: Intercom.FindDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `export/content/data/${encodeURIComponent(jobIdentifier)}`, + `export/content/data/${core.url.encodePathParam(jobIdentifier)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse }; @@ -231,30 +327,19 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /export/content/data/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/export/content/data/{job_identifier}", + ); } /** * You can cancel your job * * @param {Intercom.CancelDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.dataExport.cancel({ @@ -263,40 +348,38 @@ export class DataExport { */ public cancel( request: Intercom.CancelDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); } private async __cancel( request: Intercom.CancelDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `export/cancel/${encodeURIComponent(jobIdentifier)}`, + `export/cancel/${core.url.encodePathParam(jobIdentifier)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataExport, rawResponse: _response.rawResponse }; @@ -310,23 +393,12 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /export/cancel/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/export/cancel/{job_identifier}", + ); } /** @@ -339,7 +411,7 @@ export class DataExport { * > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint. * * @param {Intercom.DownloadDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.dataExport.download({ @@ -348,40 +420,38 @@ export class DataExport { */ public download( request: Intercom.DownloadDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__download(request, requestOptions)); } private async __download( request: Intercom.DownloadDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `download/content/data/${encodeURIComponent(jobIdentifier)}`, + `download/content/data/${core.url.encodePathParam(jobIdentifier)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -395,34 +465,11 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /download/content/data/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/download/content/data/{job_identifier}", + ); } } diff --git a/src/api/resources/dataExport/client/index.ts b/src/api/resources/dataExport/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/dataExport/client/index.ts +++ b/src/api/resources/dataExport/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/dataExport/client/requests/CancelDataExportRequest.ts b/src/api/resources/dataExport/client/requests/CancelDataExportRequest.ts index 39ed6925..4e387ec1 100644 --- a/src/api/resources/dataExport/client/requests/CancelDataExportRequest.ts +++ b/src/api/resources/dataExport/client/requests/CancelDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface CancelDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/dataExport/client/requests/CreateDataExportRequest.ts b/src/api/resources/dataExport/client/requests/CreateDataExportRequest.ts index d8b4e380..b0bc000c 100644 --- a/src/api/resources/dataExport/client/requests/CreateDataExportRequest.ts +++ b/src/api/resources/dataExport/client/requests/CreateDataExportRequest.ts @@ -1,12 +1,10 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * created_at_after: 1719474967, - * created_at_before: 1719492967 + * created_at_after: 1734519776, + * created_at_before: 1734537776 * } */ export interface CreateDataExportRequest { diff --git a/src/api/resources/dataExport/client/requests/DownloadDataExportRequest.ts b/src/api/resources/dataExport/client/requests/DownloadDataExportRequest.ts index 4a7ee828..98aab0f3 100644 --- a/src/api/resources/dataExport/client/requests/DownloadDataExportRequest.ts +++ b/src/api/resources/dataExport/client/requests/DownloadDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DownloadDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/dataExport/client/requests/DownloadReportingDataExportRequest.ts b/src/api/resources/dataExport/client/requests/DownloadReportingDataExportRequest.ts new file mode 100644 index 00000000..92bec12f --- /dev/null +++ b/src/api/resources/dataExport/client/requests/DownloadReportingDataExportRequest.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * job_identifier: "job_identifier", + * app_id: "app_id" + * } + */ +export interface DownloadReportingDataExportRequest { + job_identifier: string; + app_id: string; +} diff --git a/src/api/resources/dataExport/client/requests/ExportReportingDataRequest.ts b/src/api/resources/dataExport/client/requests/ExportReportingDataRequest.ts new file mode 100644 index 00000000..15b8c300 --- /dev/null +++ b/src/api/resources/dataExport/client/requests/ExportReportingDataRequest.ts @@ -0,0 +1,24 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * job_identifier: "job_identifier", + * app_id: "app_id", + * client_id: "client_id" + * } + * + * @example + * { + * job_identifier: "job_identifier", + * app_id: "app_id", + * client_id: "client_id" + * } + */ +export interface ExportReportingDataRequest { + /** Unique identifier of the job. */ + job_identifier: string; + /** The Intercom defined code of the workspace the company is associated to. */ + app_id: string; + client_id: string; +} diff --git a/src/api/resources/dataExport/client/requests/FindDataExportRequest.ts b/src/api/resources/dataExport/client/requests/FindDataExportRequest.ts index fc5c67b4..cc335ddb 100644 --- a/src/api/resources/dataExport/client/requests/FindDataExportRequest.ts +++ b/src/api/resources/dataExport/client/requests/FindDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/dataExport/client/requests/index.ts b/src/api/resources/dataExport/client/requests/index.ts index fa7821f6..753260ad 100644 --- a/src/api/resources/dataExport/client/requests/index.ts +++ b/src/api/resources/dataExport/client/requests/index.ts @@ -1,4 +1,6 @@ -export { type CreateDataExportRequest } from "./CreateDataExportRequest"; -export { type FindDataExportRequest } from "./FindDataExportRequest"; -export { type CancelDataExportRequest } from "./CancelDataExportRequest"; -export { type DownloadDataExportRequest } from "./DownloadDataExportRequest"; +export type { CancelDataExportRequest } from "./CancelDataExportRequest.js"; +export type { CreateDataExportRequest } from "./CreateDataExportRequest.js"; +export type { DownloadDataExportRequest } from "./DownloadDataExportRequest.js"; +export type { DownloadReportingDataExportRequest } from "./DownloadReportingDataExportRequest.js"; +export type { ExportReportingDataRequest } from "./ExportReportingDataRequest.js"; +export type { FindDataExportRequest } from "./FindDataExportRequest.js"; diff --git a/src/api/resources/dataExport/index.ts b/src/api/resources/dataExport/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/dataExport/index.ts +++ b/src/api/resources/dataExport/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/dataExport/types/DataExport.ts b/src/api/resources/dataExport/types/DataExport.ts index fbb48fc4..002d8072 100644 --- a/src/api/resources/dataExport/types/DataExport.ts +++ b/src/api/resources/dataExport/types/DataExport.ts @@ -1,26 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The data export api is used to view all message sent & viewed in a given timeframe. */ export interface DataExport { /** The identifier for your job. */ - job_identifier: string; + job_identifier?: string; /** The current state of your job. */ - status: DataExport.Status; + status?: DataExport.Status; /** The time after which you will not be able to access the data. */ - download_expires_at: string; + download_expires_at?: string; /** The location where you can download your data. */ - download_url: string; + download_url?: string; } export namespace DataExport { - /** - * The current state of your job. - */ - export type Status = "pending" | "in_progress" | "failed" | "completed" | "no_data" | "canceled"; + /** The current state of your job. */ export const Status = { Pending: "pending", InProgress: "in_progress", @@ -29,4 +24,5 @@ export namespace DataExport { NoData: "no_data", Canceled: "canceled", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/dataExport/types/DataExportExportReportingDataResponse.ts b/src/api/resources/dataExport/types/DataExportExportReportingDataResponse.ts new file mode 100644 index 00000000..1eda3ab4 --- /dev/null +++ b/src/api/resources/dataExport/types/DataExportExportReportingDataResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface DataExportExportReportingDataResponse { + job_identifier?: string; + status?: string; + download_url?: string; + download_expires_at?: string; +} diff --git a/src/api/resources/dataExport/types/index.ts b/src/api/resources/dataExport/types/index.ts index 7cea751a..222f0cce 100644 --- a/src/api/resources/dataExport/types/index.ts +++ b/src/api/resources/dataExport/types/index.ts @@ -1 +1,2 @@ -export * from "./DataExport"; +export * from "./DataExport.js"; +export * from "./DataExportExportReportingDataResponse.js"; diff --git a/src/api/resources/events/client/Client.ts b/src/api/resources/events/client/Client.ts index a51cd863..2c645b76 100644 --- a/src/api/resources/events/client/Client.ts +++ b/src/api/resources/events/client/Client.ts @@ -1,76 +1,26 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Events { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace EventsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Events { - constructor(protected readonly _options: Events.Options = {}) {} +export class EventsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: EventsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * @@ -89,25 +39,30 @@ export class Events { * You can optionally define the result page size as well with the `per_page` parameter. * * @param {Intercom.ListEventsRequest} request - * @param {Events.RequestOptions} requestOptions - Request-specific configuration. + * @param {EventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.events.list({ - * type: "type" + * user_id: "user_id", + * intercom_user_id: "intercom_user_id", + * email: "email", + * type: "type", + * summary: true, + * per_page: 1 * }) */ public list( request: Intercom.ListEventsRequest, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); } private async __list( request: Intercom.ListEventsRequest, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): Promise> { const { user_id: userId, @@ -119,51 +74,48 @@ export class Events { } = request; const _queryParams: Record = {}; if (userId != null) { - _queryParams["user_id"] = userId; + _queryParams.user_id = userId; } if (intercomUserId != null) { - _queryParams["intercom_user_id"] = intercomUserId; + _queryParams.intercom_user_id = intercomUserId; } if (email != null) { - _queryParams["email"] = email; + _queryParams.email = email; } - _queryParams["type"] = type_; + _queryParams.type = type_; if (summary != null) { - _queryParams["summary"] = summary.toString(); + _queryParams.summary = summary.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DataEventSummary, rawResponse: _response.rawResponse }; @@ -185,21 +137,7 @@ export class Events { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /events."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/events"); } /** @@ -245,8 +183,9 @@ export class Events { * - Event lists containing duplicate events will have those duplicates ignored. * - Server errors will return a `500` response code and may contain an error message in the body. * + * * @param {Intercom.CreateDataEventRequest} request - * @param {Events.RequestOptions} requestOptions - Request-specific configuration. + * @param {EventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -259,40 +198,40 @@ export class Events { */ public create( request: Intercom.CreateDataEventRequest, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateDataEventRequest, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -314,28 +253,15 @@ export class Events { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /events."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/events"); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. * + * * @param {Intercom.ListEventSummariesRequest} request - * @param {Events.RequestOptions} requestOptions - Request-specific configuration. + * @param {EventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -344,40 +270,40 @@ export class Events { */ public summaries( request: Intercom.ListEventSummariesRequest = {}, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__summaries(request, requestOptions)); } private async __summaries( request: Intercom.ListEventSummariesRequest = {}, - requestOptions?: Events.RequestOptions, + requestOptions?: EventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events/summaries", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -399,32 +325,6 @@ export class Events { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /events/summaries."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/events/summaries"); } } diff --git a/src/api/resources/events/client/index.ts b/src/api/resources/events/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/events/client/index.ts +++ b/src/api/resources/events/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/events/client/requests/ListEventSummariesRequest.ts b/src/api/resources/events/client/requests/ListEventSummariesRequest.ts index b1f4c485..6c0d7bca 100644 --- a/src/api/resources/events/client/requests/ListEventSummariesRequest.ts +++ b/src/api/resources/events/client/requests/ListEventSummariesRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/events/client/requests/ListEventsRequest.ts b/src/api/resources/events/client/requests/ListEventsRequest.ts index c77ac53b..6617f912 100644 --- a/src/api/resources/events/client/requests/ListEventsRequest.ts +++ b/src/api/resources/events/client/requests/ListEventsRequest.ts @@ -1,36 +1,27 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * type: "type" + * user_id: "user_id", + * intercom_user_id: "intercom_user_id", + * email: "email", + * type: "type", + * summary: true, + * per_page: 1 * } */ export interface ListEventsRequest { - /** - * user_id query parameter - */ + /** user_id query parameter */ user_id?: string; - /** - * intercom_user_id query parameter - */ + /** intercom_user_id query parameter */ intercom_user_id?: string; - /** - * email query parameter - */ + /** email query parameter */ email?: string; - /** - * The value must be user - */ + /** The value must be user */ type: string; - /** - * summary flag - */ + /** summary flag */ summary?: boolean; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/events/client/requests/index.ts b/src/api/resources/events/client/requests/index.ts index 25f04352..584ea81e 100644 --- a/src/api/resources/events/client/requests/index.ts +++ b/src/api/resources/events/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type ListEventsRequest } from "./ListEventsRequest"; -export { type ListEventSummariesRequest } from "./ListEventSummariesRequest"; +export type { ListEventSummariesRequest } from "./ListEventSummariesRequest.js"; +export type { ListEventsRequest } from "./ListEventsRequest.js"; diff --git a/src/api/resources/events/index.ts b/src/api/resources/events/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/events/index.ts +++ b/src/api/resources/events/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/export/client/Client.ts b/src/api/resources/export/client/Client.ts new file mode 100644 index 00000000..521fe210 --- /dev/null +++ b/src/api/resources/export/client/Client.ts @@ -0,0 +1,176 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace ExportClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +export class ExportClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ExportClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * @param {Intercom.PostExportReportingDataEnqueueRequest} request + * @param {ExportClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.TooManyRequestsError} + * + * @example + * await client.export.enqueueANewReportingDataExportJob({ + * dataset_id: "conversation", + * attribute_ids: ["conversation_id", "conversation_started_at"], + * start_time: 1717490000, + * end_time: 1717510000 + * }) + */ + public enqueueANewReportingDataExportJob( + request: Intercom.PostExportReportingDataEnqueueRequest, + requestOptions?: ExportClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__enqueueANewReportingDataExportJob(request, requestOptions)); + } + + private async __enqueueANewReportingDataExportJob( + request: Intercom.PostExportReportingDataEnqueueRequest, + requestOptions?: ExportClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "export/reporting_data/enqueue", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.PostExportReportingDataEnqueueResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 429: + throw new Intercom.TooManyRequestsError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/export/reporting_data/enqueue", + ); + } + + /** + * @param {ExportClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @example + * await client.export.listAvailableDatasetsAndAttributes() + */ + public listAvailableDatasetsAndAttributes( + requestOptions?: ExportClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listAvailableDatasetsAndAttributes(requestOptions)); + } + + private async __listAvailableDatasetsAndAttributes( + requestOptions?: ExportClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "export/reporting_data/get_datasets", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.GetExportReportingDataGetDatasetsResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/export/reporting_data/get_datasets", + ); + } +} diff --git a/src/api/resources/export/client/index.ts b/src/api/resources/export/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/export/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts b/src/api/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts new file mode 100644 index 00000000..57767a44 --- /dev/null +++ b/src/api/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * dataset_id: "conversation", + * attribute_ids: ["conversation_id", "conversation_started_at"], + * start_time: 1717490000, + * end_time: 1717510000 + * } + */ +export interface PostExportReportingDataEnqueueRequest { + dataset_id: string; + attribute_ids: string[]; + start_time: number; + end_time: number; +} diff --git a/src/api/resources/export/client/requests/index.ts b/src/api/resources/export/client/requests/index.ts new file mode 100644 index 00000000..a18772b7 --- /dev/null +++ b/src/api/resources/export/client/requests/index.ts @@ -0,0 +1 @@ +export type { PostExportReportingDataEnqueueRequest } from "./PostExportReportingDataEnqueueRequest.js"; diff --git a/src/api/resources/export/index.ts b/src/api/resources/export/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/export/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts b/src/api/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts new file mode 100644 index 00000000..725ac29a --- /dev/null +++ b/src/api/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts @@ -0,0 +1,31 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface GetExportReportingDataGetDatasetsResponse { + type?: string; + data?: GetExportReportingDataGetDatasetsResponse.Data.Item[]; +} + +export namespace GetExportReportingDataGetDatasetsResponse { + export type Data = Data.Item[]; + + export namespace Data { + export interface Item { + id?: string; + name?: string; + description?: string; + default_time_attribute_id?: string; + attributes?: Item.Attributes.Item[]; + } + + export namespace Item { + export type Attributes = Attributes.Item[]; + + export namespace Attributes { + export interface Item { + id?: string; + name?: string; + } + } + } + } +} diff --git a/src/api/resources/export/types/PostExportReportingDataEnqueueResponse.ts b/src/api/resources/export/types/PostExportReportingDataEnqueueResponse.ts new file mode 100644 index 00000000..c15d988e --- /dev/null +++ b/src/api/resources/export/types/PostExportReportingDataEnqueueResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface PostExportReportingDataEnqueueResponse { + job_identifier?: string; + status?: string; + download_url?: string; + download_expires_at?: string; +} diff --git a/src/api/resources/export/types/index.ts b/src/api/resources/export/types/index.ts new file mode 100644 index 00000000..27e82ed3 --- /dev/null +++ b/src/api/resources/export/types/index.ts @@ -0,0 +1,2 @@ +export * from "./GetExportReportingDataGetDatasetsResponse.js"; +export * from "./PostExportReportingDataEnqueueResponse.js"; diff --git a/src/api/resources/helpCenter/index.ts b/src/api/resources/helpCenter/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/helpCenter/index.ts +++ b/src/api/resources/helpCenter/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/helpCenter/types/Collection.ts b/src/api/resources/helpCenter/types/Collection.ts index 5394f881..7c9a53b2 100644 --- a/src/api/resources/helpCenter/types/Collection.ts +++ b/src/api/resources/helpCenter/types/Collection.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Collections are top level containers for Articles within the Help Center. @@ -27,7 +25,7 @@ export interface Collection { /** The order of the section in relation to others sections within a collection. Values go from `0` upwards. `0` is the default if there's no order. */ order: number; /** The default locale of the help center. This field is only returned for multilingual help centers. */ - default_locale: string; + default_locale?: string; translated_content?: Intercom.GroupTranslatedContent; /** The id of the parent collection. If `null` then it is the first level collection. */ parent_id?: string; diff --git a/src/api/resources/helpCenter/types/HelpCenter.ts b/src/api/resources/helpCenter/types/HelpCenter.ts index acf3993d..3715e87f 100644 --- a/src/api/resources/helpCenter/types/HelpCenter.ts +++ b/src/api/resources/helpCenter/types/HelpCenter.ts @@ -1,23 +1,25 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Help Centers contain collections */ export interface HelpCenter { /** The unique identifier for the Help Center which is given by Intercom. */ - id: string; + id?: string; /** The id of the workspace which the Help Center belongs to. */ - workspace_id: string; + workspace_id?: string; /** The time when the Help Center was created. */ - created_at: number; + created_at?: number; /** The time when the Help Center was last updated. */ updated_at?: number; /** The identifier of the Help Center. This is used in the URL of the Help Center. */ - identifier: string; + identifier?: string; /** Whether the Help Center is turned on or not. This is controlled in your Help Center settings. */ - website_turned_on: boolean; + website_turned_on?: boolean; /** The display name of the Help Center only seen by teammates. */ - display_name: string; + display_name?: string; + /** The URL for the help center, if you have a custom domain then this will show the URL using the custom domain. */ + url?: string; + /** Custom domain configured for the help center */ + custom_domain?: string; } diff --git a/src/api/resources/helpCenter/types/HelpCenterList.ts b/src/api/resources/helpCenter/types/HelpCenterList.ts index f2d362f7..e034eaff 100644 --- a/src/api/resources/helpCenter/types/HelpCenterList.ts +++ b/src/api/resources/helpCenter/types/HelpCenterList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Help Centers belonging to the App */ export interface HelpCenterList { /** The type of the object - `list`. */ - type: "list"; + type?: "list"; /** An array of Help Center objects */ - data: Intercom.HelpCenter[]; + data?: Intercom.HelpCenter[]; } diff --git a/src/api/resources/helpCenter/types/index.ts b/src/api/resources/helpCenter/types/index.ts index 65d348a7..097e7b49 100644 --- a/src/api/resources/helpCenter/types/index.ts +++ b/src/api/resources/helpCenter/types/index.ts @@ -1,3 +1,3 @@ -export * from "./Collection"; -export * from "./HelpCenter"; -export * from "./HelpCenterList"; +export * from "./Collection.js"; +export * from "./HelpCenter.js"; +export * from "./HelpCenterList.js"; diff --git a/src/api/resources/helpCenters/client/Client.ts b/src/api/resources/helpCenters/client/Client.ts index f8a1cf28..5541fb5c 100644 --- a/src/api/resources/helpCenters/client/Client.ts +++ b/src/api/resources/helpCenters/client/Client.ts @@ -1,134 +1,81 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; -import { Collections } from "../resources/collections/client/Client"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; +import { CollectionsClient } from "../resources/collections/client/Client.js"; -export declare namespace HelpCenters { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace HelpCentersClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class HelpCenters { - protected _collections: Collections | undefined; +export class HelpCentersClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + protected _collections: CollectionsClient | undefined; - constructor(protected readonly _options: HelpCenters.Options = {}) {} + constructor(options: HelpCentersClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } - public get collections(): Collections { - return (this._collections ??= new Collections(this._options)); + public get collections(): CollectionsClient { + return (this._collections ??= new CollectionsClient(this._options)); } /** * You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`. * * @param {Intercom.FindHelpCenterRequest} request - * @param {HelpCenters.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCentersClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.helpCenters.find({ - * help_center_id: "123" + * help_center_id: 1 * }) */ public find( request: Intercom.FindHelpCenterRequest, - requestOptions?: HelpCenters.RequestOptions, + requestOptions?: HelpCentersClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindHelpCenterRequest, - requestOptions?: HelpCenters.RequestOptions, + requestOptions?: HelpCentersClient.RequestOptions, ): Promise> { const { help_center_id: helpCenterId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/help_centers/${encodeURIComponent(helpCenterId)}`, + `help_center/help_centers/${core.url.encodePathParam(helpCenterId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.HelpCenter, rawResponse: _response.rawResponse }; @@ -152,30 +99,19 @@ export class HelpCenters { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/help_centers/{help_center_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/help_center/help_centers/{help_center_id}", + ); } /** * You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`. * * @param {Intercom.ListHelpCentersRequest} request - * @param {HelpCenters.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCentersClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -184,8 +120,8 @@ export class HelpCenters { */ public async list( request: Intercom.ListHelpCentersRequest = {}, - requestOptions?: HelpCenters.RequestOptions, - ): Promise> { + requestOptions?: HelpCentersClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async ( request: Intercom.ListHelpCentersRequest, @@ -193,37 +129,33 @@ export class HelpCenters { const { page, per_page: perPage } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/help_centers", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.HelpCenterList, rawResponse: _response.rawResponse }; @@ -243,28 +175,17 @@ export class HelpCenters { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/help_centers.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/help_center/help_centers", + ); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.data ?? []).length > 0, @@ -275,16 +196,4 @@ export class HelpCenters { }, }); } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; - } } diff --git a/src/api/resources/helpCenters/client/index.ts b/src/api/resources/helpCenters/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/helpCenters/client/index.ts +++ b/src/api/resources/helpCenters/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/helpCenters/client/requests/FindHelpCenterRequest.ts b/src/api/resources/helpCenters/client/requests/FindHelpCenterRequest.ts index 2be74aba..f3efe0e4 100644 --- a/src/api/resources/helpCenters/client/requests/FindHelpCenterRequest.ts +++ b/src/api/resources/helpCenters/client/requests/FindHelpCenterRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * help_center_id: "123" + * help_center_id: 1 * } */ export interface FindHelpCenterRequest { - /** - * The unique identifier for the Help Center which is given by Intercom. - */ - help_center_id: string; + /** The unique identifier for the collection which is given by Intercom. */ + help_center_id: number; } diff --git a/src/api/resources/helpCenters/client/requests/ListHelpCentersRequest.ts b/src/api/resources/helpCenters/client/requests/ListHelpCentersRequest.ts index 952e8e50..88dbf4b2 100644 --- a/src/api/resources/helpCenters/client/requests/ListHelpCentersRequest.ts +++ b/src/api/resources/helpCenters/client/requests/ListHelpCentersRequest.ts @@ -1,18 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * {} */ export interface ListHelpCentersRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/helpCenters/client/requests/index.ts b/src/api/resources/helpCenters/client/requests/index.ts index 8cc9bf08..ea47193d 100644 --- a/src/api/resources/helpCenters/client/requests/index.ts +++ b/src/api/resources/helpCenters/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type FindHelpCenterRequest } from "./FindHelpCenterRequest"; -export { type ListHelpCentersRequest } from "./ListHelpCentersRequest"; +export type { FindHelpCenterRequest } from "./FindHelpCenterRequest.js"; +export type { ListHelpCentersRequest } from "./ListHelpCentersRequest.js"; diff --git a/src/api/resources/helpCenters/index.ts b/src/api/resources/helpCenters/index.ts index 33a87f10..9eb1192d 100644 --- a/src/api/resources/helpCenters/index.ts +++ b/src/api/resources/helpCenters/index.ts @@ -1,2 +1,2 @@ -export * from "./client"; -export * from "./resources"; +export * from "./client/index.js"; +export * from "./resources/index.js"; diff --git a/src/api/resources/helpCenters/resources/collections/client/Client.ts b/src/api/resources/helpCenters/resources/collections/client/Client.ts index b123a0c1..86958a90 100644 --- a/src/api/resources/helpCenters/resources/collections/client/Client.ts +++ b/src/api/resources/helpCenters/resources/collections/client/Client.ts @@ -1,76 +1,26 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Collections { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace CollectionsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Collections { - constructor(protected readonly _options: Collections.Options = {}) {} +export class CollectionsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CollectionsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. @@ -78,7 +28,7 @@ export class Collections { * Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first. * * @param {Intercom.helpCenters.ListCollectionsRequest} request - * @param {Collections.RequestOptions} requestOptions - Request-specific configuration. + * @param {CollectionsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -87,8 +37,8 @@ export class Collections { */ public async list( request: Intercom.helpCenters.ListCollectionsRequest = {}, - requestOptions?: Collections.RequestOptions, - ): Promise> { + requestOptions?: CollectionsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async ( request: Intercom.helpCenters.ListCollectionsRequest, @@ -96,37 +46,33 @@ export class Collections { const { page, per_page: perPage } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/collections", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.CollectionList, rawResponse: _response.rawResponse }; @@ -146,28 +92,17 @@ export class Collections { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/collections.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/help_center/collections", + ); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.data ?? []).length > 0, @@ -183,7 +118,7 @@ export class Collections { * You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.` * * @param {Intercom.helpCenters.CreateCollectionRequest} request - * @param {Collections.RequestOptions} requestOptions - Request-specific configuration. + * @param {CollectionsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -201,40 +136,40 @@ export class Collections { */ public create( request: Intercom.helpCenters.CreateCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.helpCenters.CreateCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/collections", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Collection, rawResponse: _response.rawResponse }; @@ -258,73 +193,57 @@ export class Collections { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /help_center/collections."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/help_center/collections"); } /** * You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`. * * @param {Intercom.helpCenters.FindCollectionRequest} request - * @param {Collections.RequestOptions} requestOptions - Request-specific configuration. + * @param {CollectionsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.helpCenters.collections.find({ - * collection_id: "123" + * collection_id: 1 * }) */ public find( request: Intercom.helpCenters.FindCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.helpCenters.FindCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): Promise> { const { collection_id: collectionId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(collectionId)}`, + `help_center/collections/${core.url.encodePathParam(collectionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Collection, rawResponse: _response.rawResponse }; @@ -348,77 +267,66 @@ export class Collections { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/collections/{collection_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/help_center/collections/{collection_id}", + ); } /** * You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`. * * @param {Intercom.helpCenters.UpdateCollectionRequest} request - * @param {Collections.RequestOptions} requestOptions - Request-specific configuration. + * @param {CollectionsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.helpCenters.collections.update({ - * collection_id: "123", + * collection_id: 1, * name: "Update collection name" * }) */ public update( request: Intercom.helpCenters.UpdateCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.helpCenters.UpdateCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): Promise> { const { collection_id: collectionId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(collectionId)}`, + `help_center/collections/${core.url.encodePathParam(collectionId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Collection, rawResponse: _response.rawResponse }; @@ -442,75 +350,62 @@ export class Collections { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /help_center/collections/{collection_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/help_center/collections/{collection_id}", + ); } /** * You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`. * * @param {Intercom.helpCenters.DeleteCollectionRequest} request - * @param {Collections.RequestOptions} requestOptions - Request-specific configuration. + * @param {CollectionsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.helpCenters.collections.delete({ - * collection_id: "123" + * collection_id: 1 * }) */ public delete( request: Intercom.helpCenters.DeleteCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.helpCenters.DeleteCollectionRequest, - requestOptions?: Collections.RequestOptions, + requestOptions?: CollectionsClient.RequestOptions, ): Promise> { const { collection_id: collectionId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(collectionId)}`, + `help_center/collections/${core.url.encodePathParam(collectionId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DeletedCollectionObject, rawResponse: _response.rawResponse }; @@ -534,34 +429,11 @@ export class Collections { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /help_center/collections/{collection_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/help_center/collections/{collection_id}", + ); } } diff --git a/src/api/resources/helpCenters/resources/collections/client/index.ts b/src/api/resources/helpCenters/resources/collections/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/helpCenters/resources/collections/client/index.ts +++ b/src/api/resources/helpCenters/resources/collections/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/CreateCollectionRequest.ts b/src/api/resources/helpCenters/resources/collections/client/requests/CreateCollectionRequest.ts index 3fe27292..045965d9 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/CreateCollectionRequest.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/CreateCollectionRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/DeleteCollectionRequest.ts b/src/api/resources/helpCenters/resources/collections/client/requests/DeleteCollectionRequest.ts index 8dbdb625..f97cdf86 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/DeleteCollectionRequest.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/DeleteCollectionRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * collection_id: "123" + * collection_id: 1 * } */ export interface DeleteCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ - collection_id: string; + /** The unique identifier for the collection which is given by Intercom. */ + collection_id: number; } diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/FindCollectionRequest.ts b/src/api/resources/helpCenters/resources/collections/client/requests/FindCollectionRequest.ts index 6c44a759..ddf2e39b 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/FindCollectionRequest.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/FindCollectionRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * collection_id: "123" + * collection_id: 1 * } */ export interface FindCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ - collection_id: string; + /** The unique identifier for the collection which is given by Intercom. */ + collection_id: number; } diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/ListCollectionsRequest.ts b/src/api/resources/helpCenters/resources/collections/client/requests/ListCollectionsRequest.ts index c8d346bd..2ebe21cd 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/ListCollectionsRequest.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/ListCollectionsRequest.ts @@ -1,18 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * {} */ export interface ListCollectionsRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/UpdateCollectionRequest.ts b/src/api/resources/helpCenters/resources/collections/client/requests/UpdateCollectionRequest.ts index 69bf333a..63cae012 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/UpdateCollectionRequest.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/UpdateCollectionRequest.ts @@ -1,27 +1,23 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example * { - * collection_id: "123", + * collection_id: 1, * name: "Update collection name" * } * * @example * { - * collection_id: "123", + * collection_id: 1, * name: "Update collection name" * } */ export interface UpdateCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ - collection_id: string; + /** The unique identifier for the collection which is given by Intercom. */ + collection_id: number; /** The name of the collection. For multilingual collections, this will be the name of the default language's content. */ name?: string; /** The description of the collection. For multilingual collections, this will be the description of the default language's content. */ diff --git a/src/api/resources/helpCenters/resources/collections/client/requests/index.ts b/src/api/resources/helpCenters/resources/collections/client/requests/index.ts index ed57ba6d..83e00901 100644 --- a/src/api/resources/helpCenters/resources/collections/client/requests/index.ts +++ b/src/api/resources/helpCenters/resources/collections/client/requests/index.ts @@ -1,5 +1,5 @@ -export { type ListCollectionsRequest } from "./ListCollectionsRequest"; -export { type CreateCollectionRequest } from "./CreateCollectionRequest"; -export { type FindCollectionRequest } from "./FindCollectionRequest"; -export { type UpdateCollectionRequest } from "./UpdateCollectionRequest"; -export { type DeleteCollectionRequest } from "./DeleteCollectionRequest"; +export type { CreateCollectionRequest } from "./CreateCollectionRequest.js"; +export type { DeleteCollectionRequest } from "./DeleteCollectionRequest.js"; +export type { FindCollectionRequest } from "./FindCollectionRequest.js"; +export type { ListCollectionsRequest } from "./ListCollectionsRequest.js"; +export type { UpdateCollectionRequest } from "./UpdateCollectionRequest.js"; diff --git a/src/api/resources/helpCenters/resources/collections/index.ts b/src/api/resources/helpCenters/resources/collections/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/helpCenters/resources/collections/index.ts +++ b/src/api/resources/helpCenters/resources/collections/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/helpCenters/resources/index.ts b/src/api/resources/helpCenters/resources/index.ts index d52abdea..a661f9d8 100644 --- a/src/api/resources/helpCenters/resources/index.ts +++ b/src/api/resources/helpCenters/resources/index.ts @@ -1,2 +1,2 @@ -export * as collections from "./collections"; -export * from "./collections/client/requests"; +export * from "./collections/client/requests/index.js"; +export * as collections from "./collections/index.js"; diff --git a/src/api/resources/index.ts b/src/api/resources/index.ts index 7761ecb9..80be8483 100644 --- a/src/api/resources/index.ts +++ b/src/api/resources/index.ts @@ -1,61 +1,82 @@ -export * as admins from "./admins"; -export * from "./admins/types"; -export * as articles from "./articles"; -export * from "./articles/types"; -export * as companies from "./companies"; -export * from "./companies/types"; -export * as contacts from "./contacts"; -export * from "./contacts/types"; -export * as notes from "./notes"; -export * from "./notes/types"; -export * as tags from "./tags"; -export * from "./tags/types"; -export * as conversations from "./conversations"; -export * from "./conversations/types"; -export * as dataAttributes from "./dataAttributes"; -export * from "./dataAttributes/types"; -export * as dataExport from "./dataExport"; -export * from "./dataExport/types"; -export * as messages from "./messages"; -export * from "./messages/types"; -export * as segments from "./segments"; -export * from "./segments/types"; -export * as subscriptionTypes from "./subscriptionTypes"; -export * from "./subscriptionTypes/types"; -export * as teams from "./teams"; -export * from "./teams/types"; -export * as tickets from "./tickets"; -export * from "./tickets/types"; -export * as aiAgent from "./aiAgent"; -export * from "./aiAgent/types"; -export * as helpCenter from "./helpCenter"; -export * from "./helpCenter/types"; -export * as aiContentSource from "./aiContentSource"; -export * from "./aiContentSource/types"; -export * as dataEvents from "./dataEvents"; -export * from "./dataEvents/types"; -export * as news from "./news"; -export * from "./news/types"; -export * as unstable from "./unstable"; -export * as helpCenters from "./helpCenters"; -export * as events from "./events"; -export * as phoneCallRedirects from "./phoneCallRedirects"; -export * as ticketTypes from "./ticketTypes"; -export * as visitors from "./visitors"; -export * from "./admins/client/requests"; -export * from "./articles/client/requests"; -export * from "./helpCenters/client/requests"; -export * from "./companies/client/requests"; -export * from "./contacts/client/requests"; -export * from "./notes/client/requests"; -export * from "./tags/client/requests"; -export * from "./conversations/client/requests"; -export * from "./dataAttributes/client/requests"; -export * from "./events/client/requests"; -export * from "./dataExport/client/requests"; -export * from "./segments/client/requests"; -export * from "./phoneCallRedirects/client/requests"; -export * from "./teams/client/requests"; -export * from "./ticketTypes/client/requests"; -export * from "./tickets/client/requests"; -export * from "./visitors/client/requests"; +export * from "./admins/client/requests/index.js"; +export * as admins from "./admins/index.js"; +export * from "./admins/types/index.js"; +export * as aiAgent from "./aiAgent/index.js"; +export * from "./aiAgent/types/index.js"; +export * from "./aiContent/client/requests/index.js"; +export * as aiContent from "./aiContent/index.js"; +export * from "./aiContent/types/index.js"; +export * as aiContentSource from "./aiContentSource/index.js"; +export * from "./aiContentSource/types/index.js"; +export * from "./articles/client/requests/index.js"; +export * as articles from "./articles/index.js"; +export * from "./articles/types/index.js"; +export * as awayStatusReasons from "./awayStatusReasons/index.js"; +export * from "./calls/client/requests/index.js"; +export * as calls from "./calls/index.js"; +export * from "./calls/types/index.js"; +export * from "./companies/client/requests/index.js"; +export * as companies from "./companies/index.js"; +export * from "./companies/types/index.js"; +export * from "./contacts/client/requests/index.js"; +export * as contacts from "./contacts/index.js"; +export * from "./contacts/types/index.js"; +export * from "./conversations/client/requests/index.js"; +export * as conversations from "./conversations/index.js"; +export * from "./conversations/types/index.js"; +export * from "./customChannelEvents/client/requests/index.js"; +export * as customChannelEvents from "./customChannelEvents/index.js"; +export * from "./customObjectInstances/client/requests/index.js"; +export * as customObjectInstances from "./customObjectInstances/index.js"; +export * from "./customObjectInstances/types/index.js"; +export * from "./dataAttributes/client/requests/index.js"; +export * as dataAttributes from "./dataAttributes/index.js"; +export * from "./dataAttributes/types/index.js"; +export * as dataEvents from "./dataEvents/index.js"; +export * from "./dataEvents/types/index.js"; +export * from "./dataExport/client/requests/index.js"; +export * as dataExport from "./dataExport/index.js"; +export * from "./dataExport/types/index.js"; +export * from "./events/client/requests/index.js"; +export * as events from "./events/index.js"; +export * from "./export/client/requests/index.js"; +export * as export_ from "./export/index.js"; +export * from "./export/types/index.js"; +export * as helpCenter from "./helpCenter/index.js"; +export * from "./helpCenter/types/index.js"; +export * from "./helpCenters/client/requests/index.js"; +export * as helpCenters from "./helpCenters/index.js"; +export * from "./internalArticles/client/requests/index.js"; +export * as internalArticles from "./internalArticles/index.js"; +export * from "./internalArticles/types/index.js"; +export * from "./jobs/client/requests/index.js"; +export * as jobs from "./jobs/index.js"; +export * from "./jobs/types/index.js"; +export * as messages from "./messages/index.js"; +export * from "./messages/types/index.js"; +export * as news from "./news/index.js"; +export * from "./news/types/index.js"; +export * from "./notes/client/requests/index.js"; +export * as notes from "./notes/index.js"; +export * from "./notes/types/index.js"; +export * as phoneCallRedirects from "./phoneCallRedirects/index.js"; +export * from "./segments/client/requests/index.js"; +export * as segments from "./segments/index.js"; +export * from "./segments/types/index.js"; +export * as subscriptionTypes from "./subscriptionTypes/index.js"; +export * from "./subscriptionTypes/types/index.js"; +export * from "./tags/client/requests/index.js"; +export * as tags from "./tags/index.js"; +export * from "./tags/types/index.js"; +export * from "./teams/client/requests/index.js"; +export * as teams from "./teams/index.js"; +export * from "./teams/types/index.js"; +export * as ticketStates from "./ticketStates/index.js"; +export * from "./tickets/client/requests/index.js"; +export * as tickets from "./tickets/index.js"; +export * from "./tickets/types/index.js"; +export * from "./ticketTypes/client/requests/index.js"; +export * as ticketTypes from "./ticketTypes/index.js"; +export * as unstable from "./unstable/index.js"; +export * from "./visitors/client/requests/index.js"; +export * as visitors from "./visitors/index.js"; diff --git a/src/api/resources/internalArticles/client/Client.ts b/src/api/resources/internalArticles/client/Client.ts new file mode 100644 index 00000000..4640a818 --- /dev/null +++ b/src/api/resources/internalArticles/client/Client.ts @@ -0,0 +1,503 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace InternalArticlesClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Internal Articles + */ +export class InternalArticlesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: InternalArticlesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can fetch a list of all internal articles by making a GET request to `https://api.intercom.io/internal_articles`. + * + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.internalArticles.listInternalArticles() + */ + public listInternalArticles( + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listInternalArticles(requestOptions)); + } + + private async __listInternalArticles( + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.InternalArticleList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/internal_articles"); + } + + /** + * You can create a new internal article by making a POST request to `https://api.intercom.io/internal_articles`. + * + * @param {Intercom.CreateInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.internalArticles.createInternalArticle({ + * title: "Thanks for everything", + * body: "Body of the Article", + * author_id: 991266252, + * owner_id: 991266252 + * }) + * + * @example + * await client.internalArticles.createInternalArticle({ + * title: "Thanks for everything", + * body: "Body of the Internal Article", + * author_id: 1295, + * owner_id: 1295 + * }) + */ + public createInternalArticle( + request?: Intercom.CreateInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createInternalArticle(request, requestOptions)); + } + + private async __createInternalArticle( + request?: Intercom.CreateInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/internal_articles"); + } + + /** + * You can fetch the details of a single internal article by making a GET request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.RetrieveInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.internalArticles.retrieveInternalArticle({ + * internal_article_id: 1 + * }) + */ + public retrieveInternalArticle( + request: Intercom.RetrieveInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveInternalArticle(request, requestOptions)); + } + + private async __retrieveInternalArticle( + request: Intercom.RetrieveInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { internal_article_id: internalArticleId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(internalArticleId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/internal_articles/{internal_article_id}", + ); + } + + /** + * You can update the details of a single internal article by making a PUT request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.UpdateInternalArticleRequestBody} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.internalArticles.updateInternalArticle({ + * internal_article_id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * }) + */ + public updateInternalArticle( + request: Intercom.UpdateInternalArticleRequestBody, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateInternalArticle(request, requestOptions)); + } + + private async __updateInternalArticle( + request: Intercom.UpdateInternalArticleRequestBody, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { internal_article_id: internalArticleId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(internalArticleId)}`, + ), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: _body, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/internal_articles/{internal_article_id}", + ); + } + + /** + * You can delete a single internal article by making a DELETE request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.DeleteInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.internalArticles.deleteInternalArticle({ + * internal_article_id: 1 + * }) + */ + public deleteInternalArticle( + request: Intercom.DeleteInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteInternalArticle(request, requestOptions)); + } + + private async __deleteInternalArticle( + request: Intercom.DeleteInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { internal_article_id: internalArticleId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(internalArticleId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.DeletedInternalArticleObject, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/internal_articles/{internal_article_id}", + ); + } + + /** + * You can search for internal articles by making a GET request to `https://api.intercom.io/internal_articles/search`. + * + * @param {Intercom.SearchInternalArticlesRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.internalArticles.searchInternalArticles({ + * folder_id: "folder_id" + * }) + */ + public searchInternalArticles( + request: Intercom.SearchInternalArticlesRequest = {}, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchInternalArticles(request, requestOptions)); + } + + private async __searchInternalArticles( + request: Intercom.SearchInternalArticlesRequest = {}, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { folder_id: folderId } = request; + const _queryParams: Record = {}; + if (folderId != null) { + _queryParams.folder_id = folderId; + } + + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles/search", + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.InternalArticleSearchResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/internal_articles/search"); + } +} diff --git a/src/api/resources/internalArticles/client/index.ts b/src/api/resources/internalArticles/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/internalArticles/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts b/src/api/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts new file mode 100644 index 00000000..6cd2773b --- /dev/null +++ b/src/api/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * internal_article_id: 1 + * } + */ +export interface DeleteInternalArticleRequest { + /** The unique identifier for the internal article which is given by Intercom. */ + internal_article_id: number; +} diff --git a/src/api/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts b/src/api/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts new file mode 100644 index 00000000..ca4bac12 --- /dev/null +++ b/src/api/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * internal_article_id: 1 + * } + */ +export interface RetrieveInternalArticleRequest { + /** The unique identifier for the article which is given by Intercom. */ + internal_article_id: number; +} diff --git a/src/api/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts b/src/api/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts new file mode 100644 index 00000000..6f80cf05 --- /dev/null +++ b/src/api/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * folder_id: "folder_id" + * } + */ +export interface SearchInternalArticlesRequest { + /** The ID of the folder to search in. */ + folder_id?: string; +} diff --git a/src/api/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts b/src/api/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts new file mode 100644 index 00000000..55416491 --- /dev/null +++ b/src/api/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts @@ -0,0 +1,29 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * internal_article_id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * } + * + * @example + * { + * internal_article_id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * } + */ +export interface UpdateInternalArticleRequestBody { + /** The unique identifier for the internal article which is given by Intercom. */ + internal_article_id: number; + /** The title of the article. */ + title?: string; + /** The content of the article. */ + body?: string; + /** The id of the author of the article. */ + author_id?: number; + /** The id of the author of the article. */ + owner_id?: number; +} diff --git a/src/api/resources/internalArticles/client/requests/index.ts b/src/api/resources/internalArticles/client/requests/index.ts new file mode 100644 index 00000000..677bd9fa --- /dev/null +++ b/src/api/resources/internalArticles/client/requests/index.ts @@ -0,0 +1,4 @@ +export type { DeleteInternalArticleRequest } from "./DeleteInternalArticleRequest.js"; +export type { RetrieveInternalArticleRequest } from "./RetrieveInternalArticleRequest.js"; +export type { SearchInternalArticlesRequest } from "./SearchInternalArticlesRequest.js"; +export type { UpdateInternalArticleRequestBody } from "./UpdateInternalArticleRequestBody.js"; diff --git a/src/api/resources/internalArticles/index.ts b/src/api/resources/internalArticles/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/internalArticles/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/internalArticles/types/InternalArticleListItem.ts b/src/api/resources/internalArticles/types/InternalArticleListItem.ts new file mode 100644 index 00000000..b906ff6f --- /dev/null +++ b/src/api/resources/internalArticles/types/InternalArticleListItem.ts @@ -0,0 +1,25 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * The data returned about your internal articles when you list them. + */ +export interface InternalArticleListItem { + /** The type of object - `internal_article`. */ + type?: "internal_article"; + /** The unique identifier for the article which is given by Intercom. */ + id?: string; + /** The title of the article. */ + title?: string; + /** The body of the article in HTML. */ + body?: string; + /** The id of the owner of the article. */ + owner_id?: number; + /** The id of the author of the article. */ + author_id?: number; + /** The time when the article was created. */ + created_at?: number; + /** The time when the article was last updated. */ + updated_at?: number; + /** The default locale of the article. */ + locale?: string; +} diff --git a/src/api/resources/internalArticles/types/InternalArticleSearchResponse.ts b/src/api/resources/internalArticles/types/InternalArticleSearchResponse.ts new file mode 100644 index 00000000..9718b94b --- /dev/null +++ b/src/api/resources/internalArticles/types/InternalArticleSearchResponse.ts @@ -0,0 +1,26 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * The results of an Internal Article search + */ +export interface InternalArticleSearchResponse { + /** The type of the object - `list`. */ + type?: "list"; + /** The total number of Internal Articles matching the search query */ + total_count?: number; + /** An object containing the results of the search. */ + data?: InternalArticleSearchResponse.Data; + pages?: Intercom.CursorPages; +} + +export namespace InternalArticleSearchResponse { + /** + * An object containing the results of the search. + */ + export interface Data { + /** An array of Internal Article objects */ + internal_articles?: Intercom.InternalArticle[]; + } +} diff --git a/src/api/resources/internalArticles/types/index.ts b/src/api/resources/internalArticles/types/index.ts new file mode 100644 index 00000000..aedeb96e --- /dev/null +++ b/src/api/resources/internalArticles/types/index.ts @@ -0,0 +1,2 @@ +export * from "./InternalArticleListItem.js"; +export * from "./InternalArticleSearchResponse.js"; diff --git a/src/api/resources/jobs/client/Client.ts b/src/api/resources/jobs/client/Client.ts new file mode 100644 index 00000000..80585eeb --- /dev/null +++ b/src/api/resources/jobs/client/Client.ts @@ -0,0 +1,101 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace JobsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about jobs + */ +export class JobsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: JobsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Retrieve the status of job execution. + * + * @param {Intercom.JobsStatusRequest} request + * @param {JobsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.jobs.status({ + * job_id: "job_id" + * }) + */ + public status( + request: Intercom.JobsStatusRequest, + requestOptions?: JobsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__status(request, requestOptions)); + } + + private async __status( + request: Intercom.JobsStatusRequest, + requestOptions?: JobsClient.RequestOptions, + ): Promise> { + const { job_id: jobId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `jobs/status/${core.url.encodePathParam(jobId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.Jobs, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/jobs/status/{job_id}"); + } +} diff --git a/src/api/resources/jobs/client/index.ts b/src/api/resources/jobs/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/jobs/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/jobs/client/requests/JobsStatusRequest.ts b/src/api/resources/jobs/client/requests/JobsStatusRequest.ts new file mode 100644 index 00000000..d5971376 --- /dev/null +++ b/src/api/resources/jobs/client/requests/JobsStatusRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * job_id: "job_id" + * } + */ +export interface JobsStatusRequest { + /** The unique identifier for the job which is given by Intercom */ + job_id: string; +} diff --git a/src/api/resources/jobs/client/requests/index.ts b/src/api/resources/jobs/client/requests/index.ts new file mode 100644 index 00000000..bfed16f9 --- /dev/null +++ b/src/api/resources/jobs/client/requests/index.ts @@ -0,0 +1 @@ +export type { JobsStatusRequest } from "./JobsStatusRequest.js"; diff --git a/src/api/resources/jobs/index.ts b/src/api/resources/jobs/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/jobs/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/jobs/types/Jobs.ts b/src/api/resources/jobs/types/Jobs.ts new file mode 100644 index 00000000..c3e63585 --- /dev/null +++ b/src/api/resources/jobs/types/Jobs.ts @@ -0,0 +1,31 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Jobs are tasks that are processed asynchronously by the Intercom system after being enqueued via the API. This allows for efficient handling of operations that may take time to complete, such as data imports or exports. You can check the status of your jobs to monitor their progress and ensure they are completed successfully. + */ +export interface Jobs { + /** The type of the object */ + type?: "job"; + /** The id of the job that's currently being processed or has completed. */ + id: string; + /** API endpoint URL to check the job status. */ + url?: string; + /** The status of the job execution. */ + status?: Jobs.Status; + /** The type of resource created during job execution. */ + resource_type?: string; + /** The id of the resource created during job execution (e.g. ticket id) */ + resource_id?: string; + /** The url of the resource created during job exeuction. Use this url to fetch the resource. */ + resource_url?: string; +} + +export namespace Jobs { + /** The status of the job execution. */ + export const Status = { + Pending: "pending", + Success: "success", + Failed: "failed", + } as const; + export type Status = (typeof Status)[keyof typeof Status]; +} diff --git a/src/api/resources/jobs/types/index.ts b/src/api/resources/jobs/types/index.ts new file mode 100644 index 00000000..c4ca9992 --- /dev/null +++ b/src/api/resources/jobs/types/index.ts @@ -0,0 +1 @@ +export * from "./Jobs.js"; diff --git a/src/api/resources/messages/client/Client.ts b/src/api/resources/messages/client/Client.ts index 9fd4d027..f4b5d54c 100644 --- a/src/api/resources/messages/client/Client.ts +++ b/src/api/resources/messages/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Messages { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace MessagesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your messages */ -export class Messages { - constructor(protected readonly _options: Messages.Options = {}) {} +export class MessagesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: MessagesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. @@ -89,7 +39,7 @@ export class Messages { * > As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message. * * @param {Intercom.CreateMessageRequest} request - * @param {Messages.RequestOptions} requestOptions - Request-specific configuration. + * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -124,7 +74,7 @@ export class Messages { * }, * to: { * type: "user", - * id: "667d616d8a68186f43bafe53" + * id: "6762f23b1bb69f9f2193bc1a" * }, * created_at: 1590000000, * create_conversation_without_contact_reply: true @@ -160,48 +110,48 @@ export class Messages { * }, * to: { * type: "user", - * id: "667d616e8a68186f43bafe55" + * id: "6762f23d1bb69f9f2193bc1c" * }, * created_at: 1590000000, * create_conversation_without_contact_reply: true * }) */ public create( - request: Intercom.CreateMessageRequest, - requestOptions?: Messages.RequestOptions, + request?: Intercom.CreateMessageRequest, + requestOptions?: MessagesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( - request: Intercom.CreateMessageRequest, - requestOptions?: Messages.RequestOptions, + request?: Intercom.CreateMessageRequest, + requestOptions?: MessagesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "messages", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Message, rawResponse: _response.rawResponse }; @@ -229,32 +179,6 @@ export class Messages { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /messages."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/messages"); } } diff --git a/src/api/resources/messages/index.ts b/src/api/resources/messages/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/messages/index.ts +++ b/src/api/resources/messages/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/messages/types/Message.ts b/src/api/resources/messages/types/Message.ts index d8bd0388..a2f8aa46 100644 --- a/src/api/resources/messages/types/Message.ts +++ b/src/api/resources/messages/types/Message.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Message are how you reach out to contacts in Intercom. They are created when an admin sends an outbound message to a contact. @@ -13,24 +11,22 @@ export interface Message { /** The time the conversation was created. */ created_at: number; /** The subject of the message. Only present if message_type: email. */ - subject: string; + subject?: string; /** The message body, which may contain HTML. */ body: string; /** The type of message that was sent. Can be email, inapp, facebook or twitter. */ message_type: Message.MessageType; /** The associated conversation_id */ - conversation_id: string; + conversation_id?: string; } export namespace Message { - /** - * The type of message that was sent. Can be email, inapp, facebook or twitter. - */ - export type MessageType = "email" | "inapp" | "facebook" | "twitter"; + /** The type of message that was sent. Can be email, inapp, facebook or twitter. */ export const MessageType = { Email: "email", Inapp: "inapp", Facebook: "facebook", Twitter: "twitter", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; } diff --git a/src/api/resources/messages/types/index.ts b/src/api/resources/messages/types/index.ts index 6596816a..e16d36b7 100644 --- a/src/api/resources/messages/types/index.ts +++ b/src/api/resources/messages/types/index.ts @@ -1 +1 @@ -export * from "./Message"; +export * from "./Message.js"; diff --git a/src/api/resources/news/client/Client.ts b/src/api/resources/news/client/Client.ts index 2b6dd6ab..65efc563 100644 --- a/src/api/resources/news/client/Client.ts +++ b/src/api/resources/news/client/Client.ts @@ -1,53 +1,28 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import { Items } from "../resources/items/client/Client"; -import { Feeds } from "../resources/feeds/client/Client"; +import type { BaseClientOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { FeedsClient } from "../resources/feeds/client/Client.js"; +import { ItemsClient } from "../resources/items/client/Client.js"; -export declare namespace News { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace NewsClient { + export interface Options extends BaseClientOptions {} } -export class News { - protected _items: Items | undefined; - protected _feeds: Feeds | undefined; +export class NewsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + protected _items: ItemsClient | undefined; + protected _feeds: FeedsClient | undefined; - constructor(protected readonly _options: News.Options = {}) {} + constructor(options: NewsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } - public get items(): Items { - return (this._items ??= new Items(this._options)); + public get items(): ItemsClient { + return (this._items ??= new ItemsClient(this._options)); } - public get feeds(): Feeds { - return (this._feeds ??= new Feeds(this._options)); + public get feeds(): FeedsClient { + return (this._feeds ??= new FeedsClient(this._options)); } } diff --git a/src/api/resources/news/index.ts b/src/api/resources/news/index.ts index 848e75ab..0ef16e76 100644 --- a/src/api/resources/news/index.ts +++ b/src/api/resources/news/index.ts @@ -1,3 +1,3 @@ -export * from "./types"; -export * from "./client"; -export * from "./resources"; +export * from "./client/index.js"; +export * from "./resources/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/news/resources/feeds/client/Client.ts b/src/api/resources/news/resources/feeds/client/Client.ts index 7af908b2..b3c72e7d 100644 --- a/src/api/resources/news/resources/feeds/client/Client.ts +++ b/src/api/resources/news/resources/feeds/client/Client.ts @@ -1,82 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Feeds { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace FeedsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Feeds { - constructor(protected readonly _options: Feeds.Options = {}) {} +export class FeedsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: FeedsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all news items that are live on a given newsfeed * * @param {Intercom.news.ListNewsFeedItemsRequest} request - * @param {Feeds.RequestOptions} requestOptions - Request-specific configuration. + * @param {FeedsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -87,43 +37,41 @@ export class Feeds { */ public listItems( request: Intercom.news.ListNewsFeedItemsRequest, - requestOptions?: Feeds.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: FeedsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listItems(request, requestOptions)); } private async __listItems( request: Intercom.news.ListNewsFeedItemsRequest, - requestOptions?: Feeds.RequestOptions, - ): Promise> { + requestOptions?: FeedsClient.RequestOptions, + ): Promise> { const { newsfeed_id: newsfeedId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/newsfeeds/${encodeURIComponent(newsfeedId)}/items`, + `news/newsfeeds/${core.url.encodePathParam(newsfeedId)}/items`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.PaginatedNewsItemResponse, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.PaginatedResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -142,69 +90,56 @@ export class Feeds { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /news/newsfeeds/{newsfeed_id}/items.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/news/newsfeeds/{newsfeed_id}/items", + ); } /** * You can fetch a list of all newsfeeds * - * @param {Feeds.RequestOptions} requestOptions - Request-specific configuration. + * @param {FeedsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.news.feeds.list() */ - public list(requestOptions?: Feeds.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: FeedsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } private async __list( - requestOptions?: Feeds.RequestOptions, - ): Promise> { + requestOptions?: FeedsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/newsfeeds", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.PaginatedNewsfeedResponse, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.PaginatedResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -223,28 +158,14 @@ export class Feeds { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/newsfeeds."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/newsfeeds"); } /** * You can fetch the details of a single newsfeed * * @param {Intercom.news.FindNewsFeedRequest} request - * @param {Feeds.RequestOptions} requestOptions - Request-specific configuration. + * @param {FeedsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -255,40 +176,38 @@ export class Feeds { */ public find( request: Intercom.news.FindNewsFeedRequest, - requestOptions?: Feeds.RequestOptions, + requestOptions?: FeedsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.news.FindNewsFeedRequest, - requestOptions?: Feeds.RequestOptions, + requestOptions?: FeedsClient.RequestOptions, ): Promise> { const { newsfeed_id: newsfeedId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/newsfeeds/${encodeURIComponent(newsfeedId)}`, + `news/newsfeeds/${core.url.encodePathParam(newsfeedId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Newsfeed, rawResponse: _response.rawResponse }; @@ -310,34 +229,6 @@ export class Feeds { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /news/newsfeeds/{newsfeed_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/newsfeeds/{newsfeed_id}"); } } diff --git a/src/api/resources/news/resources/feeds/client/index.ts b/src/api/resources/news/resources/feeds/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/news/resources/feeds/client/index.ts +++ b/src/api/resources/news/resources/feeds/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/news/resources/feeds/client/requests/FindNewsFeedRequest.ts b/src/api/resources/news/resources/feeds/client/requests/FindNewsFeedRequest.ts index 4882b9d2..a462c8d7 100644 --- a/src/api/resources/news/resources/feeds/client/requests/FindNewsFeedRequest.ts +++ b/src/api/resources/news/resources/feeds/client/requests/FindNewsFeedRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindNewsFeedRequest { - /** - * The unique identifier for the news feed item which is given by Intercom. - */ + /** The unique identifier for the news feed item which is given by Intercom. */ newsfeed_id: string; } diff --git a/src/api/resources/news/resources/feeds/client/requests/ListNewsFeedItemsRequest.ts b/src/api/resources/news/resources/feeds/client/requests/ListNewsFeedItemsRequest.ts index 209d86cc..5847e03b 100644 --- a/src/api/resources/news/resources/feeds/client/requests/ListNewsFeedItemsRequest.ts +++ b/src/api/resources/news/resources/feeds/client/requests/ListNewsFeedItemsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListNewsFeedItemsRequest { - /** - * The unique identifier for the news feed item which is given by Intercom. - */ + /** The unique identifier for the news feed item which is given by Intercom. */ newsfeed_id: string; } diff --git a/src/api/resources/news/resources/feeds/client/requests/index.ts b/src/api/resources/news/resources/feeds/client/requests/index.ts index 0d025c4f..c32a3ad5 100644 --- a/src/api/resources/news/resources/feeds/client/requests/index.ts +++ b/src/api/resources/news/resources/feeds/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type ListNewsFeedItemsRequest } from "./ListNewsFeedItemsRequest"; -export { type FindNewsFeedRequest } from "./FindNewsFeedRequest"; +export type { FindNewsFeedRequest } from "./FindNewsFeedRequest.js"; +export type { ListNewsFeedItemsRequest } from "./ListNewsFeedItemsRequest.js"; diff --git a/src/api/resources/news/resources/feeds/index.ts b/src/api/resources/news/resources/feeds/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/news/resources/feeds/index.ts +++ b/src/api/resources/news/resources/feeds/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/news/resources/index.ts b/src/api/resources/news/resources/index.ts index bab08c4a..631ce9c7 100644 --- a/src/api/resources/news/resources/index.ts +++ b/src/api/resources/news/resources/index.ts @@ -1,4 +1,4 @@ -export * as items from "./items"; -export * as feeds from "./feeds"; -export * from "./items/client/requests"; -export * from "./feeds/client/requests"; +export * from "./feeds/client/requests/index.js"; +export * as feeds from "./feeds/index.js"; +export * from "./items/client/requests/index.js"; +export * as items from "./items/index.js"; diff --git a/src/api/resources/news/resources/items/client/Client.ts b/src/api/resources/news/resources/items/client/Client.ts index 2dc9fa97..96910a6b 100644 --- a/src/api/resources/news/resources/items/client/Client.ts +++ b/src/api/resources/news/resources/items/client/Client.ts @@ -1,121 +1,69 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Items { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ItemsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Items { - constructor(protected readonly _options: Items.Options = {}) {} +export class ItemsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ItemsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all news items * - * @param {Items.RequestOptions} requestOptions - Request-specific configuration. + * @param {ItemsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.news.items.list() */ - public list(requestOptions?: Items.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: ItemsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } private async __list( - requestOptions?: Items.RequestOptions, - ): Promise> { + requestOptions?: ItemsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/news_items", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.PaginatedNewsItemResponse, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.PaginatedResponse, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -134,28 +82,14 @@ export class Items { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/news_items."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/news_items"); } /** * You can create a news item * * @param {Intercom.NewsItemRequest} request - * @param {Items.RequestOptions} requestOptions - Request-specific configuration. + * @param {ItemsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -163,7 +97,7 @@ export class Items { * await client.news.items.create({ * title: "Halloween is here!", * body: "

New costumes in store for this spooky season

", - * sender_id: 991267734, + * sender_id: 991267834, * state: "live", * deliver_silently: true, * labels: ["Product", "Update", "New"], @@ -176,40 +110,40 @@ export class Items { */ public create( request: Intercom.NewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.NewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/news_items", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.NewsItem, rawResponse: _response.rawResponse }; @@ -231,73 +165,57 @@ export class Items { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /news/news_items."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/news/news_items"); } /** * You can fetch the details of a single news item. * * @param {Intercom.news.FindNewsItemRequest} request - * @param {Items.RequestOptions} requestOptions - Request-specific configuration. + * @param {ItemsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.news.items.find({ - * news_item_id: "123" + * news_item_id: 1 * }) */ public find( request: Intercom.news.FindNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.news.FindNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): Promise> { const { news_item_id: newsItemId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(newsItemId)}`, + `news/news_items/${core.url.encodePathParam(newsItemId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.NewsItem, rawResponse: _response.rawResponse }; @@ -321,91 +239,80 @@ export class Items { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /news/news_items/{news_item_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/news/news_items/{news_item_id}", + ); } /** * @param {Intercom.news.UpdateNewsItemRequest} request - * @param {Items.RequestOptions} requestOptions - Request-specific configuration. + * @param {ItemsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.news.items.update({ - * news_item_id: "123", + * news_item_id: 1, * body: { * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

", - * sender_id: 991267745, + * sender_id: 991267845, * reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] * } * }) * * @example * await client.news.items.update({ - * news_item_id: "123", + * news_item_id: 1, * body: { * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

", - * sender_id: 991267748, + * sender_id: 991267848, * reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] * } * }) */ public update( request: Intercom.news.UpdateNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.news.UpdateNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): Promise> { const { news_item_id: newsItemId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(newsItemId)}`, + `news/news_items/${core.url.encodePathParam(newsItemId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.NewsItem, rawResponse: _response.rawResponse }; @@ -429,75 +336,62 @@ export class Items { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /news/news_items/{news_item_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/news/news_items/{news_item_id}", + ); } /** * You can delete a single news item. * * @param {Intercom.news.DeleteNewsItemRequest} request - * @param {Items.RequestOptions} requestOptions - Request-specific configuration. + * @param {ItemsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.news.items.delete({ - * news_item_id: "123" + * news_item_id: 1 * }) */ public delete( request: Intercom.news.DeleteNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.news.DeleteNewsItemRequest, - requestOptions?: Items.RequestOptions, + requestOptions?: ItemsClient.RequestOptions, ): Promise> { const { news_item_id: newsItemId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(newsItemId)}`, + `news/news_items/${core.url.encodePathParam(newsItemId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.DeletedObject, rawResponse: _response.rawResponse }; @@ -521,34 +415,11 @@ export class Items { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /news/news_items/{news_item_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/news/news_items/{news_item_id}", + ); } } diff --git a/src/api/resources/news/resources/items/client/index.ts b/src/api/resources/news/resources/items/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/news/resources/items/client/index.ts +++ b/src/api/resources/news/resources/items/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/news/resources/items/client/requests/DeleteNewsItemRequest.ts b/src/api/resources/news/resources/items/client/requests/DeleteNewsItemRequest.ts index 9fc8094b..87c64a80 100644 --- a/src/api/resources/news/resources/items/client/requests/DeleteNewsItemRequest.ts +++ b/src/api/resources/news/resources/items/client/requests/DeleteNewsItemRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * news_item_id: "123" + * news_item_id: 1 * } */ export interface DeleteNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ - news_item_id: string; + /** The unique identifier for the news item which is given by Intercom. */ + news_item_id: number; } diff --git a/src/api/resources/news/resources/items/client/requests/FindNewsItemRequest.ts b/src/api/resources/news/resources/items/client/requests/FindNewsItemRequest.ts index d727fbdb..6e8e5ac2 100644 --- a/src/api/resources/news/resources/items/client/requests/FindNewsItemRequest.ts +++ b/src/api/resources/news/resources/items/client/requests/FindNewsItemRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * news_item_id: "123" + * news_item_id: 1 * } */ export interface FindNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ - news_item_id: string; + /** The unique identifier for the news item which is given by Intercom. */ + news_item_id: number; } diff --git a/src/api/resources/news/resources/items/client/requests/UpdateNewsItemRequest.ts b/src/api/resources/news/resources/items/client/requests/UpdateNewsItemRequest.ts index ec976bc2..948351c3 100644 --- a/src/api/resources/news/resources/items/client/requests/UpdateNewsItemRequest.ts +++ b/src/api/resources/news/resources/items/client/requests/UpdateNewsItemRequest.ts @@ -1,36 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example * { - * news_item_id: "123", + * news_item_id: 1, * body: { * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

", - * sender_id: 991267745, + * sender_id: 991267845, * reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] * } * } * * @example * { - * news_item_id: "123", + * news_item_id: 1, * body: { * title: "Christmas is here!", * body: "

New gifts in store for the jolly season

", - * sender_id: 991267748, + * sender_id: 991267848, * reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"] * } * } */ export interface UpdateNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ - news_item_id: string; + /** The unique identifier for the news item which is given by Intercom. */ + news_item_id: number; body: Intercom.NewsItemRequest; } diff --git a/src/api/resources/news/resources/items/client/requests/index.ts b/src/api/resources/news/resources/items/client/requests/index.ts index 0ae128c3..3869d0b3 100644 --- a/src/api/resources/news/resources/items/client/requests/index.ts +++ b/src/api/resources/news/resources/items/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type FindNewsItemRequest } from "./FindNewsItemRequest"; -export { type UpdateNewsItemRequest } from "./UpdateNewsItemRequest"; -export { type DeleteNewsItemRequest } from "./DeleteNewsItemRequest"; +export type { DeleteNewsItemRequest } from "./DeleteNewsItemRequest.js"; +export type { FindNewsItemRequest } from "./FindNewsItemRequest.js"; +export type { UpdateNewsItemRequest } from "./UpdateNewsItemRequest.js"; diff --git a/src/api/resources/news/resources/items/index.ts b/src/api/resources/news/resources/items/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/news/resources/items/index.ts +++ b/src/api/resources/news/resources/items/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/news/types/NewsItem.ts b/src/api/resources/news/types/NewsItem.ts index 2addce53..7ae7b3f9 100644 --- a/src/api/resources/news/types/NewsItem.ts +++ b/src/api/resources/news/types/NewsItem.ts @@ -1,27 +1,25 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A News Item is a content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers. */ export interface NewsItem { /** The type of object. */ - type: "news-item"; + type?: "news-item"; /** The unique identifier for the news item which is given by Intercom. */ - id: string; + id?: string; /** The id of the workspace which the news item belongs to. */ - workspace_id: string; + workspace_id?: string; /** The title of the news item. */ - title: string; + title?: string; /** The news item body, which may contain HTML. */ - body: string; + body?: string; /** The id of the sender of the news item. Must be a teammate on the workspace. */ - sender_id: number; + sender_id?: number; /** News items will not be visible to your users in the assigned newsfeeds until they are set live. */ - state: NewsItem.State; + state?: NewsItem.State; /** A list of newsfeed_assignments to assign to the specified newsfeed. */ newsfeed_assignments?: Intercom.NewsfeedAssignment[]; /** Label names displayed to users to categorize the news item. */ @@ -33,18 +31,16 @@ export interface NewsItem { /** When set to true, the news item will appear in the messenger newsfeed without showing a notification badge. */ deliver_silently?: boolean; /** Timestamp for when the news item was created. */ - created_at: number; + created_at?: number; /** Timestamp for when the news item was last updated. */ updated_at?: number; } export namespace NewsItem { - /** - * News items will not be visible to your users in the assigned newsfeeds until they are set live. - */ - export type State = "draft" | "live"; + /** News items will not be visible to your users in the assigned newsfeeds until they are set live. */ export const State = { Draft: "draft", Live: "live", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/news/types/Newsfeed.ts b/src/api/resources/news/types/Newsfeed.ts index a20a9016..a42f6306 100644 --- a/src/api/resources/news/types/Newsfeed.ts +++ b/src/api/resources/news/types/Newsfeed.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A newsfeed is a collection of news items, targeted to a specific audience. @@ -9,13 +7,13 @@ */ export interface Newsfeed { /** The unique identifier for the newsfeed which is given by Intercom. */ - id: string; + id?: string; /** The type of object. */ - type: "newsfeed"; + type?: "newsfeed"; /** The name of the newsfeed. This name will never be visible to your users. */ - name: string; + name?: string; /** Timestamp for when the newsfeed was created. */ - created_at: number; + created_at?: number; /** Timestamp for when the newsfeed was last updated. */ updated_at?: number; } diff --git a/src/api/resources/news/types/NewsfeedAssignment.ts b/src/api/resources/news/types/NewsfeedAssignment.ts index 80447b20..064483c9 100644 --- a/src/api/resources/news/types/NewsfeedAssignment.ts +++ b/src/api/resources/news/types/NewsfeedAssignment.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Assigns a news item to a newsfeed. */ export interface NewsfeedAssignment { /** The unique identifier for the newsfeed which is given by Intercom. Publish dates cannot be in the future, to schedule news items use the dedicated feature in app (see this article). */ - newsfeed_id: number; + newsfeed_id?: number; /** Publish date of the news item on the newsfeed, use this field if you want to set a publish date in the past (e.g. when importing existing news items). On write, this field will be ignored if the news item state is "draft". */ - published_at: number; + published_at?: number; } diff --git a/src/api/resources/news/types/index.ts b/src/api/resources/news/types/index.ts index b8c22f3c..fe7a29c8 100644 --- a/src/api/resources/news/types/index.ts +++ b/src/api/resources/news/types/index.ts @@ -1,3 +1,3 @@ -export * from "./NewsItem"; -export * from "./Newsfeed"; -export * from "./NewsfeedAssignment"; +export * from "./Newsfeed.js"; +export * from "./NewsfeedAssignment.js"; +export * from "./NewsItem.js"; diff --git a/src/api/resources/notes/client/Client.ts b/src/api/resources/notes/client/Client.ts index 44866b02..da58ae5d 100644 --- a/src/api/resources/notes/client/Client.ts +++ b/src/api/resources/notes/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Notes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace NotesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Notes */ -export class Notes { - constructor(protected readonly _options: Notes.Options = {}) {} +export class NotesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: NotesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of notes that are associated to a contact. * * @param {Intercom.ListContactNotesRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.NotFoundError} * @@ -90,44 +40,40 @@ export class Notes { */ public async list( request: Intercom.ListContactNotesRequest, - requestOptions?: Notes.RequestOptions, - ): Promise> { + requestOptions?: NotesClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.ListContactNotesRequest): Promise> => { const { contact_id: contactId, page, per_page: perPage } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/notes`, + `contacts/${core.url.encodePathParam(contactId)}/notes`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.NoteList, rawResponse: _response.rawResponse }; @@ -144,28 +90,17 @@ export class Notes { }); } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/notes.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/notes", + ); }, ); let _offset = request?.page != null ? request?.page : 1; const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, hasNextPage: (response) => (response?.data ?? []).length > 0, @@ -181,7 +116,7 @@ export class Notes { * You can add a note to a single contact. * * @param {Intercom.CreateContactNoteRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.NotFoundError} * @@ -194,41 +129,41 @@ export class Notes { */ public create( request: Intercom.CreateContactNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateContactNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/notes`, + `contacts/${core.url.encodePathParam(contactId)}/notes`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Note, rawResponse: _response.rawResponse }; @@ -247,75 +182,57 @@ export class Notes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/notes.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{contact_id}/notes"); } /** * You can fetch the details of a single note. * * @param {Intercom.FindNoteRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.notes.find({ - * note_id: "1" + * note_id: 1 * }) */ public find( request: Intercom.FindNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): Promise> { const { note_id: noteId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `notes/${encodeURIComponent(noteId)}`, + `notes/${core.url.encodePathParam(noteId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Note, rawResponse: _response.rawResponse }; @@ -339,32 +256,6 @@ export class Notes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /notes/{note_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/notes/{note_id}"); } } diff --git a/src/api/resources/notes/client/index.ts b/src/api/resources/notes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/notes/client/index.ts +++ b/src/api/resources/notes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/notes/client/requests/CreateContactNoteRequest.ts b/src/api/resources/notes/client/requests/CreateContactNoteRequest.ts index 1cadbe4a..bff219f9 100644 --- a/src/api/resources/notes/client/requests/CreateContactNoteRequest.ts +++ b/src/api/resources/notes/client/requests/CreateContactNoteRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,9 +23,7 @@ * } */ export interface CreateContactNoteRequest { - /** - * The unique identifier of a given contact. - */ + /** The unique identifier of a given contact. */ contact_id: string; /** The text of the note. */ body: string; diff --git a/src/api/resources/notes/client/requests/FindNoteRequest.ts b/src/api/resources/notes/client/requests/FindNoteRequest.ts index 35bff5e2..c7efb6a9 100644 --- a/src/api/resources/notes/client/requests/FindNoteRequest.ts +++ b/src/api/resources/notes/client/requests/FindNoteRequest.ts @@ -1,16 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * note_id: "1" + * note_id: 1 * } */ export interface FindNoteRequest { - /** - * The unique identifier of a given note - */ - note_id: string; + /** The unique identifier of a given note */ + note_id: number; } diff --git a/src/api/resources/notes/client/requests/ListContactNotesRequest.ts b/src/api/resources/notes/client/requests/ListContactNotesRequest.ts index 1c8b5763..49b13673 100644 --- a/src/api/resources/notes/client/requests/ListContactNotesRequest.ts +++ b/src/api/resources/notes/client/requests/ListContactNotesRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,16 +7,10 @@ * } */ export interface ListContactNotesRequest { - /** - * The unique identifier of a contact. - */ + /** The unique identifier of a contact. */ contact_id: string; - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/notes/client/requests/index.ts b/src/api/resources/notes/client/requests/index.ts index 6271b2a9..d6e2648b 100644 --- a/src/api/resources/notes/client/requests/index.ts +++ b/src/api/resources/notes/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type ListContactNotesRequest } from "./ListContactNotesRequest"; -export { type CreateContactNoteRequest } from "./CreateContactNoteRequest"; -export { type FindNoteRequest } from "./FindNoteRequest"; +export type { CreateContactNoteRequest } from "./CreateContactNoteRequest.js"; +export type { FindNoteRequest } from "./FindNoteRequest.js"; +export type { ListContactNotesRequest } from "./ListContactNotesRequest.js"; diff --git a/src/api/resources/notes/index.ts b/src/api/resources/notes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/notes/index.ts +++ b/src/api/resources/notes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/notes/types/Note.ts b/src/api/resources/notes/types/Note.ts index a2b2345d..e22e0eb3 100644 --- a/src/api/resources/notes/types/Note.ts +++ b/src/api/resources/notes/types/Note.ts @@ -1,25 +1,23 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Notes allow you to annotate and comment on your contacts. */ export interface Note { /** String representing the object's type. Always has the value `note`. */ - type: "note"; + type?: string; /** The id of the note. */ - id: string; + id?: string; /** The time the note was created. */ - created_at: number; + created_at?: number; /** Represents the contact that the note was created about. */ contact?: Note.Contact; /** Optional. Represents the Admin that created the note. */ - author: Intercom.Admin; + author?: Intercom.Admin; /** The body text of the note. */ - body: string; + body?: string; } export namespace Note { @@ -28,7 +26,7 @@ export namespace Note { */ export interface Contact { /** String representing the object's type. Always has the value `contact`. */ - type?: "contact"; + type?: string; /** The id of the contact. */ id?: string; } diff --git a/src/api/resources/notes/types/index.ts b/src/api/resources/notes/types/index.ts index cf881fa5..e0e2f407 100644 --- a/src/api/resources/notes/types/index.ts +++ b/src/api/resources/notes/types/index.ts @@ -1 +1 @@ -export * from "./Note"; +export * from "./Note.js"; diff --git a/src/api/resources/phoneCallRedirects/client/Client.ts b/src/api/resources/phoneCallRedirects/client/Client.ts index 2c057d93..e2585a9f 100644 --- a/src/api/resources/phoneCallRedirects/client/Client.ts +++ b/src/api/resources/phoneCallRedirects/client/Client.ts @@ -1,76 +1,26 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace PhoneCallRedirects { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace PhoneCallRedirectsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class PhoneCallRedirects { - constructor(protected readonly _options: PhoneCallRedirects.Options = {}) {} +export class PhoneCallRedirectsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: PhoneCallRedirectsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can use the API to deflect phone calls to the Intercom Messenger. @@ -78,8 +28,8 @@ export class PhoneCallRedirects { * * If custom attributes are specified, they will be added to the user or lead's custom data attributes. * - * @param {Intercom.CreatePhoneCallRedirectRequest} request - * @param {PhoneCallRedirects.RequestOptions} requestOptions - Request-specific configuration. + * @param {Intercom.CreatePhoneSwitchRequest} request + * @param {PhoneCallRedirectsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -104,44 +54,44 @@ export class PhoneCallRedirects { * }) */ public create( - request: Intercom.CreatePhoneCallRedirectRequest, - requestOptions?: PhoneCallRedirects.RequestOptions, - ): core.HttpResponsePromise { + request?: Intercom.CreatePhoneSwitchRequest, + requestOptions?: PhoneCallRedirectsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( - request: Intercom.CreatePhoneCallRedirectRequest, - requestOptions?: PhoneCallRedirects.RequestOptions, - ): Promise> { + request?: Intercom.CreatePhoneSwitchRequest, + requestOptions?: PhoneCallRedirectsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "phone_call_redirects", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.PhoneSwitch, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.PhoneSwitch | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -164,32 +114,6 @@ export class PhoneCallRedirects { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /phone_call_redirects."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/phone_call_redirects"); } } diff --git a/src/api/resources/phoneCallRedirects/client/index.ts b/src/api/resources/phoneCallRedirects/client/index.ts index 415726b7..cb0ff5c3 100644 --- a/src/api/resources/phoneCallRedirects/client/index.ts +++ b/src/api/resources/phoneCallRedirects/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export {}; diff --git a/src/api/resources/phoneCallRedirects/client/requests/CreatePhoneCallRedirectRequest.ts b/src/api/resources/phoneCallRedirects/client/requests/CreatePhoneCallRedirectRequest.ts deleted file mode 100644 index 3b19efc3..00000000 --- a/src/api/resources/phoneCallRedirects/client/requests/CreatePhoneCallRedirectRequest.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../../../../index"; - -/** - * @example - * { - * phone: "+353832345678", - * custom_attributes: { - * "issue_type": "Billing", - * "priority": "High" - * } - * } - * - * @example - * { - * phone: "+353832345678", - * custom_attributes: { - * "issue_type": "Billing", - * "priority": "High" - * } - * } - * - * @example - * { - * phone: "+353832345678", - * custom_attributes: { - * "issue_type": "Billing", - * "priority": "High" - * } - * } - * - * @example - * { - * phone: "+40241100100", - * custom_attributes: { - * "issue_type": "Billing", - * "priority": "High" - * } - * } - */ -export interface CreatePhoneCallRedirectRequest { - /** Phone number in E.164 format, that will receive the SMS to continue the conversation in the Messenger. */ - phone: string; - custom_attributes?: Intercom.CustomAttributes; -} diff --git a/src/api/resources/phoneCallRedirects/client/requests/index.ts b/src/api/resources/phoneCallRedirects/client/requests/index.ts deleted file mode 100644 index 7038d703..00000000 --- a/src/api/resources/phoneCallRedirects/client/requests/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { type CreatePhoneCallRedirectRequest } from "./CreatePhoneCallRedirectRequest"; diff --git a/src/api/resources/phoneCallRedirects/index.ts b/src/api/resources/phoneCallRedirects/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/phoneCallRedirects/index.ts +++ b/src/api/resources/phoneCallRedirects/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/segments/client/Client.ts b/src/api/resources/segments/client/Client.ts index 738a10b7..d7073779 100644 --- a/src/api/resources/segments/client/Client.ts +++ b/src/api/resources/segments/client/Client.ts @@ -1,133 +1,82 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Segments { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace SegmentsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Segments */ -export class Segments { - constructor(protected readonly _options: Segments.Options = {}) {} +export class SegmentsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: SegmentsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all segments. * * @param {Intercom.ListSegmentsRequest} request - * @param {Segments.RequestOptions} requestOptions - Request-specific configuration. + * @param {SegmentsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example - * await client.segments.list() + * await client.segments.list({ + * include_count: true + * }) */ public list( request: Intercom.ListSegmentsRequest = {}, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); } private async __list( request: Intercom.ListSegmentsRequest = {}, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): Promise> { const { include_count: includeCount } = request; const _queryParams: Record = {}; if (includeCount != null) { - _queryParams["include_count"] = includeCount.toString(); + _queryParams.include_count = includeCount.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "segments", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.SegmentList, rawResponse: _response.rawResponse }; @@ -149,28 +98,14 @@ export class Segments { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /segments."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/segments"); } /** * You can fetch the details of a single segment. * * @param {Intercom.FindSegmentRequest} request - * @param {Segments.RequestOptions} requestOptions - Request-specific configuration. + * @param {SegmentsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -182,40 +117,38 @@ export class Segments { */ public find( request: Intercom.FindSegmentRequest, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindSegmentRequest, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): Promise> { const { segment_id: segmentId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `segments/${encodeURIComponent(segmentId)}`, + `segments/${core.url.encodePathParam(segmentId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Segment, rawResponse: _response.rawResponse }; @@ -239,32 +172,6 @@ export class Segments { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /segments/{segment_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/segments/{segment_id}"); } } diff --git a/src/api/resources/segments/client/index.ts b/src/api/resources/segments/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/segments/client/index.ts +++ b/src/api/resources/segments/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/segments/client/requests/FindSegmentRequest.ts b/src/api/resources/segments/client/requests/FindSegmentRequest.ts index 0e0dff0b..eb150f95 100644 --- a/src/api/resources/segments/client/requests/FindSegmentRequest.ts +++ b/src/api/resources/segments/client/requests/FindSegmentRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindSegmentRequest { - /** - * The unique identified of a given segment. - */ + /** The unique identified of a given segment. */ segment_id: string; } diff --git a/src/api/resources/segments/client/requests/ListSegmentsRequest.ts b/src/api/resources/segments/client/requests/ListSegmentsRequest.ts index 116acd5e..7554f000 100644 --- a/src/api/resources/segments/client/requests/ListSegmentsRequest.ts +++ b/src/api/resources/segments/client/requests/ListSegmentsRequest.ts @@ -1,14 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * include_count: true + * } */ export interface ListSegmentsRequest { - /** - * It includes the count of contacts that belong to each segment. - */ + /** It includes the count of contacts that belong to each segment. */ include_count?: boolean; } diff --git a/src/api/resources/segments/client/requests/index.ts b/src/api/resources/segments/client/requests/index.ts index a7d400d9..851720dd 100644 --- a/src/api/resources/segments/client/requests/index.ts +++ b/src/api/resources/segments/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type ListSegmentsRequest } from "./ListSegmentsRequest"; -export { type FindSegmentRequest } from "./FindSegmentRequest"; +export type { FindSegmentRequest } from "./FindSegmentRequest.js"; +export type { ListSegmentsRequest } from "./ListSegmentsRequest.js"; diff --git a/src/api/resources/segments/index.ts b/src/api/resources/segments/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/segments/index.ts +++ b/src/api/resources/segments/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/segments/types/Segment.ts b/src/api/resources/segments/types/Segment.ts index 6612edb7..5fbb6b53 100644 --- a/src/api/resources/segments/types/Segment.ts +++ b/src/api/resources/segments/types/Segment.ts @@ -1,34 +1,30 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A segment is a group of your contacts defined by the rules that you set. */ export interface Segment { /** The type of object. */ - type: "segment"; + type?: "segment"; /** The unique identifier representing the segment. */ - id: string; + id?: string; /** The name of the segment. */ - name: string; + name?: string; /** The time the segment was created. */ - created_at: number; + created_at?: number; /** The time the segment was updated. */ updated_at?: number; /** Type of the contact: contact (lead) or user. */ - person_type: Segment.PersonType; + person_type?: Segment.PersonType; /** The number of items in the user segment. It's returned when `include_count=true` is included in the request. */ count?: number; } export namespace Segment { - /** - * Type of the contact: contact (lead) or user. - */ - export type PersonType = "contact" | "user"; + /** Type of the contact: contact (lead) or user. */ export const PersonType = { Contact: "contact", User: "user", } as const; + export type PersonType = (typeof PersonType)[keyof typeof PersonType]; } diff --git a/src/api/resources/segments/types/index.ts b/src/api/resources/segments/types/index.ts index 957aab14..a934b01a 100644 --- a/src/api/resources/segments/types/index.ts +++ b/src/api/resources/segments/types/index.ts @@ -1 +1 @@ -export * from "./Segment"; +export * from "./Segment.js"; diff --git a/src/api/resources/subscriptionTypes/client/Client.ts b/src/api/resources/subscriptionTypes/client/Client.ts index abfe8aa7..3f0c2673 100644 --- a/src/api/resources/subscriptionTypes/client/Client.ts +++ b/src/api/resources/subscriptionTypes/client/Client.ts @@ -1,84 +1,34 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace SubscriptionTypes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace SubscriptionTypesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about subscription types */ -export class SubscriptionTypes { - constructor(protected readonly _options: SubscriptionTypes.Options = {}) {} +export class SubscriptionTypesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: SubscriptionTypesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can list all subscription types. A list of subscription type objects will be returned. * - * @param {SubscriptionTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -86,38 +36,36 @@ export class SubscriptionTypes { * await client.subscriptionTypes.list() */ public list( - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } private async __list( - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "subscription_types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.SubscriptionTypeList, rawResponse: _response.rawResponse }; @@ -139,32 +87,6 @@ export class SubscriptionTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /subscription_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/subscription_types"); } } diff --git a/src/api/resources/subscriptionTypes/index.ts b/src/api/resources/subscriptionTypes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/subscriptionTypes/index.ts +++ b/src/api/resources/subscriptionTypes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/subscriptionTypes/types/SubscriptionType.ts b/src/api/resources/subscriptionTypes/types/SubscriptionType.ts index fe1c68ff..55372879 100644 --- a/src/api/resources/subscriptionTypes/types/SubscriptionType.ts +++ b/src/api/resources/subscriptionTypes/types/SubscriptionType.ts @@ -1,53 +1,47 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A subscription type lets customers easily opt out of non-essential communications without missing what's important to them. */ export interface SubscriptionType { /** The type of the object - subscription */ - type: "subscription"; + type?: "subscription"; /** The unique identifier representing the subscription type. */ - id: string; + id?: string; /** The state of the subscription type. */ - state: SubscriptionType.State; - default_translation: Intercom.Translation; + state?: SubscriptionType.State; + default_translation?: Intercom.Translation; /** An array of translations objects with the localised version of the subscription type in each available locale within your translation settings. */ - translations: Intercom.Translation[]; + translations?: Intercom.Translation[]; /** Describes the type of consent. */ - consent_type: SubscriptionType.ConsentType; + consent_type?: SubscriptionType.ConsentType; /** The message types that this subscription supports - can contain `email` or `sms_message`. */ - content_types: SubscriptionType.ContentTypes.Item[]; + content_types?: SubscriptionType.ContentTypes.Item[]; } export namespace SubscriptionType { - /** - * The state of the subscription type. - */ - export type State = "live" | "draft" | "archived"; + /** The state of the subscription type. */ export const State = { Live: "live", Draft: "draft", Archived: "archived", } as const; - /** - * Describes the type of consent. - */ - export type ConsentType = "opt_out" | "opt_in"; + export type State = (typeof State)[keyof typeof State]; + /** Describes the type of consent. */ export const ConsentType = { OptOut: "opt_out", OptIn: "opt_in", } as const; + export type ConsentType = (typeof ConsentType)[keyof typeof ConsentType]; export type ContentTypes = ContentTypes.Item[]; export namespace ContentTypes { - export type Item = "email" | "sms_message"; export const Item = { Email: "email", SmsMessage: "sms_message", } as const; + export type Item = (typeof Item)[keyof typeof Item]; } } diff --git a/src/api/resources/subscriptionTypes/types/index.ts b/src/api/resources/subscriptionTypes/types/index.ts index fe95bab5..b6a27359 100644 --- a/src/api/resources/subscriptionTypes/types/index.ts +++ b/src/api/resources/subscriptionTypes/types/index.ts @@ -1 +1 @@ -export * from "./SubscriptionType"; +export * from "./SubscriptionType.js"; diff --git a/src/api/resources/tags/client/Client.ts b/src/api/resources/tags/client/Client.ts index db51c738..33235bf3 100644 --- a/src/api/resources/tags/client/Client.ts +++ b/src/api/resources/tags/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Tags { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TagsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about tags */ -export class Tags { - constructor(protected readonly _options: Tags.Options = {}) {} +export class TagsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TagsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. * * @param {Intercom.TagContactRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -98,41 +48,41 @@ export class Tags { */ public tagContact( request: Intercom.TagContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__tagContact(request, requestOptions)); } private async __tagContact( request: Intercom.TagContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags`, + `contacts/${core.url.encodePathParam(contactId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -156,30 +106,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/tags.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{contact_id}/tags"); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. * * @param {Intercom.UntagContactRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -192,40 +126,38 @@ export class Tags { */ public untagContact( request: Intercom.UntagContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__untagContact(request, requestOptions)); } private async __untagContact( request: Intercom.UntagContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { contact_id: contactId, tag_id: tagId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags/${encodeURIComponent(tagId)}`, + `contacts/${core.url.encodePathParam(contactId)}/tags/${core.url.encodePathParam(tagId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -249,30 +181,19 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/tags/{tag_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/tags/{tag_id}", + ); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. * * @param {Intercom.TagConversationRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -286,41 +207,41 @@ export class Tags { */ public tagConversation( request: Intercom.TagConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__tagConversation(request, requestOptions)); } private async __tagConversation( request: Intercom.TagConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/tags`, + `conversations/${core.url.encodePathParam(conversationId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -344,30 +265,19 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/tags.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/tags", + ); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. * * @param {Intercom.UntagConversationRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -381,41 +291,41 @@ export class Tags { */ public untagConversation( request: Intercom.UntagConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__untagConversation(request, requestOptions)); } private async __untagConversation( request: Intercom.UntagConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, tag_id: tagId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/tags/${encodeURIComponent(tagId)}`, + `conversations/${core.url.encodePathParam(conversationId)}/tags/${core.url.encodePathParam(tagId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -439,64 +349,52 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /conversations/{conversation_id}/tags/{tag_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/conversations/{conversation_id}/tags/{tag_id}", + ); } /** * You can fetch a list of all tags for a given workspace. * - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.tags.list() */ - public list(requestOptions?: Tags.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: TagsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } - private async __list(requestOptions?: Tags.RequestOptions): Promise> { + private async __list(requestOptions?: TagsClient.RequestOptions): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tags", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TagList, rawResponse: _response.rawResponse }; @@ -518,21 +416,7 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tags"); } /** @@ -551,7 +435,7 @@ export class Tags { * Each operation will return a tag object. * * @param {Intercom.TagsCreateRequestBody} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -585,40 +469,40 @@ export class Tags { */ public create( request: Intercom.TagsCreateRequestBody, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.TagsCreateRequestBody, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tags", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -644,21 +528,7 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tags"); } /** @@ -666,7 +536,7 @@ export class Tags { * This will return a tag object. * * @param {Intercom.FindTagRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -678,40 +548,38 @@ export class Tags { */ public find( request: Intercom.FindTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { tag_id: tagId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tags/${encodeURIComponent(tagId)}`, + `tags/${core.url.encodePathParam(tagId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -735,28 +603,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tags/{tag_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tags/{tag_id}"); } /** * You can delete the details of tags that are on the workspace by passing in the id. * * @param {Intercom.DeleteTagRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -769,40 +623,38 @@ export class Tags { */ public delete( request: Intercom.DeleteTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); } private async __delete( request: Intercom.DeleteTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { tag_id: tagId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tags/${encodeURIComponent(tagId)}`, + `tags/${core.url.encodePathParam(tagId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -828,28 +680,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /tags/{tag_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/tags/{tag_id}"); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. * * @param {Intercom.TagTicketRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -863,41 +701,41 @@ export class Tags { */ public tagTicket( request: Intercom.TagTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__tagTicket(request, requestOptions)); } private async __tagTicket( request: Intercom.TagTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { ticket_id: ticketId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}/tags`, + `tickets/${core.url.encodePathParam(ticketId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -921,28 +759,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/{ticket_id}/tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/{ticket_id}/tags"); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. * * @param {Intercom.UntagTicketRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -956,41 +780,41 @@ export class Tags { */ public untagTicket( request: Intercom.UntagTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__untagTicket(request, requestOptions)); } private async __untagTicket( request: Intercom.UntagTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { ticket_id: ticketId, tag_id: tagId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}/tags/${encodeURIComponent(tagId)}`, + `tickets/${core.url.encodePathParam(ticketId)}/tags/${core.url.encodePathParam(tagId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Tag, rawResponse: _response.rawResponse }; @@ -1014,34 +838,11 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /tickets/{ticket_id}/tags/{tag_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/tickets/{ticket_id}/tags/{tag_id}", + ); } } diff --git a/src/api/resources/tags/client/index.ts b/src/api/resources/tags/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/tags/client/index.ts +++ b/src/api/resources/tags/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/tags/client/requests/DeleteTagRequest.ts b/src/api/resources/tags/client/requests/DeleteTagRequest.ts index c6f44174..4e81f7e4 100644 --- a/src/api/resources/tags/client/requests/DeleteTagRequest.ts +++ b/src/api/resources/tags/client/requests/DeleteTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteTagRequest { - /** - * The unique identifier of a given tag - */ + /** The unique identifier of a given tag */ tag_id: string; } diff --git a/src/api/resources/tags/client/requests/FindTagRequest.ts b/src/api/resources/tags/client/requests/FindTagRequest.ts index b708ed6a..89b19db8 100644 --- a/src/api/resources/tags/client/requests/FindTagRequest.ts +++ b/src/api/resources/tags/client/requests/FindTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindTagRequest { - /** - * The unique identifier of a given tag - */ + /** The unique identifier of a given tag */ tag_id: string; } diff --git a/src/api/resources/tags/client/requests/TagContactRequest.ts b/src/api/resources/tags/client/requests/TagContactRequest.ts index fe463e94..a9dd6aa2 100644 --- a/src/api/resources/tags/client/requests/TagContactRequest.ts +++ b/src/api/resources/tags/client/requests/TagContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -22,9 +20,7 @@ * } */ export interface TagContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/tags/client/requests/TagConversationRequest.ts b/src/api/resources/tags/client/requests/TagConversationRequest.ts index 2fd2282f..1a744067 100644 --- a/src/api/resources/tags/client/requests/TagConversationRequest.ts +++ b/src/api/resources/tags/client/requests/TagConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -18,9 +16,7 @@ * } */ export interface TagConversationRequest { - /** - * conversation_id - */ + /** conversation_id */ conversation_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/tags/client/requests/TagTicketRequest.ts b/src/api/resources/tags/client/requests/TagTicketRequest.ts index 3be7d004..6835d0db 100644 --- a/src/api/resources/tags/client/requests/TagTicketRequest.ts +++ b/src/api/resources/tags/client/requests/TagTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -18,9 +16,7 @@ * } */ export interface TagTicketRequest { - /** - * ticket_id - */ + /** ticket_id */ ticket_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/tags/client/requests/UntagContactRequest.ts b/src/api/resources/tags/client/requests/UntagContactRequest.ts index 81a2c945..27108640 100644 --- a/src/api/resources/tags/client/requests/UntagContactRequest.ts +++ b/src/api/resources/tags/client/requests/UntagContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface UntagContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the tag which is given by Intercom - */ + /** The unique identifier for the tag which is given by Intercom */ tag_id: string; } diff --git a/src/api/resources/tags/client/requests/UntagConversationRequest.ts b/src/api/resources/tags/client/requests/UntagConversationRequest.ts index 1d730070..bcf4e945 100644 --- a/src/api/resources/tags/client/requests/UntagConversationRequest.ts +++ b/src/api/resources/tags/client/requests/UntagConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,13 +23,9 @@ * } */ export interface UntagConversationRequest { - /** - * conversation_id - */ + /** conversation_id */ conversation_id: string; - /** - * id - */ + /** tag_id */ tag_id: string; /** The unique identifier for the admin which is given by Intercom. */ admin_id: string; diff --git a/src/api/resources/tags/client/requests/UntagTicketRequest.ts b/src/api/resources/tags/client/requests/UntagTicketRequest.ts index 2115f12e..d6063ea7 100644 --- a/src/api/resources/tags/client/requests/UntagTicketRequest.ts +++ b/src/api/resources/tags/client/requests/UntagTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,13 +23,9 @@ * } */ export interface UntagTicketRequest { - /** - * ticket_id - */ + /** ticket_id */ ticket_id: string; - /** - * The unique identifier for the tag which is given by Intercom - */ + /** The unique identifier for the tag which is given by Intercom */ tag_id: string; /** The unique identifier for the admin which is given by Intercom. */ admin_id: string; diff --git a/src/api/resources/tags/client/requests/index.ts b/src/api/resources/tags/client/requests/index.ts index 0d5e855b..f924d8ba 100644 --- a/src/api/resources/tags/client/requests/index.ts +++ b/src/api/resources/tags/client/requests/index.ts @@ -1,8 +1,8 @@ -export { type TagContactRequest } from "./TagContactRequest"; -export { type UntagContactRequest } from "./UntagContactRequest"; -export { type TagConversationRequest } from "./TagConversationRequest"; -export { type UntagConversationRequest } from "./UntagConversationRequest"; -export { type FindTagRequest } from "./FindTagRequest"; -export { type DeleteTagRequest } from "./DeleteTagRequest"; -export { type TagTicketRequest } from "./TagTicketRequest"; -export { type UntagTicketRequest } from "./UntagTicketRequest"; +export type { DeleteTagRequest } from "./DeleteTagRequest.js"; +export type { FindTagRequest } from "./FindTagRequest.js"; +export type { TagContactRequest } from "./TagContactRequest.js"; +export type { TagConversationRequest } from "./TagConversationRequest.js"; +export type { TagTicketRequest } from "./TagTicketRequest.js"; +export type { UntagContactRequest } from "./UntagContactRequest.js"; +export type { UntagConversationRequest } from "./UntagConversationRequest.js"; +export type { UntagTicketRequest } from "./UntagTicketRequest.js"; diff --git a/src/api/resources/tags/index.ts b/src/api/resources/tags/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/tags/index.ts +++ b/src/api/resources/tags/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/tags/types/Tag.ts b/src/api/resources/tags/types/Tag.ts index 7002dfdb..3a2c7940 100644 --- a/src/api/resources/tags/types/Tag.ts +++ b/src/api/resources/tags/types/Tag.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A tag allows you to label your contacts, companies, and conversations and list them using that tag. @@ -15,6 +13,6 @@ export interface Tag { /** The name of the tag */ name: string; /** The time when the tag was applied to the object */ - applied_at: number; - applied_by: Intercom.Reference; + applied_at?: number; + applied_by?: Intercom.Reference; } diff --git a/src/api/resources/tags/types/TagBasic.ts b/src/api/resources/tags/types/TagBasic.ts new file mode 100644 index 00000000..8e8b815d --- /dev/null +++ b/src/api/resources/tags/types/TagBasic.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * A tag allows you to label your contacts, companies, and conversations and list them using that tag. + */ +export interface TagBasic { + /** value is "tag" */ + type?: string; + /** The id of the tag */ + id?: string; + /** The name of the tag */ + name?: string; +} diff --git a/src/api/resources/tags/types/TagsCreateRequestBody.ts b/src/api/resources/tags/types/TagsCreateRequestBody.ts index aaf7c9e9..3858b435 100644 --- a/src/api/resources/tags/types/TagsCreateRequestBody.ts +++ b/src/api/resources/tags/types/TagsCreateRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type TagsCreateRequestBody = | Intercom.CreateOrUpdateTagRequest diff --git a/src/api/resources/tags/types/index.ts b/src/api/resources/tags/types/index.ts index 9f251c2a..9a358541 100644 --- a/src/api/resources/tags/types/index.ts +++ b/src/api/resources/tags/types/index.ts @@ -1,2 +1,3 @@ -export * from "./TagsCreateRequestBody"; -export * from "./Tag"; +export * from "./Tag.js"; +export * from "./TagBasic.js"; +export * from "./TagsCreateRequestBody.js"; diff --git a/src/api/resources/teams/client/Client.ts b/src/api/resources/teams/client/Client.ts index 2d523ac4..13d8921e 100644 --- a/src/api/resources/teams/client/Client.ts +++ b/src/api/resources/teams/client/Client.ts @@ -1,119 +1,69 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Teams { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TeamsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Teams */ -export class Teams { - constructor(protected readonly _options: Teams.Options = {}) {} +export class TeamsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TeamsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * This will return a list of team objects for the App. * - * @param {Teams.RequestOptions} requestOptions - Request-specific configuration. + * @param {TeamsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.teams.list() */ - public list(requestOptions?: Teams.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: TeamsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } - private async __list(requestOptions?: Teams.RequestOptions): Promise> { + private async __list( + requestOptions?: TeamsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "teams", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TeamList, rawResponse: _response.rawResponse }; @@ -135,28 +85,14 @@ export class Teams { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /teams."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/teams"); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. * * @param {Intercom.FindTeamRequest} request - * @param {Teams.RequestOptions} requestOptions - Request-specific configuration. + * @param {TeamsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -168,40 +104,38 @@ export class Teams { */ public find( request: Intercom.FindTeamRequest, - requestOptions?: Teams.RequestOptions, + requestOptions?: TeamsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindTeamRequest, - requestOptions?: Teams.RequestOptions, + requestOptions?: TeamsClient.RequestOptions, ): Promise> { const { team_id: teamId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `teams/${encodeURIComponent(teamId)}`, + `teams/${core.url.encodePathParam(teamId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Team, rawResponse: _response.rawResponse }; @@ -225,32 +159,6 @@ export class Teams { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /teams/{team_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/teams/{team_id}"); } } diff --git a/src/api/resources/teams/client/index.ts b/src/api/resources/teams/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/teams/client/index.ts +++ b/src/api/resources/teams/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/teams/client/requests/FindTeamRequest.ts b/src/api/resources/teams/client/requests/FindTeamRequest.ts index c2a2151a..8902bc93 100644 --- a/src/api/resources/teams/client/requests/FindTeamRequest.ts +++ b/src/api/resources/teams/client/requests/FindTeamRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindTeamRequest { - /** - * The unique identifier of a given team. - */ + /** The unique identifier of a given team. */ team_id: string; } diff --git a/src/api/resources/teams/client/requests/index.ts b/src/api/resources/teams/client/requests/index.ts index 38be3714..0cc78a95 100644 --- a/src/api/resources/teams/client/requests/index.ts +++ b/src/api/resources/teams/client/requests/index.ts @@ -1 +1 @@ -export { type FindTeamRequest } from "./FindTeamRequest"; +export type { FindTeamRequest } from "./FindTeamRequest.js"; diff --git a/src/api/resources/teams/index.ts b/src/api/resources/teams/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/teams/index.ts +++ b/src/api/resources/teams/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/teams/types/Team.ts b/src/api/resources/teams/types/Team.ts index 698c89c9..8b038649 100644 --- a/src/api/resources/teams/types/Team.ts +++ b/src/api/resources/teams/types/Team.ts @@ -1,20 +1,22 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Teams are groups of admins in Intercom. */ export interface Team { /** Value is always "team" */ - type: "team"; + type?: string; /** The id of the team */ - id: string; + id?: string; /** The name of the team */ - name: string; + name?: string; /** The list of admin IDs that are a part of the team. */ - admin_ids: number[]; + admin_ids?: number[]; admin_priority_level?: Intercom.AdminPriorityLevel; + /** The assignment limit for the team. This field is only present when the team's distribution type is load balanced. */ + assignment_limit?: number; + /** Describes how assignments are distributed among the team members */ + distribution_method?: string; } diff --git a/src/api/resources/teams/types/index.ts b/src/api/resources/teams/types/index.ts index e3645596..bc100e99 100644 --- a/src/api/resources/teams/types/index.ts +++ b/src/api/resources/teams/types/index.ts @@ -1 +1 @@ -export * from "./Team"; +export * from "./Team.js"; diff --git a/src/api/resources/ticketStates/client/Client.ts b/src/api/resources/ticketStates/client/Client.ts new file mode 100644 index 00000000..58ed8ebf --- /dev/null +++ b/src/api/resources/ticketStates/client/Client.ts @@ -0,0 +1,92 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; + +export declare namespace TicketStatesClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your ticket states + */ +export class TicketStatesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketStatesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can get a list of all ticket states for a workspace. + * + * @param {TicketStatesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.ticketStates.listTicketStates() + */ + public listTicketStates( + requestOptions?: TicketStatesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listTicketStates(requestOptions)); + } + + private async __listTicketStates( + requestOptions?: TicketStatesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "ticket_states", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.TicketStateList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ticket_states"); + } +} diff --git a/src/api/resources/ticketStates/client/index.ts b/src/api/resources/ticketStates/client/index.ts new file mode 100644 index 00000000..cb0ff5c3 --- /dev/null +++ b/src/api/resources/ticketStates/client/index.ts @@ -0,0 +1 @@ +export {}; diff --git a/src/api/resources/ticketStates/index.ts b/src/api/resources/ticketStates/index.ts new file mode 100644 index 00000000..914b8c3c --- /dev/null +++ b/src/api/resources/ticketStates/index.ts @@ -0,0 +1 @@ +export * from "./client/index.js"; diff --git a/src/api/resources/ticketTypes/client/Client.ts b/src/api/resources/ticketTypes/client/Client.ts index f4909e81..8649ba80 100644 --- a/src/api/resources/ticketTypes/client/Client.ts +++ b/src/api/resources/ticketTypes/client/Client.ts @@ -1,128 +1,75 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; -import { Attributes } from "../resources/attributes/client/Client"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; +import { AttributesClient } from "../resources/attributes/client/Client.js"; -export declare namespace TicketTypes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketTypesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your ticket types */ -export class TicketTypes { - protected _attributes: Attributes | undefined; +export class TicketTypesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + protected _attributes: AttributesClient | undefined; - constructor(protected readonly _options: TicketTypes.Options = {}) {} + constructor(options: TicketTypesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } - public get attributes(): Attributes { - return (this._attributes ??= new Attributes(this._options)); + public get attributes(): AttributesClient { + return (this._attributes ??= new AttributesClient(this._options)); } /** * You can get a list of all ticket types for a workspace. * - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * * @example * await client.ticketTypes.list() */ - public list(requestOptions?: TicketTypes.RequestOptions): core.HttpResponsePromise { + public list(requestOptions?: TicketTypesClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); } private async __list( - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ticket_types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TicketTypeList, rawResponse: _response.rawResponse }; @@ -144,21 +91,7 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ticket_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ticket_types"); } /** @@ -169,7 +102,7 @@ export class TicketTypes { * > For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) * * @param {Intercom.CreateTicketTypeRequest} request - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -182,44 +115,44 @@ export class TicketTypes { * }) */ public create( - request: Intercom.CreateTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): core.HttpResponsePromise { + request?: Intercom.CreateTicketTypeRequest, + requestOptions?: TicketTypesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( - request: Intercom.CreateTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): Promise> { + request?: Intercom.CreateTicketTypeRequest, + requestOptions?: TicketTypesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ticket_types", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.TicketType, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.TicketType | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -238,28 +171,14 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /ticket_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ticket_types"); } /** * You can fetch the details of a single ticket type. * * @param {Intercom.FindTicketTypeRequest} request - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -270,43 +189,41 @@ export class TicketTypes { */ public get( request: Intercom.FindTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: TicketTypesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); } private async __get( request: Intercom.FindTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): Promise> { + requestOptions?: TicketTypesClient.RequestOptions, + ): Promise> { const { ticket_type_id: ticketTypeId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.TicketType, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.TicketType | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -325,23 +242,12 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /ticket_types/{ticket_type_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/ticket_types/{ticket_type_id}", + ); } /** @@ -353,7 +259,7 @@ export class TicketTypes { * > For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) * * @param {Intercom.UpdateTicketTypeRequest} request - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -365,44 +271,44 @@ export class TicketTypes { */ public update( request: Intercom.UpdateTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: TicketTypesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, - ): Promise> { + requestOptions?: TicketTypesClient.RequestOptions, + ): Promise> { const { ticket_type_id: ticketTypeId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.TicketType, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.TicketType | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -421,34 +327,11 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /ticket_types/{ticket_type_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/ticket_types/{ticket_type_id}", + ); } } diff --git a/src/api/resources/ticketTypes/client/index.ts b/src/api/resources/ticketTypes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/ticketTypes/client/index.ts +++ b/src/api/resources/ticketTypes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/ticketTypes/client/requests/FindTicketTypeRequest.ts b/src/api/resources/ticketTypes/client/requests/FindTicketTypeRequest.ts index 968dd46d..84a6e0ef 100644 --- a/src/api/resources/ticketTypes/client/requests/FindTicketTypeRequest.ts +++ b/src/api/resources/ticketTypes/client/requests/FindTicketTypeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindTicketTypeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; } diff --git a/src/api/resources/ticketTypes/client/requests/UpdateTicketTypeRequest.ts b/src/api/resources/ticketTypes/client/requests/UpdateTicketTypeRequest.ts index 55572ebe..1d2bd489 100644 --- a/src/api/resources/ticketTypes/client/requests/UpdateTicketTypeRequest.ts +++ b/src/api/resources/ticketTypes/client/requests/UpdateTicketTypeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,9 +8,7 @@ * } */ export interface UpdateTicketTypeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; /** The name of the ticket type. */ name?: string; @@ -29,13 +25,11 @@ export interface UpdateTicketTypeRequest { } export namespace UpdateTicketTypeRequest { - /** - * Category of the Ticket Type. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket Type. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/ticketTypes/client/requests/index.ts b/src/api/resources/ticketTypes/client/requests/index.ts index 7b66e378..8eee27c4 100644 --- a/src/api/resources/ticketTypes/client/requests/index.ts +++ b/src/api/resources/ticketTypes/client/requests/index.ts @@ -1,3 +1,2 @@ -export { type CreateTicketTypeRequest } from "./CreateTicketTypeRequest"; -export { type FindTicketTypeRequest } from "./FindTicketTypeRequest"; -export { type UpdateTicketTypeRequest } from "./UpdateTicketTypeRequest"; +export type { FindTicketTypeRequest } from "./FindTicketTypeRequest.js"; +export type { UpdateTicketTypeRequest } from "./UpdateTicketTypeRequest.js"; diff --git a/src/api/resources/ticketTypes/index.ts b/src/api/resources/ticketTypes/index.ts index 33a87f10..9eb1192d 100644 --- a/src/api/resources/ticketTypes/index.ts +++ b/src/api/resources/ticketTypes/index.ts @@ -1,2 +1,2 @@ -export * from "./client"; -export * from "./resources"; +export * from "./client/index.js"; +export * from "./resources/index.js"; diff --git a/src/api/resources/ticketTypes/resources/attributes/client/Client.ts b/src/api/resources/ticketTypes/resources/attributes/client/Client.ts index 32ac1e89..0f27dcd1 100644 --- a/src/api/resources/ticketTypes/resources/attributes/client/Client.ts +++ b/src/api/resources/ticketTypes/resources/attributes/client/Client.ts @@ -1,82 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Attributes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace AttributesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Attributes { - constructor(protected readonly _options: Attributes.Options = {}) {} +export class AttributesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AttributesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can create a new attribute for a ticket type. * * @param {Intercom.ticketTypes.CreateTicketTypeAttributeRequest} request - * @param {Attributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {AttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -91,44 +41,47 @@ export class Attributes { */ public create( request: Intercom.ticketTypes.CreateTicketTypeAttributeRequest, - requestOptions?: Attributes.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: AttributesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.ticketTypes.CreateTicketTypeAttributeRequest, - requestOptions?: Attributes.RequestOptions, - ): Promise> { + requestOptions?: AttributesClient.RequestOptions, + ): Promise> { const { ticket_type_id: ticketTypeId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}/attributes`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}/attributes`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.TicketTypeAttribute, rawResponse: _response.rawResponse }; + return { + data: _response.body as Intercom.TicketTypeAttribute | undefined, + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { @@ -147,30 +100,19 @@ export class Attributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /ticket_types/{ticket_type_id}/attributes.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/ticket_types/{ticket_type_id}/attributes", + ); } /** * You can update an existing attribute for a ticket type. * * @param {Intercom.ticketTypes.UpdateTicketTypeAttributeRequest} request - * @param {Attributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {AttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -183,44 +125,47 @@ export class Attributes { */ public update( request: Intercom.ticketTypes.UpdateTicketTypeAttributeRequest, - requestOptions?: Attributes.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: AttributesClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.ticketTypes.UpdateTicketTypeAttributeRequest, - requestOptions?: Attributes.RequestOptions, - ): Promise> { + requestOptions?: AttributesClient.RequestOptions, + ): Promise> { const { ticket_type_id: ticketTypeId, attribute_id: attributeId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}/attributes/${encodeURIComponent(attributeId)}`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}/attributes/${core.url.encodePathParam(attributeId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.TicketTypeAttribute, rawResponse: _response.rawResponse }; + return { + data: _response.body as Intercom.TicketTypeAttribute | undefined, + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { @@ -239,34 +184,11 @@ export class Attributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /ticket_types/{ticket_type_id}/attributes/{attribute_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/ticket_types/{ticket_type_id}/attributes/{attribute_id}", + ); } } diff --git a/src/api/resources/ticketTypes/resources/attributes/client/index.ts b/src/api/resources/ticketTypes/resources/attributes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/ticketTypes/resources/attributes/client/index.ts +++ b/src/api/resources/ticketTypes/resources/attributes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/ticketTypes/resources/attributes/client/requests/CreateTicketTypeAttributeRequest.ts b/src/api/resources/ticketTypes/resources/attributes/client/requests/CreateTicketTypeAttributeRequest.ts index 0a9604c1..6dbf0ac2 100644 --- a/src/api/resources/ticketTypes/resources/attributes/client/requests/CreateTicketTypeAttributeRequest.ts +++ b/src/api/resources/ticketTypes/resources/attributes/client/requests/CreateTicketTypeAttributeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -13,9 +11,7 @@ * } */ export interface CreateTicketTypeAttributeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; /** The name of the ticket type attribute */ name: string; @@ -40,10 +36,7 @@ export interface CreateTicketTypeAttributeRequest { } export namespace CreateTicketTypeAttributeRequest { - /** - * The data type of the attribute - */ - export type DataType = "string" | "list" | "integer" | "decimal" | "boolean" | "datetime" | "files"; + /** The data type of the attribute */ export const DataType = { String: "string", List: "list", @@ -53,4 +46,5 @@ export namespace CreateTicketTypeAttributeRequest { Datetime: "datetime", Files: "files", } as const; + export type DataType = (typeof DataType)[keyof typeof DataType]; } diff --git a/src/api/resources/ticketTypes/resources/attributes/client/requests/UpdateTicketTypeAttributeRequest.ts b/src/api/resources/ticketTypes/resources/attributes/client/requests/UpdateTicketTypeAttributeRequest.ts index a7324b1e..8fda5439 100644 --- a/src/api/resources/ticketTypes/resources/attributes/client/requests/UpdateTicketTypeAttributeRequest.ts +++ b/src/api/resources/ticketTypes/resources/attributes/client/requests/UpdateTicketTypeAttributeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -11,13 +9,9 @@ * } */ export interface UpdateTicketTypeAttributeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; - /** - * The unique identifier for the ticket type attribute which is given by Intercom. - */ + /** The unique identifier for the ticket type attribute which is given by Intercom. */ attribute_id: string; /** The name of the ticket type attribute */ name?: string; diff --git a/src/api/resources/ticketTypes/resources/attributes/client/requests/index.ts b/src/api/resources/ticketTypes/resources/attributes/client/requests/index.ts index b2d37564..2a2ffb63 100644 --- a/src/api/resources/ticketTypes/resources/attributes/client/requests/index.ts +++ b/src/api/resources/ticketTypes/resources/attributes/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type CreateTicketTypeAttributeRequest } from "./CreateTicketTypeAttributeRequest"; -export { type UpdateTicketTypeAttributeRequest } from "./UpdateTicketTypeAttributeRequest"; +export type { CreateTicketTypeAttributeRequest } from "./CreateTicketTypeAttributeRequest.js"; +export type { UpdateTicketTypeAttributeRequest } from "./UpdateTicketTypeAttributeRequest.js"; diff --git a/src/api/resources/ticketTypes/resources/attributes/index.ts b/src/api/resources/ticketTypes/resources/attributes/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/ticketTypes/resources/attributes/index.ts +++ b/src/api/resources/ticketTypes/resources/attributes/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/ticketTypes/resources/index.ts b/src/api/resources/ticketTypes/resources/index.ts index 85faeec8..f11460cf 100644 --- a/src/api/resources/ticketTypes/resources/index.ts +++ b/src/api/resources/ticketTypes/resources/index.ts @@ -1,2 +1,2 @@ -export * as attributes from "./attributes"; -export * from "./attributes/client/requests"; +export * from "./attributes/client/requests/index.js"; +export * as attributes from "./attributes/index.js"; diff --git a/src/api/resources/tickets/client/Client.ts b/src/api/resources/tickets/client/Client.ts index a47554f7..d7456f7f 100644 --- a/src/api/resources/tickets/client/Client.ts +++ b/src/api/resources/tickets/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Tickets { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your tickets */ -export class Tickets { - constructor(protected readonly _options: Tickets.Options = {}) {} +export class TicketsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. * * @param {Intercom.ReplyToTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} @@ -92,7 +42,7 @@ export class Tickets { * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d619d8a68186f43bafe82" + * intercom_user_id: "6762f2971bb69f9f2193bc49" * } * }) * @@ -116,10 +66,10 @@ export class Tickets { * admin_id: "3156780", * reply_options: [{ * text: "Yes", - * uuid: "22d6d1f4-1a19-41d0-94c2-e54031f78aca" + * uuid: "0df48b85-9a93-4c66-a167-753eff0baaec" * }, { * text: "No", - * uuid: "fbc3dbe0-ec0c-4fb6-826d-e19127191906" + * uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938" * }] * } * }) @@ -131,47 +81,47 @@ export class Tickets { * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d61a68a68186f43bafe85" + * intercom_user_id: "6762f2a41bb69f9f2193bc4c" * } * }) */ public reply( request: Intercom.ReplyToTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__reply(request, requestOptions)); } private async __reply( request: Intercom.ReplyToTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { const { ticket_id: ticketId, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}/reply`, + `tickets/${core.url.encodePathParam(ticketId)}/reply`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TicketReply, rawResponse: _response.rawResponse }; @@ -197,28 +147,14 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/{ticket_id}/reply."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/{ticket_id}/reply"); } /** * You can create a new ticket. * * @param {Intercom.CreateTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -226,53 +162,49 @@ export class Tickets { * await client.tickets.create({ * ticket_type_id: "1234", * contacts: [{ - * id: "667d61b78a68186f43bafe8d" - * }], - * ticket_attributes: { - * "_default_title_": "example", - * "_default_description_": "there is a problem" - * } + * id: "6762f2d81bb69f9f2193bc54" + * }] * }) */ public create( request: Intercom.CreateTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: TicketsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); } private async __create( request: Intercom.CreateTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): Promise> { + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tickets", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Ticket, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Ticket | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -291,28 +223,93 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets"); + } + + /** + * Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job. + * + * @param {Intercom.EnqueueCreateTicketRequest} request + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.BadRequestError} + * @throws {@link Intercom.UnauthorizedError} + * + * @example + * await client.tickets.enqueueCreateTicket({ + * ticket_type_id: "1234", + * contacts: [{ + * id: "6762f2d81bb69f9f2193bc54" + * }] + * }) + */ + public enqueueCreateTicket( + request: Intercom.EnqueueCreateTicketRequest, + requestOptions?: TicketsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__enqueueCreateTicket(request, requestOptions)); + } + + private async __enqueueCreateTicket( + request: Intercom.EnqueueCreateTicketRequest, + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "tickets/enqueue", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.Jobs, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/enqueue"); } /** * You can fetch the details of a single ticket. * * @param {Intercom.FindTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -323,43 +320,41 @@ export class Tickets { */ public get( request: Intercom.FindTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: TicketsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); } private async __get( request: Intercom.FindTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): Promise> { + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { const { ticket_id: ticketId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}`, + `tickets/${core.url.encodePathParam(ticketId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Ticket, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Ticket | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -378,29 +373,16 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tickets/{ticket_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tickets/{ticket_id}"); } /** * You can update a ticket. * * @param {Intercom.UpdateTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * + * @throws {@link Intercom.BadRequestError} * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * @@ -411,13 +393,11 @@ export class Tickets { * "_default_title_": "example", * "_default_description_": "there is a problem" * }, - * state: "in_progress", + * ticket_state_id: "123", * open: true, * snoozed_until: 1673609604, - * assignment: { - * admin_id: "991267883", - * assignee_id: "991267885" - * } + * admin_id: 991268011, + * assignee_id: "123" * }) * * @example @@ -427,71 +407,63 @@ export class Tickets { * "_default_title_": "example", * "_default_description_": "there is a problem" * }, - * state: "in_progress", - * assignment: { - * admin_id: "123", - * assignee_id: "991267893" - * } + * ticket_state_id: "123", + * admin_id: 991268011, + * assignee_id: "123" * }) * * @example * await client.tickets.update({ * ticket_id: "ticket_id", - * ticket_attributes: { - * "_default_title_": "example", - * "_default_description_": "there is a problem" - * }, - * state: "in_progress", - * assignment: { - * admin_id: "991267899", - * assignee_id: "456" - * } + * ticket_state_id: "123" * }) */ public update( request: Intercom.UpdateTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: TicketsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateTicketRequest, - requestOptions?: Tickets.RequestOptions, - ): Promise> { + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { const { ticket_id: ticketId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}`, + `tickets/${core.url.encodePathParam(ticketId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Ticket, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Ticket | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { switch (_response.error.statusCode) { + case 400: + throw new Intercom.BadRequestError(_response.error.body as unknown, _response.rawResponse); case 401: throw new Intercom.UnauthorizedError( _response.error.body as Intercom.Error_, @@ -508,21 +480,81 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /tickets/{ticket_id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/tickets/{ticket_id}"); + } + + /** + * You can delete a ticket using the Intercom provided ID. + * + * @param {Intercom.DeleteTicketRequest} request + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.UnauthorizedError} + * @throws {@link Intercom.NotFoundError} + * + * @example + * await client.tickets.deleteTicket({ + * ticket_id: "ticket_id" + * }) + */ + public deleteTicket( + request: Intercom.DeleteTicketRequest, + requestOptions?: TicketsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteTicket(request, requestOptions)); + } + + private async __deleteTicket( + request: Intercom.DeleteTicketRequest, + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { + const { ticket_id: ticketId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `tickets/${core.url.encodePathParam(ticketId)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.DeleteTicketResponse, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.UnauthorizedError( + _response.error.body as Intercom.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/tickets/{ticket_id}"); } /** @@ -548,14 +580,15 @@ export class Tickets { * ### Accepted Fields * * Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as `created_at` accepts a date, the `value` cannot be a string such as `"foobar"`). + * The `source.body` field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a `"I need support"` body - the query should contain a `=` operator with the value `"support"` for such conversation to be returned. A query with a `=` operator and a `"need support"` value will not yield a result. * * | Field | Type | * | :---------------------------------------- | :--------------------------------------------------------------------------------------- | * | id | String | * | created_at | Date (UNIX timestamp) | * | updated_at | Date (UNIX timestamp) | - * | _default_title_ | String | - * | _default_description_ | String | + * | title | String | + * | description | String | * | category | String | * | ticket_type_id | String | * | contact_ids | String | @@ -567,6 +600,13 @@ export class Tickets { * | snoozed_until | Date (UNIX timestamp) | * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | * + * {% admonition type="info" name="Searching by Category" %} + * When searching for tickets by the **`category`** field, specific terms must be used instead of the category names: + * * For **Customer** category tickets, use the term `request`. + * * For **Back-office** category tickets, use the term `task`. + * * For **Tracker** category tickets, use the term `tracker`. + * {% /admonition %} + * * ### Accepted Operators * * {% admonition type="info" name="Searching based on `created_at`" %} @@ -589,7 +629,7 @@ export class Tickets { * | $ | String | Ends With | * * @param {Intercom.SearchRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.tickets.search({ @@ -608,36 +648,35 @@ export class Tickets { */ public async search( request: Intercom.SearchRequest, - requestOptions?: Tickets.RequestOptions, - ): Promise> { + requestOptions?: TicketsClient.RequestOptions, + ): Promise> { const list = core.HttpResponsePromise.interceptFunction( async (request: Intercom.SearchRequest): Promise> => { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tickets/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: - requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.TicketList, rawResponse: _response.rawResponse }; @@ -649,28 +688,19 @@ export class Tickets { rawResponse: _response.rawResponse, }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/search"); }, ); const dataWithRawResponse = await list(request).withRawResponse(); - return new core.Pageable({ + return new core.Page({ response: dataWithRawResponse.data, rawResponse: dataWithRawResponse.rawResponse, - hasNextPage: (response) => response?.pages?.next?.starting_after != null, + hasNextPage: (response) => + response?.pages?.next?.starting_after != null && + !( + typeof response?.pages?.next?.starting_after === "string" && + response?.pages?.next?.starting_after === "" + ), getItems: (response) => response?.tickets ?? [], loadPage: (response) => { return list( @@ -679,16 +709,4 @@ export class Tickets { }, }); } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; - } } diff --git a/src/api/resources/tickets/client/index.ts b/src/api/resources/tickets/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/tickets/client/index.ts +++ b/src/api/resources/tickets/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/tickets/client/requests/CreateTicketRequest.ts b/src/api/resources/tickets/client/requests/CreateTicketRequest.ts new file mode 100644 index 00000000..496df31d --- /dev/null +++ b/src/api/resources/tickets/client/requests/CreateTicketRequest.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; + +/** + * @example + * { + * ticket_type_id: "1234", + * contacts: [{ + * id: "6762f2d81bb69f9f2193bc54" + * }] + * } + */ +export interface CreateTicketRequest extends Intercom.CreateTicketRequestBody { + /** Option to disable notifications when a Ticket is created. */ + skip_notifications?: boolean; +} diff --git a/src/api/resources/tickets/client/requests/DeleteTicketRequest.ts b/src/api/resources/tickets/client/requests/DeleteTicketRequest.ts new file mode 100644 index 00000000..e5b5dee8 --- /dev/null +++ b/src/api/resources/tickets/client/requests/DeleteTicketRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * ticket_id: "ticket_id" + * } + */ +export interface DeleteTicketRequest { + /** The unique identifier for the ticket which is given by Intercom. */ + ticket_id: string; +} diff --git a/src/api/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts b/src/api/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts new file mode 100644 index 00000000..f7969901 --- /dev/null +++ b/src/api/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../index.js"; + +/** + * @example + * { + * ticket_type_id: "1234", + * contacts: [{ + * id: "6762f2d81bb69f9f2193bc54" + * }] + * } + */ +export interface EnqueueCreateTicketRequest extends Intercom.CreateTicketRequestBody { + /** Option to disable notifications when a Ticket is created. */ + skip_notifications?: boolean; +} diff --git a/src/api/resources/tickets/client/requests/FindTicketRequest.ts b/src/api/resources/tickets/client/requests/FindTicketRequest.ts index 450d0725..f3f1e814 100644 --- a/src/api/resources/tickets/client/requests/FindTicketRequest.ts +++ b/src/api/resources/tickets/client/requests/FindTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindTicketRequest { - /** - * The unique identifier for the ticket which is given by Intercom. - */ + /** The unique identifier for the ticket which is given by Intercom. */ ticket_id: string; } diff --git a/src/api/resources/tickets/client/requests/ReplyToTicketRequest.ts b/src/api/resources/tickets/client/requests/ReplyToTicketRequest.ts index c00dcfdd..b67d7011 100644 --- a/src/api/resources/tickets/client/requests/ReplyToTicketRequest.ts +++ b/src/api/resources/tickets/client/requests/ReplyToTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../../../../index.js"; /** * @example @@ -12,7 +10,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d619d8a68186f43bafe82" + * intercom_user_id: "6762f2971bb69f9f2193bc49" * } * } * @@ -36,10 +34,10 @@ import * as Intercom from "../../../../index"; * admin_id: "3156780", * reply_options: [{ * text: "Yes", - * uuid: "22d6d1f4-1a19-41d0-94c2-e54031f78aca" + * uuid: "0df48b85-9a93-4c66-a167-753eff0baaec" * }, { * text: "No", - * uuid: "fbc3dbe0-ec0c-4fb6-826d-e19127191906" + * uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938" * }] * } * } @@ -51,7 +49,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d61a68a68186f43bafe85" + * intercom_user_id: "6762f2a41bb69f9f2193bc4c" * } * } * @@ -62,7 +60,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d619d8a68186f43bafe82" + * intercom_user_id: "6762f2971bb69f9f2193bc49" * } * } * @@ -73,7 +71,7 @@ import * as Intercom from "../../../../index"; * message_type: "comment", * type: "user", * body: "Thanks again :)", - * intercom_user_id: "667d619d8a68186f43bafe82" + * intercom_user_id: "6762f2971bb69f9f2193bc49" * } * } */ diff --git a/src/api/resources/tickets/client/requests/UpdateTicketRequest.ts b/src/api/resources/tickets/client/requests/UpdateTicketRequest.ts index 99555fa9..7ba6219a 100644 --- a/src/api/resources/tickets/client/requests/UpdateTicketRequest.ts +++ b/src/api/resources/tickets/client/requests/UpdateTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,13 +8,11 @@ * "_default_title_": "example", * "_default_description_": "there is a problem" * }, - * state: "in_progress", + * ticket_state_id: "123", * open: true, * snoozed_until: 1673609604, - * assignment: { - * admin_id: "991267883", - * assignee_id: "991267885" - * } + * admin_id: 991268011, + * assignee_id: "123" * } * * @example @@ -26,11 +22,9 @@ * "_default_title_": "example", * "_default_description_": "there is a problem" * }, - * state: "in_progress", - * assignment: { - * admin_id: "123", - * assignee_id: "991267893" - * } + * ticket_state_id: "123", + * admin_id: 991268011, + * assignee_id: "123" * } * * @example @@ -40,46 +34,34 @@ * "_default_title_": "example", * "_default_description_": "there is a problem" * }, - * state: "in_progress", - * assignment: { - * admin_id: "991267899", - * assignee_id: "456" - * } + * ticket_state_id: "123", + * admin_id: 991268011, + * assignee_id: "123" + * } + * + * @example + * { + * ticket_id: "ticket_id", + * ticket_state_id: "123" * } */ export interface UpdateTicketRequest { - /** - * The unique identifier for the ticket which is given by Intercom - */ + /** The unique identifier for the ticket which is given by Intercom */ ticket_id: string; /** The attributes set on the ticket. */ ticket_attributes?: Record; - /** The state of the ticket. */ - state?: UpdateTicketRequest.State; + /** The ID of the ticket state associated with the ticket type. */ + ticket_state_id?: string; + /** The ID of the company that the ticket is associated with. The unique identifier for the company which is given by Intercom. Set to nil to remove company. */ + company_id?: string; /** Specify if a ticket is open. Set to false to close a ticket. Closing a ticket will also unsnooze it. */ open?: boolean; /** Specify whether the ticket is visible to users. */ is_shared?: boolean; /** The time you want the ticket to reopen. */ snoozed_until?: number; - assignment?: UpdateTicketRequest.Assignment; -} - -export namespace UpdateTicketRequest { - /** - * The state of the ticket. - */ - export type State = "in_progress" | "waiting_on_customer" | "resolved"; - export const State = { - InProgress: "in_progress", - WaitingOnCustomer: "waiting_on_customer", - Resolved: "resolved", - } as const; - - export interface Assignment { - /** The ID of the admin performing the action. */ - admin_id?: string; - /** The ID of the admin or team to which the ticket is assigned. Set this 0 to unassign it. */ - assignee_id?: string; - } + /** The ID of the admin performing ticket update. Needed for workflows execution and attributing actions to specific admins. */ + admin_id?: number; + /** The ID of the admin or team to which the ticket is assigned. Set this 0 to unassign it. */ + assignee_id?: string; } diff --git a/src/api/resources/tickets/client/requests/index.ts b/src/api/resources/tickets/client/requests/index.ts index 23ce5a7f..2a2313d7 100644 --- a/src/api/resources/tickets/client/requests/index.ts +++ b/src/api/resources/tickets/client/requests/index.ts @@ -1,3 +1,6 @@ -export { type ReplyToTicketRequest } from "./ReplyToTicketRequest"; -export { type FindTicketRequest } from "./FindTicketRequest"; -export { type UpdateTicketRequest } from "./UpdateTicketRequest"; +export type { CreateTicketRequest } from "./CreateTicketRequest.js"; +export type { DeleteTicketRequest } from "./DeleteTicketRequest.js"; +export type { EnqueueCreateTicketRequest } from "./EnqueueCreateTicketRequest.js"; +export type { FindTicketRequest } from "./FindTicketRequest.js"; +export type { ReplyToTicketRequest } from "./ReplyToTicketRequest.js"; +export type { UpdateTicketRequest } from "./UpdateTicketRequest.js"; diff --git a/src/api/resources/tickets/index.ts b/src/api/resources/tickets/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/tickets/index.ts +++ b/src/api/resources/tickets/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/tickets/types/DeleteTicketResponse.ts b/src/api/resources/tickets/types/DeleteTicketResponse.ts new file mode 100644 index 00000000..cdad7f2d --- /dev/null +++ b/src/api/resources/tickets/types/DeleteTicketResponse.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Response when a ticket is deleted. + */ +export interface DeleteTicketResponse { + /** The unique identifier for the ticket. */ + id?: string; + /** always ticket */ + object?: "ticket"; + /** Whether the ticket is deleted or not. */ + deleted?: boolean; +} diff --git a/src/api/resources/tickets/types/Ticket.ts b/src/api/resources/tickets/types/Ticket.ts index 4962e861..8582aca5 100644 --- a/src/api/resources/tickets/types/Ticket.ts +++ b/src/api/resources/tickets/types/Ticket.ts @@ -1,26 +1,23 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Tickets are how you track requests from your users. */ export interface Ticket { /** Always ticket */ - type: "ticket"; + type?: "ticket"; /** The unique identifier for the ticket which is given by Intercom. */ - id: string; + id?: string; /** The ID of the Ticket used in the Intercom Inbox and Messenger. Do not use ticket_id for API queries. */ - ticket_id: string; + ticket_id?: string; /** Category of the Ticket. */ - category: Ticket.Category; - ticket_attributes: Intercom.TicketCustomAttributes; - /** The state the ticket is currently in */ - ticket_state: Ticket.TicketState; - ticket_type: Intercom.TicketType; - contacts: Intercom.TicketContacts; + category?: Ticket.Category; + ticket_attributes?: Intercom.TicketCustomAttributes; + ticket_state?: Intercom.TicketState; + ticket_type?: Intercom.TicketType; + contacts?: Intercom.TicketContacts; /** The id representing the admin assigned to the ticket. */ admin_assignee_id?: string; /** The id representing the team assigned to the ticket. */ @@ -37,30 +34,14 @@ export interface Ticket { ticket_parts?: Intercom.TicketParts; /** Whether or not the ticket is shared with the customer. */ is_shared?: boolean; - /** The state the ticket is currently in, in a human readable form - visible in Intercom */ - ticket_state_internal_label?: string; - /** The state the ticket is currently in, in a human readable form - visible to customers, in the messenger, email and tickets portal. */ - ticket_state_external_label?: string; } export namespace Ticket { - /** - * Category of the Ticket. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; - /** - * The state the ticket is currently in - */ - export type TicketState = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; - export const TicketState = { - Submitted: "submitted", - InProgress: "in_progress", - WaitingOnCustomer: "waiting_on_customer", - Resolved: "resolved", - } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/tickets/types/TicketContacts.ts b/src/api/resources/tickets/types/TicketContacts.ts index cc70ccbb..1d775525 100644 --- a/src/api/resources/tickets/types/TicketContacts.ts +++ b/src/api/resources/tickets/types/TicketContacts.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The list of contacts affected by a ticket. */ export interface TicketContacts { /** always contact.list */ - type: "contact.list"; + type?: "contact.list"; /** The list of contacts affected by this ticket. */ - contacts: Intercom.ContactReference[]; + contacts?: Intercom.ContactReference[]; } diff --git a/src/api/resources/tickets/types/TicketPart.ts b/src/api/resources/tickets/types/TicketPart.ts index ecfb0528..ffe19d95 100644 --- a/src/api/resources/tickets/types/TicketPart.ts +++ b/src/api/resources/tickets/types/TicketPart.ts @@ -1,27 +1,25 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A Ticket Part represents a message in the ticket. */ export interface TicketPart { /** Always ticket_part */ - type: "ticket_part"; + type?: string; /** The id representing the ticket part. */ - id: string; + id?: string; /** The type of ticket part. */ - part_type: string; + part_type?: string; /** The message body, which may contain HTML. */ body?: string; /** The previous state of the ticket. */ previous_ticket_state?: TicketPart.PreviousTicketState; /** The state of the ticket. */ - ticket_state: TicketPart.TicketState; + ticket_state?: TicketPart.TicketState; /** The time the ticket part was created. */ - created_at: number; + created_at?: number; /** The last time the ticket part was updated. */ updated_at?: number; /** The id of the admin that was assigned the ticket by this ticket_part (null if there has been no change in assignment.) */ @@ -33,27 +31,79 @@ export interface TicketPart { external_id?: string; /** Whether or not the ticket part has been redacted. */ redacted?: boolean; + /** The app package code if this part was created via API. Note this field won't show if the part was not created via API. */ + app_package_code?: string; + /** The updated attribute data of the ticket part. Only present for attribute update parts. */ + updated_attribute_data?: TicketPart.UpdatedAttributeData; } export namespace TicketPart { - /** - * The previous state of the ticket. - */ - export type PreviousTicketState = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + /** The previous state of the ticket. */ export const PreviousTicketState = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; - /** - * The state of the ticket. - */ - export type TicketState = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + export type PreviousTicketState = (typeof PreviousTicketState)[keyof typeof PreviousTicketState]; + /** The state of the ticket. */ export const TicketState = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; + export type TicketState = (typeof TicketState)[keyof typeof TicketState]; + + /** + * The updated attribute data of the ticket part. Only present for attribute update parts. + */ + export interface UpdatedAttributeData { + /** Information about the attribute that was updated. */ + attribute: UpdatedAttributeData.Attribute; + /** The new value of the attribute. */ + value: UpdatedAttributeData.Value; + } + + export namespace UpdatedAttributeData { + /** + * Information about the attribute that was updated. + */ + export interface Attribute { + /** The type of the object. Always 'attribute'. */ + type: "attribute"; + /** The unique identifier of the attribute. */ + id: string; + /** The human-readable name of the attribute. */ + label: string; + } + + /** + * The new value of the attribute. + */ + export interface Value { + /** The type of the object. Always 'value'. */ + type: "value"; + id: Value.Id; + label: Value.Label; + } + + export namespace Value { + export type Id = + /** + * The value for text/number/decimal/boolean/date attributes, or the ID of the list option for list attributes. */ + | string + | undefined + /** + * Array of file IDs for file attributes. */ + | number[]; + export type Label = + /** + * The display value for text/number/decimal/boolean/date/list attributes. */ + | string + /** + * Array of file names for file attributes. */ + | string[]; + } + } } diff --git a/src/api/resources/tickets/types/TicketState.ts b/src/api/resources/tickets/types/TicketState.ts new file mode 100644 index 00000000..beef89c7 --- /dev/null +++ b/src/api/resources/tickets/types/TicketState.ts @@ -0,0 +1,28 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * A ticket state, used to define the state of a ticket. + */ +export interface TicketState { + /** String representing the object's type. Always has the value `ticket_state`. */ + type?: string; + /** The id of the ticket state */ + id?: string; + /** The category of the ticket state */ + category?: TicketState.Category; + /** The state the ticket is currently in, in a human readable form - visible in Intercom */ + internal_label?: string; + /** The state the ticket is currently in, in a human readable form - visible to customers, in the messenger, email and tickets portal. */ + external_label?: string; +} + +export namespace TicketState { + /** The category of the ticket state */ + export const Category = { + Submitted: "submitted", + InProgress: "in_progress", + WaitingOnCustomer: "waiting_on_customer", + Resolved: "resolved", + } as const; + export type Category = (typeof Category)[keyof typeof Category]; +} diff --git a/src/api/resources/tickets/types/TicketStateDetailed.ts b/src/api/resources/tickets/types/TicketStateDetailed.ts new file mode 100644 index 00000000..df97b118 --- /dev/null +++ b/src/api/resources/tickets/types/TicketStateDetailed.ts @@ -0,0 +1,44 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * A ticket state, used to define the state of a ticket. + */ +export interface TicketStateDetailed { + /** String representing the object's type. Always has the value `ticket_state`. */ + type?: string; + /** The id of the ticket state */ + id?: string; + /** The category of the ticket state */ + category?: TicketStateDetailed.Category; + /** The state the ticket is currently in, in a human readable form - visible in Intercom */ + internal_label?: string; + /** The state the ticket is currently in, in a human readable form - visible to customers, in the messenger, email and tickets portal. */ + external_label?: string; + /** Whether the ticket state is archived */ + archived?: boolean; + /** A list of ticket types associated with a given ticket state. */ + ticket_types?: TicketStateDetailed.TicketTypes; +} + +export namespace TicketStateDetailed { + /** The category of the ticket state */ + export const Category = { + Submitted: "submitted", + InProgress: "in_progress", + WaitingOnCustomer: "waiting_on_customer", + Resolved: "resolved", + } as const; + export type Category = (typeof Category)[keyof typeof Category]; + + /** + * A list of ticket types associated with a given ticket state. + */ + export interface TicketTypes { + /** String representing the object's type. Always has the value `list`. */ + type?: string; + /** A list of ticket type attributes associated with a given ticket type. */ + data?: (Intercom.TicketType | undefined)[]; + } +} diff --git a/src/api/resources/tickets/types/TicketType.ts b/src/api/resources/tickets/types/TicketType.ts index ae240f82..5ad0cd5d 100644 --- a/src/api/resources/tickets/types/TicketType.ts +++ b/src/api/resources/tickets/types/TicketType.ts @@ -1,44 +1,52 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A ticket type, used to define the data fields to be captured in a ticket. */ export interface TicketType { /** String representing the object's type. Always has the value `ticket_type`. */ - type: "ticket_type"; + type?: string; /** The id representing the ticket type. */ - id: string; + id?: string; /** Category of the Ticket Type. */ - category: TicketType.Category; + category?: TicketType.Category; /** The name of the ticket type */ - name: string; + name?: string; /** The description of the ticket type */ - description: string; + description?: string; /** The icon of the ticket type */ - icon: string; + icon?: string; /** The id of the workspace that the ticket type belongs to. */ - workspace_id: string; - ticket_type_attributes: Intercom.TicketTypeAttributeList; + workspace_id?: string; + ticket_type_attributes?: Intercom.TicketTypeAttributeList; + /** A list of ticket states associated with a given ticket type. */ + ticket_states?: TicketType.TicketStates; /** Whether the ticket type is archived or not. */ - archived: boolean; + archived?: boolean; /** The date and time the ticket type was created. */ - created_at: number; + created_at?: number; /** The date and time the ticket type was last updated. */ updated_at?: number; } export namespace TicketType { - /** - * Category of the Ticket Type. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket Type. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; + export type Category = (typeof Category)[keyof typeof Category]; + + /** + * A list of ticket states associated with a given ticket type. + */ + export interface TicketStates { + /** String representing the object's type. Always has the value `list`. */ + type?: string; + /** A list of ticket states associated with a given ticket type. */ + data?: (Intercom.TicketState | undefined)[]; + } } diff --git a/src/api/resources/tickets/types/TicketsReplyRequestBody.ts b/src/api/resources/tickets/types/TicketsReplyRequestBody.ts index e6c57710..f56d4a42 100644 --- a/src/api/resources/tickets/types/TicketsReplyRequestBody.ts +++ b/src/api/resources/tickets/types/TicketsReplyRequestBody.ts @@ -1,7 +1,5 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type TicketsReplyRequestBody = Intercom.ContactReplyTicketRequest | Intercom.AdminReplyTicketRequest; diff --git a/src/api/resources/tickets/types/index.ts b/src/api/resources/tickets/types/index.ts index 2bba4510..0802fc77 100644 --- a/src/api/resources/tickets/types/index.ts +++ b/src/api/resources/tickets/types/index.ts @@ -1,5 +1,8 @@ -export * from "./TicketsReplyRequestBody"; -export * from "./Ticket"; -export * from "./TicketContacts"; -export * from "./TicketPart"; -export * from "./TicketType"; +export * from "./DeleteTicketResponse.js"; +export * from "./Ticket.js"; +export * from "./TicketContacts.js"; +export * from "./TicketPart.js"; +export * from "./TicketState.js"; +export * from "./TicketStateDetailed.js"; +export * from "./TicketsReplyRequestBody.js"; +export * from "./TicketType.js"; diff --git a/src/api/resources/unstable/client/Client.ts b/src/api/resources/unstable/client/Client.ts index d05f4c7f..3058c14f 100644 --- a/src/api/resources/unstable/client/Client.ts +++ b/src/api/resources/unstable/client/Client.ts @@ -1,209 +1,214 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import { Admins } from "../resources/admins/client/Client"; -import { AiContent } from "../resources/aiContent/client/Client"; -import { Articles } from "../resources/articles/client/Client"; -import { AwayStatusReasons } from "../resources/awayStatusReasons/client/Client"; -import { Export } from "../resources/export/client/Client"; -import { HelpCenter } from "../resources/helpCenter/client/Client"; -import { Companies } from "../resources/companies/client/Client"; -import { Contacts } from "../resources/contacts/client/Client"; -import { Notes } from "../resources/notes/client/Client"; -import { SubscriptionTypes } from "../resources/subscriptionTypes/client/Client"; -import { Tags } from "../resources/tags/client/Client"; -import { Conversations } from "../resources/conversations/client/Client"; -import { CustomChannelEvents } from "../resources/customChannelEvents/client/Client"; -import { CustomObjectInstances } from "../resources/customObjectInstances/client/Client"; -import { DataAttributes } from "../resources/dataAttributes/client/Client"; -import { DataEvents } from "../resources/dataEvents/client/Client"; -import { DataExport } from "../resources/dataExport/client/Client"; -import { Jobs } from "../resources/jobs/client/Client"; -import { Messages } from "../resources/messages/client/Client"; -import { News } from "../resources/news/client/Client"; -import { Segments } from "../resources/segments/client/Client"; -import { Switch } from "../resources/switch/client/Client"; -import { Teams } from "../resources/teams/client/Client"; -import { TicketStates } from "../resources/ticketStates/client/Client"; -import { TicketTypeAttributes } from "../resources/ticketTypeAttributes/client/Client"; -import { TicketTypes } from "../resources/ticketTypes/client/Client"; -import { Tickets } from "../resources/tickets/client/Client"; -import { Visitors } from "../resources/visitors/client/Client"; - -export declare namespace Unstable { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { AdminsClient } from "../resources/admins/client/Client.js"; +import { AiContentClient } from "../resources/aiContent/client/Client.js"; +import { ArticlesClient } from "../resources/articles/client/Client.js"; +import { AwayStatusReasonsClient } from "../resources/awayStatusReasons/client/Client.js"; +import { BrandsClient } from "../resources/brands/client/Client.js"; +import { CallsClient } from "../resources/calls/client/Client.js"; +import { CompaniesClient } from "../resources/companies/client/Client.js"; +import { ContactsClient } from "../resources/contacts/client/Client.js"; +import { ConversationsClient } from "../resources/conversations/client/Client.js"; +import { CustomChannelEventsClient } from "../resources/customChannelEvents/client/Client.js"; +import { CustomObjectInstancesClient } from "../resources/customObjectInstances/client/Client.js"; +import { DataAttributesClient } from "../resources/dataAttributes/client/Client.js"; +import { DataEventsClient } from "../resources/dataEvents/client/Client.js"; +import { DataExportClient } from "../resources/dataExport/client/Client.js"; +import { EmailsClient } from "../resources/emails/client/Client.js"; +import { ExportClient } from "../resources/export/client/Client.js"; +import { HelpCenterClient } from "../resources/helpCenter/client/Client.js"; +import { InternalArticlesClient } from "../resources/internalArticles/client/Client.js"; +import { JobsClient } from "../resources/jobs/client/Client.js"; +import { MacrosClient } from "../resources/macros/client/Client.js"; +import { MessagesClient } from "../resources/messages/client/Client.js"; +import { NewsClient } from "../resources/news/client/Client.js"; +import { NotesClient } from "../resources/notes/client/Client.js"; +import { SegmentsClient } from "../resources/segments/client/Client.js"; +import { SubscriptionTypesClient } from "../resources/subscriptionTypes/client/Client.js"; +import { SwitchClient } from "../resources/switch/client/Client.js"; +import { TagsClient } from "../resources/tags/client/Client.js"; +import { TeamsClient } from "../resources/teams/client/Client.js"; +import { TicketStatesClient } from "../resources/ticketStates/client/Client.js"; +import { TicketsClient } from "../resources/tickets/client/Client.js"; +import { TicketTypeAttributesClient } from "../resources/ticketTypeAttributes/client/Client.js"; +import { TicketTypesClient } from "../resources/ticketTypes/client/Client.js"; +import { VisitorsClient } from "../resources/visitors/client/Client.js"; + +export declare namespace UnstableClient { + export interface Options extends BaseClientOptions {} } -export class Unstable { - protected _admins: Admins | undefined; - protected _aiContent: AiContent | undefined; - protected _articles: Articles | undefined; - protected _awayStatusReasons: AwayStatusReasons | undefined; - protected _export: Export | undefined; - protected _helpCenter: HelpCenter | undefined; - protected _companies: Companies | undefined; - protected _contacts: Contacts | undefined; - protected _notes: Notes | undefined; - protected _subscriptionTypes: SubscriptionTypes | undefined; - protected _tags: Tags | undefined; - protected _conversations: Conversations | undefined; - protected _customChannelEvents: CustomChannelEvents | undefined; - protected _customObjectInstances: CustomObjectInstances | undefined; - protected _dataAttributes: DataAttributes | undefined; - protected _dataEvents: DataEvents | undefined; - protected _dataExport: DataExport | undefined; - protected _jobs: Jobs | undefined; - protected _messages: Messages | undefined; - protected _news: News | undefined; - protected _segments: Segments | undefined; - protected _switch: Switch | undefined; - protected _teams: Teams | undefined; - protected _ticketStates: TicketStates | undefined; - protected _ticketTypeAttributes: TicketTypeAttributes | undefined; - protected _ticketTypes: TicketTypes | undefined; - protected _tickets: Tickets | undefined; - protected _visitors: Visitors | undefined; +export class UnstableClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + protected _admins: AdminsClient | undefined; + protected _aiContent: AiContentClient | undefined; + protected _articles: ArticlesClient | undefined; + protected _awayStatusReasons: AwayStatusReasonsClient | undefined; + protected _export: ExportClient | undefined; + protected _helpCenter: HelpCenterClient | undefined; + protected _internalArticles: InternalArticlesClient | undefined; + protected _companies: CompaniesClient | undefined; + protected _notes: NotesClient | undefined; + protected _contacts: ContactsClient | undefined; + protected _subscriptionTypes: SubscriptionTypesClient | undefined; + protected _tags: TagsClient | undefined; + protected _conversations: ConversationsClient | undefined; + protected _customChannelEvents: CustomChannelEventsClient | undefined; + protected _customObjectInstances: CustomObjectInstancesClient | undefined; + protected _dataAttributes: DataAttributesClient | undefined; + protected _dataEvents: DataEventsClient | undefined; + protected _dataExport: DataExportClient | undefined; + protected _jobs: JobsClient | undefined; + protected _macros: MacrosClient | undefined; + protected _messages: MessagesClient | undefined; + protected _news: NewsClient | undefined; + protected _segments: SegmentsClient | undefined; + protected _switch: SwitchClient | undefined; + protected _calls: CallsClient | undefined; + protected _teams: TeamsClient | undefined; + protected _ticketStates: TicketStatesClient | undefined; + protected _ticketTypeAttributes: TicketTypeAttributesClient | undefined; + protected _ticketTypes: TicketTypesClient | undefined; + protected _tickets: TicketsClient | undefined; + protected _visitors: VisitorsClient | undefined; + protected _brands: BrandsClient | undefined; + protected _emails: EmailsClient | undefined; + + constructor(options: UnstableClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + public get admins(): AdminsClient { + return (this._admins ??= new AdminsClient(this._options)); + } + + public get aiContent(): AiContentClient { + return (this._aiContent ??= new AiContentClient(this._options)); + } + + public get articles(): ArticlesClient { + return (this._articles ??= new ArticlesClient(this._options)); + } - constructor(protected readonly _options: Unstable.Options = {}) {} + public get awayStatusReasons(): AwayStatusReasonsClient { + return (this._awayStatusReasons ??= new AwayStatusReasonsClient(this._options)); + } + + public get export(): ExportClient { + return (this._export ??= new ExportClient(this._options)); + } - public get admins(): Admins { - return (this._admins ??= new Admins(this._options)); + public get helpCenter(): HelpCenterClient { + return (this._helpCenter ??= new HelpCenterClient(this._options)); } - public get aiContent(): AiContent { - return (this._aiContent ??= new AiContent(this._options)); + public get internalArticles(): InternalArticlesClient { + return (this._internalArticles ??= new InternalArticlesClient(this._options)); } - public get articles(): Articles { - return (this._articles ??= new Articles(this._options)); + public get companies(): CompaniesClient { + return (this._companies ??= new CompaniesClient(this._options)); } - public get awayStatusReasons(): AwayStatusReasons { - return (this._awayStatusReasons ??= new AwayStatusReasons(this._options)); + public get notes(): NotesClient { + return (this._notes ??= new NotesClient(this._options)); } - public get export(): Export { - return (this._export ??= new Export(this._options)); + public get contacts(): ContactsClient { + return (this._contacts ??= new ContactsClient(this._options)); } - public get helpCenter(): HelpCenter { - return (this._helpCenter ??= new HelpCenter(this._options)); + public get subscriptionTypes(): SubscriptionTypesClient { + return (this._subscriptionTypes ??= new SubscriptionTypesClient(this._options)); } - public get companies(): Companies { - return (this._companies ??= new Companies(this._options)); + public get tags(): TagsClient { + return (this._tags ??= new TagsClient(this._options)); } - public get contacts(): Contacts { - return (this._contacts ??= new Contacts(this._options)); + public get conversations(): ConversationsClient { + return (this._conversations ??= new ConversationsClient(this._options)); } - public get notes(): Notes { - return (this._notes ??= new Notes(this._options)); + public get customChannelEvents(): CustomChannelEventsClient { + return (this._customChannelEvents ??= new CustomChannelEventsClient(this._options)); } - public get subscriptionTypes(): SubscriptionTypes { - return (this._subscriptionTypes ??= new SubscriptionTypes(this._options)); + public get customObjectInstances(): CustomObjectInstancesClient { + return (this._customObjectInstances ??= new CustomObjectInstancesClient(this._options)); } - public get tags(): Tags { - return (this._tags ??= new Tags(this._options)); + public get dataAttributes(): DataAttributesClient { + return (this._dataAttributes ??= new DataAttributesClient(this._options)); } - public get conversations(): Conversations { - return (this._conversations ??= new Conversations(this._options)); + public get dataEvents(): DataEventsClient { + return (this._dataEvents ??= new DataEventsClient(this._options)); } - public get customChannelEvents(): CustomChannelEvents { - return (this._customChannelEvents ??= new CustomChannelEvents(this._options)); + public get dataExport(): DataExportClient { + return (this._dataExport ??= new DataExportClient(this._options)); } - public get customObjectInstances(): CustomObjectInstances { - return (this._customObjectInstances ??= new CustomObjectInstances(this._options)); + public get jobs(): JobsClient { + return (this._jobs ??= new JobsClient(this._options)); } - public get dataAttributes(): DataAttributes { - return (this._dataAttributes ??= new DataAttributes(this._options)); + public get macros(): MacrosClient { + return (this._macros ??= new MacrosClient(this._options)); } - public get dataEvents(): DataEvents { - return (this._dataEvents ??= new DataEvents(this._options)); + public get messages(): MessagesClient { + return (this._messages ??= new MessagesClient(this._options)); } - public get dataExport(): DataExport { - return (this._dataExport ??= new DataExport(this._options)); + public get news(): NewsClient { + return (this._news ??= new NewsClient(this._options)); } - public get jobs(): Jobs { - return (this._jobs ??= new Jobs(this._options)); + public get segments(): SegmentsClient { + return (this._segments ??= new SegmentsClient(this._options)); } - public get messages(): Messages { - return (this._messages ??= new Messages(this._options)); + public get switch(): SwitchClient { + return (this._switch ??= new SwitchClient(this._options)); } - public get news(): News { - return (this._news ??= new News(this._options)); + public get calls(): CallsClient { + return (this._calls ??= new CallsClient(this._options)); } - public get segments(): Segments { - return (this._segments ??= new Segments(this._options)); + public get teams(): TeamsClient { + return (this._teams ??= new TeamsClient(this._options)); } - public get switch(): Switch { - return (this._switch ??= new Switch(this._options)); + public get ticketStates(): TicketStatesClient { + return (this._ticketStates ??= new TicketStatesClient(this._options)); } - public get teams(): Teams { - return (this._teams ??= new Teams(this._options)); + public get ticketTypeAttributes(): TicketTypeAttributesClient { + return (this._ticketTypeAttributes ??= new TicketTypeAttributesClient(this._options)); } - public get ticketStates(): TicketStates { - return (this._ticketStates ??= new TicketStates(this._options)); + public get ticketTypes(): TicketTypesClient { + return (this._ticketTypes ??= new TicketTypesClient(this._options)); } - public get ticketTypeAttributes(): TicketTypeAttributes { - return (this._ticketTypeAttributes ??= new TicketTypeAttributes(this._options)); + public get tickets(): TicketsClient { + return (this._tickets ??= new TicketsClient(this._options)); } - public get ticketTypes(): TicketTypes { - return (this._ticketTypes ??= new TicketTypes(this._options)); + public get visitors(): VisitorsClient { + return (this._visitors ??= new VisitorsClient(this._options)); } - public get tickets(): Tickets { - return (this._tickets ??= new Tickets(this._options)); + public get brands(): BrandsClient { + return (this._brands ??= new BrandsClient(this._options)); } - public get visitors(): Visitors { - return (this._visitors ??= new Visitors(this._options)); + public get emails(): EmailsClient { + return (this._emails ??= new EmailsClient(this._options)); } } diff --git a/src/api/resources/unstable/errors/BadRequestError.ts b/src/api/resources/unstable/errors/BadRequestError.ts index d7e71d09..351933dd 100644 --- a/src/api/resources/unstable/errors/BadRequestError.ts +++ b/src/api/resources/unstable/errors/BadRequestError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; export class BadRequestError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/ConflictError.ts b/src/api/resources/unstable/errors/ConflictError.ts new file mode 100644 index 00000000..afd826b8 --- /dev/null +++ b/src/api/resources/unstable/errors/ConflictError.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; +import type * as Intercom from "../../../index.js"; + +export class ConflictError extends errors.IntercomError { + constructor(body: Intercom.unstable.Error_, rawResponse?: core.RawResponse) { + super({ + message: "ConflictError", + statusCode: 409, + body: body, + rawResponse: rawResponse, + }); + Object.setPrototypeOf(this, ConflictError.prototype); + } +} diff --git a/src/api/resources/unstable/errors/ForbiddenError.ts b/src/api/resources/unstable/errors/ForbiddenError.ts index c98ade42..a5eefa5f 100644 --- a/src/api/resources/unstable/errors/ForbiddenError.ts +++ b/src/api/resources/unstable/errors/ForbiddenError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as Intercom from "../../../index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; +import type * as Intercom from "../../../index.js"; export class ForbiddenError extends errors.IntercomError { constructor(body: Intercom.unstable.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/InternalServerError.ts b/src/api/resources/unstable/errors/InternalServerError.ts index 6e6ad916..05de1b39 100644 --- a/src/api/resources/unstable/errors/InternalServerError.ts +++ b/src/api/resources/unstable/errors/InternalServerError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as Intercom from "../../../index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; +import type * as Intercom from "../../../index.js"; export class InternalServerError extends errors.IntercomError { constructor(body: Intercom.unstable.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/NotFoundError.ts b/src/api/resources/unstable/errors/NotFoundError.ts index 323b5b44..2b6a1c39 100644 --- a/src/api/resources/unstable/errors/NotFoundError.ts +++ b/src/api/resources/unstable/errors/NotFoundError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; export class NotFoundError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/TooManyRequestsError.ts b/src/api/resources/unstable/errors/TooManyRequestsError.ts index e9ff4d56..8213e523 100644 --- a/src/api/resources/unstable/errors/TooManyRequestsError.ts +++ b/src/api/resources/unstable/errors/TooManyRequestsError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as Intercom from "../../../index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; +import type * as Intercom from "../../../index.js"; export class TooManyRequestsError extends errors.IntercomError { constructor(body: Intercom.unstable.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/UnauthorizedError.ts b/src/api/resources/unstable/errors/UnauthorizedError.ts index 33fb0bce..15ea9d4f 100644 --- a/src/api/resources/unstable/errors/UnauthorizedError.ts +++ b/src/api/resources/unstable/errors/UnauthorizedError.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as Intercom from "../../../index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; +import type * as Intercom from "../../../index.js"; export class UnauthorizedError extends errors.IntercomError { constructor(body: Intercom.unstable.Error_, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/UnprocessableEntityError.ts b/src/api/resources/unstable/errors/UnprocessableEntityError.ts index 912441d7..a2021d64 100644 --- a/src/api/resources/unstable/errors/UnprocessableEntityError.ts +++ b/src/api/resources/unstable/errors/UnprocessableEntityError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as errors from "../../../../errors/index"; -import * as core from "../../../../core"; +import type * as core from "../../../../core/index.js"; +import * as errors from "../../../../errors/index.js"; export class UnprocessableEntityError extends errors.IntercomError { constructor(body?: unknown, rawResponse?: core.RawResponse) { diff --git a/src/api/resources/unstable/errors/index.ts b/src/api/resources/unstable/errors/index.ts index 6190d905..200c43d1 100644 --- a/src/api/resources/unstable/errors/index.ts +++ b/src/api/resources/unstable/errors/index.ts @@ -1,7 +1,8 @@ -export * from "./BadRequestError"; -export * from "./UnauthorizedError"; -export * from "./NotFoundError"; -export * from "./TooManyRequestsError"; -export * from "./ForbiddenError"; -export * from "./UnprocessableEntityError"; -export * from "./InternalServerError"; +export * from "./BadRequestError.js"; +export * from "./ConflictError.js"; +export * from "./ForbiddenError.js"; +export * from "./InternalServerError.js"; +export * from "./NotFoundError.js"; +export * from "./TooManyRequestsError.js"; +export * from "./UnauthorizedError.js"; +export * from "./UnprocessableEntityError.js"; diff --git a/src/api/resources/unstable/index.ts b/src/api/resources/unstable/index.ts index d5c609c4..d73889d8 100644 --- a/src/api/resources/unstable/index.ts +++ b/src/api/resources/unstable/index.ts @@ -1,4 +1,4 @@ -export * from "./resources"; -export * from "./types"; -export * from "./errors"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./errors/index.js"; +export * from "./resources/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/admins/client/Client.ts b/src/api/resources/unstable/resources/admins/client/Client.ts index fad5ac42..ece2566e 100644 --- a/src/api/resources/unstable/resources/admins/client/Client.ts +++ b/src/api/resources/unstable/resources/admins/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Admins { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace AdminsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Admins */ -export class Admins { - constructor(protected readonly _options: Admins.Options = {}) {} +export class AdminsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AdminsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * @@ -83,44 +33,42 @@ export class Admins { * > * > If you are building a custom "Log in with Intercom" flow for your site, and you call the `/me` endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk. * - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.admins.identifyAdmin() */ public identifyAdmin( - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__identifyAdmin(requestOptions)); } private async __identifyAdmin( - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "me", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -137,28 +85,14 @@ export class Admins { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /me."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/me"); } /** * You can set an Admin as away for the Inbox. * * @param {Intercom.unstable.SetAwayAdminRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -181,41 +115,41 @@ export class Admins { */ public setAwayAdmin( request: Intercom.unstable.SetAwayAdminRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__setAwayAdmin(request, requestOptions)); } private async __setAwayAdmin( request: Intercom.unstable.SetAwayAdminRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `admins/${encodeURIComponent(id)}/away`, + `admins/${core.url.encodePathParam(id)}/away`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Admin | undefined, rawResponse: _response.rawResponse }; @@ -241,28 +175,14 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /admins/{id}/away."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/admins/{id}/away"); } /** * You can get a log of activities by all admins in an app. * * @param {Intercom.unstable.ListActivityLogsRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -274,47 +194,44 @@ export class Admins { */ public listActivityLogs( request: Intercom.unstable.ListActivityLogsRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listActivityLogs(request, requestOptions)); } private async __listActivityLogs( request: Intercom.unstable.ListActivityLogsRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { const { created_at_after: createdAtAfter, created_at_before: createdAtBefore } = request; const _queryParams: Record = {}; - _queryParams["created_at_after"] = createdAtAfter; + _queryParams.created_at_after = createdAtAfter; if (createdAtBefore != null) { - _queryParams["created_at_before"] = createdAtBefore; + _queryParams.created_at_before = createdAtBefore; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "admins/activity_logs", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ActivityLogList, rawResponse: _response.rawResponse }; @@ -336,64 +253,50 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins/activity_logs."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins/activity_logs"); } /** * You can fetch a list of admins for a given workspace. * - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.admins.listAdmins() */ - public listAdmins(requestOptions?: Admins.RequestOptions): core.HttpResponsePromise { + public listAdmins( + requestOptions?: AdminsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAdmins(requestOptions)); } private async __listAdmins( - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "admins", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.AdminList, rawResponse: _response.rawResponse }; @@ -415,28 +318,14 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins"); } /** * You can retrieve the details of a single admin. * * @param {Intercom.unstable.RetrieveAdminRequest} request - * @param {Admins.RequestOptions} requestOptions - Request-specific configuration. + * @param {AdminsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -448,40 +337,38 @@ export class Admins { */ public retrieveAdmin( request: Intercom.unstable.RetrieveAdminRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveAdmin(request, requestOptions)); } private async __retrieveAdmin( request: Intercom.unstable.RetrieveAdminRequest, - requestOptions?: Admins.RequestOptions, + requestOptions?: AdminsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `admins/${encodeURIComponent(id)}`, + `admins/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Admin | undefined, rawResponse: _response.rawResponse }; @@ -505,32 +392,6 @@ export class Admins { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /admins/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/admins/{id}"); } } diff --git a/src/api/resources/unstable/resources/admins/client/index.ts b/src/api/resources/unstable/resources/admins/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/admins/client/index.ts +++ b/src/api/resources/unstable/resources/admins/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/admins/client/requests/ListActivityLogsRequest.ts b/src/api/resources/unstable/resources/admins/client/requests/ListActivityLogsRequest.ts index 88dbafc4..f5608b49 100644 --- a/src/api/resources/unstable/resources/admins/client/requests/ListActivityLogsRequest.ts +++ b/src/api/resources/unstable/resources/admins/client/requests/ListActivityLogsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface ListActivityLogsRequest { - /** - * The start date that you request data for. It must be formatted as a UNIX timestamp. - */ + /** The start date that you request data for. It must be formatted as a UNIX timestamp. */ created_at_after: string; - /** - * The end date that you request data for. It must be formatted as a UNIX timestamp. - */ + /** The end date that you request data for. It must be formatted as a UNIX timestamp. */ created_at_before?: string; } diff --git a/src/api/resources/unstable/resources/admins/client/requests/RetrieveAdminRequest.ts b/src/api/resources/unstable/resources/admins/client/requests/RetrieveAdminRequest.ts index 49fb29b2..a7ae3952 100644 --- a/src/api/resources/unstable/resources/admins/client/requests/RetrieveAdminRequest.ts +++ b/src/api/resources/unstable/resources/admins/client/requests/RetrieveAdminRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveAdminRequest { - /** - * The unique identifier of a given admin - */ + /** The unique identifier of a given admin */ id: number; } diff --git a/src/api/resources/unstable/resources/admins/client/requests/SetAwayAdminRequest.ts b/src/api/resources/unstable/resources/admins/client/requests/SetAwayAdminRequest.ts index 2b986684..7c270dec 100644 --- a/src/api/resources/unstable/resources/admins/client/requests/SetAwayAdminRequest.ts +++ b/src/api/resources/unstable/resources/admins/client/requests/SetAwayAdminRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -26,9 +24,7 @@ * } */ export interface SetAwayAdminRequest { - /** - * The unique identifier of a given admin - */ + /** The unique identifier of a given admin */ id: number; /** Set to "true" to change the status of the admin to away. */ away_mode_enabled: boolean; diff --git a/src/api/resources/unstable/resources/admins/client/requests/index.ts b/src/api/resources/unstable/resources/admins/client/requests/index.ts index 9ca82847..48a61029 100644 --- a/src/api/resources/unstable/resources/admins/client/requests/index.ts +++ b/src/api/resources/unstable/resources/admins/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type SetAwayAdminRequest } from "./SetAwayAdminRequest"; -export { type ListActivityLogsRequest } from "./ListActivityLogsRequest"; -export { type RetrieveAdminRequest } from "./RetrieveAdminRequest"; +export type { ListActivityLogsRequest } from "./ListActivityLogsRequest.js"; +export type { RetrieveAdminRequest } from "./RetrieveAdminRequest.js"; +export type { SetAwayAdminRequest } from "./SetAwayAdminRequest.js"; diff --git a/src/api/resources/unstable/resources/admins/index.ts b/src/api/resources/unstable/resources/admins/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/admins/index.ts +++ b/src/api/resources/unstable/resources/admins/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/admins/types/Admin.ts b/src/api/resources/unstable/resources/admins/types/Admin.ts index 8e1794d6..113cc504 100644 --- a/src/api/resources/unstable/resources/admins/types/Admin.ts +++ b/src/api/resources/unstable/resources/admins/types/Admin.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Admins are teammate accounts that have access to a workspace. diff --git a/src/api/resources/unstable/resources/admins/types/index.ts b/src/api/resources/unstable/resources/admins/types/index.ts index c950b2eb..838f94f4 100644 --- a/src/api/resources/unstable/resources/admins/types/index.ts +++ b/src/api/resources/unstable/resources/admins/types/index.ts @@ -1 +1 @@ -export * from "./Admin"; +export * from "./Admin.js"; diff --git a/src/api/resources/unstable/resources/aiAgent/index.ts b/src/api/resources/unstable/resources/aiAgent/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/unstable/resources/aiAgent/index.ts +++ b/src/api/resources/unstable/resources/aiAgent/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/aiAgent/types/AiAgent.ts b/src/api/resources/unstable/resources/aiAgent/types/AiAgent.ts index bc37ada3..fb043f41 100644 --- a/src/api/resources/unstable/resources/aiAgent/types/AiAgent.ts +++ b/src/api/resources/unstable/resources/aiAgent/types/AiAgent.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Data related to AI Agent involvement in the conversation. @@ -13,21 +11,22 @@ export interface AiAgent { /** The title of the source that triggered AI Agent involvement in the conversation. If this is `essentials_plan_setup` then it will return `null`. */ source_title?: string; /** The type of the last answer delivered by AI Agent. If no answer was delivered then this will return `null` */ - last_answer_type?: string; + last_answer_type?: AiAgent.LastAnswerType; /** The resolution state of AI Agent. If no AI or custom answer has been delivered then this will return `null`. */ - resolution_state?: string; + resolution_state?: AiAgent.ResolutionState; /** The customer satisfaction rating given to AI Agent, from 1-5. */ rating?: number; /** The customer satisfaction rating remark given to AI Agent. */ rating_remark?: string; + /** The time when the AI agent rating was created. */ + created_at?: number; + /** The time when the AI agent rating was last updated. */ + updated_at?: number; content_sources?: Intercom.unstable.ContentSourcesList; } export namespace AiAgent { - /** - * The type of the source that triggered AI Agent involvement in the conversation. - */ - export type SourceType = "essentials_plan_setup" | "profile" | "workflow" | "workflow_preview" | "fin_preview"; + /** The type of the source that triggered AI Agent involvement in the conversation. */ export const SourceType = { EssentialsPlanSetup: "essentials_plan_setup", Profile: "profile", @@ -35,4 +34,19 @@ export namespace AiAgent { WorkflowPreview: "workflow_preview", FinPreview: "fin_preview", } as const; + export type SourceType = (typeof SourceType)[keyof typeof SourceType]; + /** The type of the last answer delivered by AI Agent. If no answer was delivered then this will return `null` */ + export const LastAnswerType = { + AiAnswer: "ai_answer", + CustomAnswer: "custom_answer", + } as const; + export type LastAnswerType = (typeof LastAnswerType)[keyof typeof LastAnswerType]; + /** The resolution state of AI Agent. If no AI or custom answer has been delivered then this will return `null`. */ + export const ResolutionState = { + AssumedResolution: "assumed_resolution", + ConfirmedResolution: "confirmed_resolution", + Escalated: "escalated", + NegativeFeedback: "negative_feedback", + } as const; + export type ResolutionState = (typeof ResolutionState)[keyof typeof ResolutionState]; } diff --git a/src/api/resources/unstable/resources/aiAgent/types/index.ts b/src/api/resources/unstable/resources/aiAgent/types/index.ts index 05de312f..27ef772f 100644 --- a/src/api/resources/unstable/resources/aiAgent/types/index.ts +++ b/src/api/resources/unstable/resources/aiAgent/types/index.ts @@ -1 +1 @@ -export * from "./AiAgent"; +export * from "./AiAgent.js"; diff --git a/src/api/resources/unstable/resources/aiContent/client/Client.ts b/src/api/resources/unstable/resources/aiContent/client/Client.ts index 55afcd8a..cdb6bcae 100644 --- a/src/api/resources/unstable/resources/aiContent/client/Client.ts +++ b/src/api/resources/unstable/resources/aiContent/client/Client.ts @@ -1,72 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; - -export declare namespace AiContent { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } +export declare namespace AiContentClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } /** @@ -84,13 +30,17 @@ export declare namespace AiContent { * * You can then iterate through the content from that source via its API and POST it to the External Pages endpoint. That endpoint has an *external_id* parameter which allows you to specify the identifier from the source. The endpoint will then either create a new External Page or update an existing one as appropriate.", */ -export class AiContent { - constructor(protected readonly _options: AiContent.Options = {}) {} +export class AiContentClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AiContentClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can retrieve a list of all content import sources for a workspace. * - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -98,38 +48,36 @@ export class AiContent { * await client.unstable.aiContent.listContentImportSources() */ public listContentImportSources( - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listContentImportSources(requestOptions)); } private async __listContentImportSources( - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ai/content_import_sources", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -154,28 +102,14 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ai/content_import_sources."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/content_import_sources"); } /** * You can create a new content import source by sending a POST request to this endpoint. * * @param {Intercom.unstable.CreateContentImportSourceRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -186,40 +120,40 @@ export class AiContent { */ public createContentImportSource( request: Intercom.unstable.CreateContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createContentImportSource(request, requestOptions)); } private async __createContentImportSource( request: Intercom.unstable.CreateContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ai/content_import_sources", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: { ...request, sync_behavior: "api" }, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -244,26 +178,12 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /ai/content_import_sources."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ai/content_import_sources"); } /** * @param {Intercom.unstable.GetContentImportSourceRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -274,40 +194,38 @@ export class AiContent { */ public getContentImportSource( request: Intercom.unstable.GetContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getContentImportSource(request, requestOptions)); } private async __getContentImportSource( request: Intercom.unstable.GetContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/content_import_sources/${encodeURIComponent(id)}`, + `ai/content_import_sources/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -332,30 +250,19 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /ai/content_import_sources/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/ai/content_import_sources/{id}", + ); } /** * You can update an existing content import source. * * @param {Intercom.unstable.UpdateContentImportSourceRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -368,41 +275,41 @@ export class AiContent { */ public updateContentImportSource( request: Intercom.unstable.UpdateContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateContentImportSource(request, requestOptions)); } private async __updateContentImportSource( request: Intercom.unstable.UpdateContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/content_import_sources/${encodeURIComponent(id)}`, + `ai/content_import_sources/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -427,30 +334,19 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /ai/content_import_sources/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/ai/content_import_sources/{id}", + ); } /** * You can delete a content import source by making a DELETE request this endpoint. This will also delete all external pages that were imported from this source. * * @param {Intercom.unstable.DeleteContentImportSourceRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -461,40 +357,38 @@ export class AiContent { */ public deleteContentImportSource( request: Intercom.unstable.DeleteContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteContentImportSource(request, requestOptions)); } private async __deleteContentImportSource( request: Intercom.unstable.DeleteContentImportSourceRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/content_import_sources/${encodeURIComponent(id)}`, + `ai/content_import_sources/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -516,29 +410,18 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /ai/content_import_sources/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/ai/content_import_sources/{id}", + ); } /** * You can retrieve a list of all external pages for a workspace. * - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -546,38 +429,36 @@ export class AiContent { * await client.unstable.aiContent.listExternalPages() */ public listExternalPages( - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listExternalPages(requestOptions)); } private async __listExternalPages( - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ai/external_pages", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ExternalPagesList, rawResponse: _response.rawResponse }; @@ -599,28 +480,14 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ai/external_pages."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/external_pages"); } /** * You can create a new external page by sending a POST request to this endpoint. If an external page already exists with the specified source_id and external_id, it will be updated instead. * * @param {Intercom.unstable.CreateExternalPageRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -635,40 +502,40 @@ export class AiContent { */ public createExternalPage( request: Intercom.unstable.CreateExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createExternalPage(request, requestOptions)); } private async __createExternalPage( request: Intercom.unstable.CreateExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ai/external_pages", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: { ...request, locale: "en" }, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ExternalPage, rawResponse: _response.rawResponse }; @@ -690,28 +557,14 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /ai/external_pages."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ai/external_pages"); } /** * You can retrieve an external page. * * @param {Intercom.unstable.GetExternalPageRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -722,40 +575,38 @@ export class AiContent { */ public getExternalPage( request: Intercom.unstable.GetExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getExternalPage(request, requestOptions)); } private async __getExternalPage( request: Intercom.unstable.GetExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/external_pages/${encodeURIComponent(id)}`, + `ai/external_pages/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ExternalPage, rawResponse: _response.rawResponse }; @@ -777,28 +628,14 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ai/external_pages/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ai/external_pages/{id}"); } /** * You can update an existing external page (if it was created via the API). * * @param {Intercom.unstable.UpdateExternalPageRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -814,41 +651,41 @@ export class AiContent { */ public updateExternalPage( request: Intercom.unstable.UpdateExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateExternalPage(request, requestOptions)); } private async __updateExternalPage( request: Intercom.unstable.UpdateExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/external_pages/${encodeURIComponent(id)}`, + `ai/external_pages/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: { ..._body, locale: "en" }, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ExternalPage, rawResponse: _response.rawResponse }; @@ -870,28 +707,14 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /ai/external_pages/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/ai/external_pages/{id}"); } /** * Sending a DELETE request for an external page will remove it from the content library UI and from being used for AI answers. * * @param {Intercom.unstable.DeleteExternalPageRequest} request - * @param {AiContent.RequestOptions} requestOptions - Request-specific configuration. + * @param {AiContentClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -902,40 +725,38 @@ export class AiContent { */ public deleteExternalPage( request: Intercom.unstable.DeleteExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteExternalPage(request, requestOptions)); } private async __deleteExternalPage( request: Intercom.unstable.DeleteExternalPageRequest, - requestOptions?: AiContent.RequestOptions, + requestOptions?: AiContentClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ai/external_pages/${encodeURIComponent(id)}`, + `ai/external_pages/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ExternalPage, rawResponse: _response.rawResponse }; @@ -957,32 +778,6 @@ export class AiContent { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /ai/external_pages/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/ai/external_pages/{id}"); } } diff --git a/src/api/resources/unstable/resources/aiContent/client/index.ts b/src/api/resources/unstable/resources/aiContent/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/aiContent/client/index.ts +++ b/src/api/resources/unstable/resources/aiContent/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts index 06da2b4a..f487b162 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/CreateContentImportSourceRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -16,12 +14,10 @@ export interface CreateContentImportSourceRequest { } export namespace CreateContentImportSourceRequest { - /** - * The status of the content import source. - */ - export type Status = "active" | "deactivated"; + /** The status of the content import source. */ export const Status = { Active: "active", Deactivated: "deactivated", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/CreateExternalPageRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/CreateExternalPageRequest.ts index d0d37237..c4f5e914 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/CreateExternalPageRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/CreateExternalPageRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts index 6d921146..255ebcd0 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/DeleteContentImportSourceRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteContentImportSourceRequest { - /** - * The unique identifier for the content import source which is given by Intercom. - */ + /** The unique identifier for the content import source which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/DeleteExternalPageRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/DeleteExternalPageRequest.ts index cf5c01d3..87532df3 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/DeleteExternalPageRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/DeleteExternalPageRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteExternalPageRequest { - /** - * The unique identifier for the external page which is given by Intercom. - */ + /** The unique identifier for the external page which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/GetContentImportSourceRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/GetContentImportSourceRequest.ts index 68b77b47..199749ac 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/GetContentImportSourceRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/GetContentImportSourceRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface GetContentImportSourceRequest { - /** - * The unique identifier for the content import source which is given by Intercom. - */ + /** The unique identifier for the content import source which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/GetExternalPageRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/GetExternalPageRequest.ts index bb1c963e..c7d50ef1 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/GetExternalPageRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/GetExternalPageRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface GetExternalPageRequest { - /** - * The unique identifier for the external page which is given by Intercom. - */ + /** The unique identifier for the external page which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts index bac30489..48401914 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/UpdateContentImportSourceRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -11,9 +9,7 @@ * } */ export interface UpdateContentImportSourceRequest { - /** - * The unique identifier for the content import source which is given by Intercom. - */ + /** The unique identifier for the content import source which is given by Intercom. */ id: string; /** If you intend to create or update External Pages via the API, this should be set to `api`. You can not change the value to or from api. */ sync_behavior: UpdateContentImportSourceRequest.SyncBehavior; @@ -24,21 +20,17 @@ export interface UpdateContentImportSourceRequest { } export namespace UpdateContentImportSourceRequest { - /** - * If you intend to create or update External Pages via the API, this should be set to `api`. You can not change the value to or from api. - */ - export type SyncBehavior = "api" | "automated" | "manual"; + /** If you intend to create or update External Pages via the API, this should be set to `api`. You can not change the value to or from api. */ export const SyncBehavior = { Api: "api", Automated: "automated", Manual: "manual", } as const; - /** - * The status of the content import source. - */ - export type Status = "active" | "deactivated"; + export type SyncBehavior = (typeof SyncBehavior)[keyof typeof SyncBehavior]; + /** The status of the content import source. */ export const Status = { Active: "active", Deactivated: "deactivated", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/UpdateExternalPageRequest.ts b/src/api/resources/unstable/resources/aiContent/client/requests/UpdateExternalPageRequest.ts index 162b3c77..ccfddc5e 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/UpdateExternalPageRequest.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/UpdateExternalPageRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -14,9 +12,7 @@ * } */ export interface UpdateExternalPageRequest { - /** - * The unique identifier for the external page which is given by Intercom. - */ + /** The unique identifier for the external page which is given by Intercom. */ id: string; /** The title of the external page. */ title: string; diff --git a/src/api/resources/unstable/resources/aiContent/client/requests/index.ts b/src/api/resources/unstable/resources/aiContent/client/requests/index.ts index 820c72ee..2c010829 100644 --- a/src/api/resources/unstable/resources/aiContent/client/requests/index.ts +++ b/src/api/resources/unstable/resources/aiContent/client/requests/index.ts @@ -1,8 +1,8 @@ -export { type CreateContentImportSourceRequest } from "./CreateContentImportSourceRequest"; -export { type GetContentImportSourceRequest } from "./GetContentImportSourceRequest"; -export { type UpdateContentImportSourceRequest } from "./UpdateContentImportSourceRequest"; -export { type DeleteContentImportSourceRequest } from "./DeleteContentImportSourceRequest"; -export { type CreateExternalPageRequest } from "./CreateExternalPageRequest"; -export { type GetExternalPageRequest } from "./GetExternalPageRequest"; -export { type UpdateExternalPageRequest } from "./UpdateExternalPageRequest"; -export { type DeleteExternalPageRequest } from "./DeleteExternalPageRequest"; +export type { CreateContentImportSourceRequest } from "./CreateContentImportSourceRequest.js"; +export type { CreateExternalPageRequest } from "./CreateExternalPageRequest.js"; +export type { DeleteContentImportSourceRequest } from "./DeleteContentImportSourceRequest.js"; +export type { DeleteExternalPageRequest } from "./DeleteExternalPageRequest.js"; +export type { GetContentImportSourceRequest } from "./GetContentImportSourceRequest.js"; +export type { GetExternalPageRequest } from "./GetExternalPageRequest.js"; +export type { UpdateContentImportSourceRequest } from "./UpdateContentImportSourceRequest.js"; +export type { UpdateExternalPageRequest } from "./UpdateExternalPageRequest.js"; diff --git a/src/api/resources/unstable/resources/aiContent/index.ts b/src/api/resources/unstable/resources/aiContent/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/aiContent/index.ts +++ b/src/api/resources/unstable/resources/aiContent/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/aiContent/types/ContentImportSource.ts b/src/api/resources/unstable/resources/aiContent/types/ContentImportSource.ts index ef5cd352..e65d8d1a 100644 --- a/src/api/resources/unstable/resources/aiContent/types/ContentImportSource.ts +++ b/src/api/resources/unstable/resources/aiContent/types/ContentImportSource.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An external source for External Pages that you add to your Fin Content Library. @@ -25,21 +23,17 @@ export interface ContentImportSource { } export namespace ContentImportSource { - /** - * If you intend to create or update External Pages via the API, this should be set to `api`. - */ - export type SyncBehavior = "api" | "automatic" | "manual"; + /** If you intend to create or update External Pages via the API, this should be set to `api`. */ export const SyncBehavior = { Api: "api", Automatic: "automatic", Manual: "manual", } as const; - /** - * The status of the content import source. - */ - export type Status = "active" | "deactivated"; + export type SyncBehavior = (typeof SyncBehavior)[keyof typeof SyncBehavior]; + /** The status of the content import source. */ export const Status = { Active: "active", Deactivated: "deactivated", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/unstable/resources/aiContent/types/ContentImportSourcesList.ts b/src/api/resources/unstable/resources/aiContent/types/ContentImportSourcesList.ts index ede951a5..ca3dfb3a 100644 --- a/src/api/resources/unstable/resources/aiContent/types/ContentImportSourcesList.ts +++ b/src/api/resources/unstable/resources/aiContent/types/ContentImportSourcesList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * This will return a list of the content import sources for the App. diff --git a/src/api/resources/unstable/resources/aiContent/types/ExternalPage.ts b/src/api/resources/unstable/resources/aiContent/types/ExternalPage.ts index 93a5eaf4..97afb31c 100644 --- a/src/api/resources/unstable/resources/aiContent/types/ExternalPage.ts +++ b/src/api/resources/unstable/resources/aiContent/types/ExternalPage.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * External pages that you have added to your Fin Content Library. diff --git a/src/api/resources/unstable/resources/aiContent/types/ExternalPagesList.ts b/src/api/resources/unstable/resources/aiContent/types/ExternalPagesList.ts index d3c610c2..94172e4f 100644 --- a/src/api/resources/unstable/resources/aiContent/types/ExternalPagesList.ts +++ b/src/api/resources/unstable/resources/aiContent/types/ExternalPagesList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * This will return a list of external pages for the App. diff --git a/src/api/resources/unstable/resources/aiContent/types/index.ts b/src/api/resources/unstable/resources/aiContent/types/index.ts index a1b39227..4a084844 100644 --- a/src/api/resources/unstable/resources/aiContent/types/index.ts +++ b/src/api/resources/unstable/resources/aiContent/types/index.ts @@ -1,4 +1,4 @@ -export * from "./ContentImportSource"; -export * from "./ContentImportSourcesList"; -export * from "./ExternalPage"; -export * from "./ExternalPagesList"; +export * from "./ContentImportSource.js"; +export * from "./ContentImportSourcesList.js"; +export * from "./ExternalPage.js"; +export * from "./ExternalPagesList.js"; diff --git a/src/api/resources/unstable/resources/aiContentSource/index.ts b/src/api/resources/unstable/resources/aiContentSource/index.ts index eea524d6..2f88e301 100644 --- a/src/api/resources/unstable/resources/aiContentSource/index.ts +++ b/src/api/resources/unstable/resources/aiContentSource/index.ts @@ -1 +1 @@ -export * from "./types"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/aiContentSource/types/ContentSource.ts b/src/api/resources/unstable/resources/aiContentSource/types/ContentSource.ts index 3baaae4a..9b504015 100644 --- a/src/api/resources/unstable/resources/aiContentSource/types/ContentSource.ts +++ b/src/api/resources/unstable/resources/aiContentSource/types/ContentSource.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The content source used by AI Agent in the conversation. @@ -17,10 +15,7 @@ export interface ContentSource { } export namespace ContentSource { - /** - * The type of the content source. - */ - export type ContentType = "file" | "article" | "external_content" | "content_snippet" | "workflow_connector_action"; + /** The type of the content source. */ export const ContentType = { File: "file", Article: "article", @@ -28,4 +23,5 @@ export namespace ContentSource { ContentSnippet: "content_snippet", WorkflowConnectorAction: "workflow_connector_action", } as const; + export type ContentType = (typeof ContentType)[keyof typeof ContentType]; } diff --git a/src/api/resources/unstable/resources/aiContentSource/types/index.ts b/src/api/resources/unstable/resources/aiContentSource/types/index.ts index 68047f7e..190780ca 100644 --- a/src/api/resources/unstable/resources/aiContentSource/types/index.ts +++ b/src/api/resources/unstable/resources/aiContentSource/types/index.ts @@ -1 +1 @@ -export * from "./ContentSource"; +export * from "./ContentSource.js"; diff --git a/src/api/resources/unstable/resources/articles/client/Client.ts b/src/api/resources/unstable/resources/articles/client/Client.ts index ec87cbce..5ab11f3e 100644 --- a/src/api/resources/unstable/resources/articles/client/Client.ts +++ b/src/api/resources/unstable/resources/articles/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Articles { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ArticlesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Articles */ -export class Articles { - constructor(protected readonly _options: Articles.Options = {}) {} +export class ArticlesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ArticlesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all articles by making a GET request to `https://api.intercom.io/articles`. @@ -82,7 +32,7 @@ export class Articles { * > * > Articles will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated articles first. * - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -90,38 +40,36 @@ export class Articles { * await client.unstable.articles.listArticles() */ public listArticles( - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listArticles(requestOptions)); } private async __listArticles( - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ArticleList, rawResponse: _response.rawResponse }; @@ -143,28 +91,14 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles"); } /** * You can create a new article by making a POST request to `https://api.intercom.io/articles`. * * @param {unknown} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -176,40 +110,40 @@ export class Articles { */ public createArticle( request?: unknown, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createArticle(request, requestOptions)); } private async __createArticle( request?: unknown, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Article, rawResponse: _response.rawResponse }; @@ -233,28 +167,14 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /articles."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/articles"); } /** * You can fetch the details of a single article by making a GET request to `https://api.intercom.io/articles/`. * * @param {Intercom.unstable.RetrieveArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -266,40 +186,38 @@ export class Articles { */ public retrieveArticle( request: Intercom.unstable.RetrieveArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveArticle(request, requestOptions)); } private async __retrieveArticle( request: Intercom.unstable.RetrieveArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `articles/${encodeURIComponent(id)}`, + `articles/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Article, rawResponse: _response.rawResponse }; @@ -323,28 +241,14 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles/{id}"); } /** * You can delete a single article by making a DELETE request to `https://api.intercom.io/articles/`. * * @param {Intercom.unstable.DeleteArticleRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -356,40 +260,38 @@ export class Articles { */ public deleteArticle( request: Intercom.unstable.DeleteArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteArticle(request, requestOptions)); } private async __deleteArticle( request: Intercom.unstable.DeleteArticleRequest, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `articles/${encodeURIComponent(id)}`, + `articles/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -416,91 +318,76 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /articles/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/articles/{id}"); } /** * You can search for articles by making a GET request to `https://api.intercom.io/articles/search`. * * @param {Intercom.unstable.SearchArticlesRequest} request - * @param {Articles.RequestOptions} requestOptions - Request-specific configuration. + * @param {ArticlesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.articles.searchArticles({ * phrase: "Getting started", - * state: "published" + * state: "published", + * help_center_id: 1, + * highlight: true * }) */ public searchArticles( request: Intercom.unstable.SearchArticlesRequest = {}, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__searchArticles(request, requestOptions)); } private async __searchArticles( request: Intercom.unstable.SearchArticlesRequest = {}, - requestOptions?: Articles.RequestOptions, + requestOptions?: ArticlesClient.RequestOptions, ): Promise> { const { phrase, state, help_center_id: helpCenterId, highlight } = request; const _queryParams: Record = {}; if (phrase != null) { - _queryParams["phrase"] = phrase; + _queryParams.phrase = phrase; } if (state != null) { - _queryParams["state"] = state; + _queryParams.state = state; } if (helpCenterId != null) { - _queryParams["help_center_id"] = helpCenterId.toString(); + _queryParams.help_center_id = helpCenterId.toString(); } if (highlight != null) { - _queryParams["highlight"] = highlight.toString(); + _queryParams.highlight = highlight.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "articles/search", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -525,32 +412,6 @@ export class Articles { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /articles/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/articles/search"); } } diff --git a/src/api/resources/unstable/resources/articles/client/index.ts b/src/api/resources/unstable/resources/articles/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/articles/client/index.ts +++ b/src/api/resources/unstable/resources/articles/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/articles/client/requests/DeleteArticleRequest.ts b/src/api/resources/unstable/resources/articles/client/requests/DeleteArticleRequest.ts index 51b8ba6a..3429b3ea 100644 --- a/src/api/resources/unstable/resources/articles/client/requests/DeleteArticleRequest.ts +++ b/src/api/resources/unstable/resources/articles/client/requests/DeleteArticleRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteArticleRequest { - /** - * The unique identifier for the article which is given by Intercom. - */ + /** The unique identifier for the article which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/articles/client/requests/RetrieveArticleRequest.ts b/src/api/resources/unstable/resources/articles/client/requests/RetrieveArticleRequest.ts index d9920ed0..b1b95775 100644 --- a/src/api/resources/unstable/resources/articles/client/requests/RetrieveArticleRequest.ts +++ b/src/api/resources/unstable/resources/articles/client/requests/RetrieveArticleRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveArticleRequest { - /** - * The unique identifier for the article which is given by Intercom. - */ + /** The unique identifier for the article which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/articles/client/requests/SearchArticlesRequest.ts b/src/api/resources/unstable/resources/articles/client/requests/SearchArticlesRequest.ts index 7c07777d..3416dd98 100644 --- a/src/api/resources/unstable/resources/articles/client/requests/SearchArticlesRequest.ts +++ b/src/api/resources/unstable/resources/articles/client/requests/SearchArticlesRequest.ts @@ -1,29 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * phrase: "Getting started", - * state: "published" + * state: "published", + * help_center_id: 1, + * highlight: true * } */ export interface SearchArticlesRequest { - /** - * The phrase within your articles to search for. - */ + /** The phrase within your articles to search for. */ phrase?: string; - /** - * The state of the Articles returned. One of `published`, `draft` or `all`. - */ + /** The state of the Articles returned. One of `published`, `draft` or `all`. */ state?: string; - /** - * The ID of the Help Center to search in. - */ + /** The ID of the Help Center to search in. */ help_center_id?: number; - /** - * Return a highlighted version of the matching content within your articles. Refer to the response schema for more details. - */ + /** Return a highlighted version of the matching content within your articles. Refer to the response schema for more details. */ highlight?: boolean; } diff --git a/src/api/resources/unstable/resources/articles/client/requests/index.ts b/src/api/resources/unstable/resources/articles/client/requests/index.ts index a0beaf5f..e0a15786 100644 --- a/src/api/resources/unstable/resources/articles/client/requests/index.ts +++ b/src/api/resources/unstable/resources/articles/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type RetrieveArticleRequest } from "./RetrieveArticleRequest"; -export { type DeleteArticleRequest } from "./DeleteArticleRequest"; -export { type SearchArticlesRequest } from "./SearchArticlesRequest"; +export type { DeleteArticleRequest } from "./DeleteArticleRequest.js"; +export type { RetrieveArticleRequest } from "./RetrieveArticleRequest.js"; +export type { SearchArticlesRequest } from "./SearchArticlesRequest.js"; diff --git a/src/api/resources/unstable/resources/articles/index.ts b/src/api/resources/unstable/resources/articles/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/articles/index.ts +++ b/src/api/resources/unstable/resources/articles/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/articles/types/Article.ts b/src/api/resources/unstable/resources/articles/types/Article.ts index adb8fda9..cab08a5d 100644 --- a/src/api/resources/unstable/resources/articles/types/Article.ts +++ b/src/api/resources/unstable/resources/articles/types/Article.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * The Articles API is a central place to gather all information and take actions on your articles. Articles can live within collections and sections, or alternatively they can stand alone. diff --git a/src/api/resources/unstable/resources/articles/types/ArticleListItem.ts b/src/api/resources/unstable/resources/articles/types/ArticleListItem.ts index 01c385fe..9c33e430 100644 --- a/src/api/resources/unstable/resources/articles/types/ArticleListItem.ts +++ b/src/api/resources/unstable/resources/articles/types/ArticleListItem.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * The data returned about your articles when you list them. @@ -42,12 +40,10 @@ export interface ArticleListItem { } export namespace ArticleListItem { - /** - * Whether the article is `published` or is a `draft`. For multilingual articles, this will be the state of the default language's content. - */ - export type State = "published" | "draft"; + /** Whether the article is `published` or is a `draft`. For multilingual articles, this will be the state of the default language's content. */ export const State = { Published: "published", Draft: "draft", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/resources/articles/types/ArticleSearchHighlights.ts b/src/api/resources/unstable/resources/articles/types/ArticleSearchHighlights.ts index 5e1f607b..c80f22fa 100644 --- a/src/api/resources/unstable/resources/articles/types/ArticleSearchHighlights.ts +++ b/src/api/resources/unstable/resources/articles/types/ArticleSearchHighlights.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The highlighted results of an Article search. In the examples provided my search query is always "my query". @@ -29,14 +27,12 @@ export namespace ArticleSearchHighlights { } export namespace Item { - /** - * The type of text - `highlight` or `plain`. - */ - export type Type = "highlight" | "plain"; + /** The type of text - `highlight` or `plain`. */ export const Type = { Highlight: "highlight", Plain: "plain", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } @@ -54,14 +50,12 @@ export namespace ArticleSearchHighlights { } export namespace Item { - /** - * The type of text - `highlight` or `plain`. - */ - export type Type = "highlight" | "plain"; + /** The type of text - `highlight` or `plain`. */ export const Type = { Highlight: "highlight", Plain: "plain", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } } diff --git a/src/api/resources/unstable/resources/articles/types/ArticleSearchResponse.ts b/src/api/resources/unstable/resources/articles/types/ArticleSearchResponse.ts index 38cd179a..71b72609 100644 --- a/src/api/resources/unstable/resources/articles/types/ArticleSearchResponse.ts +++ b/src/api/resources/unstable/resources/articles/types/ArticleSearchResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * The results of an Article search diff --git a/src/api/resources/unstable/resources/articles/types/InternalArticle.ts b/src/api/resources/unstable/resources/articles/types/InternalArticle.ts new file mode 100644 index 00000000..9cea2830 --- /dev/null +++ b/src/api/resources/unstable/resources/articles/types/InternalArticle.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * The Internal Articles API is a central place to gather all information and take actions on your internal articles. + */ +export type InternalArticle = Intercom.unstable.InternalArticleListItem; diff --git a/src/api/resources/unstable/resources/articles/types/index.ts b/src/api/resources/unstable/resources/articles/types/index.ts index 815412c7..ac1a15f9 100644 --- a/src/api/resources/unstable/resources/articles/types/index.ts +++ b/src/api/resources/unstable/resources/articles/types/index.ts @@ -1,4 +1,5 @@ -export * from "./Article"; -export * from "./ArticleListItem"; -export * from "./ArticleSearchHighlights"; -export * from "./ArticleSearchResponse"; +export * from "./Article.js"; +export * from "./ArticleListItem.js"; +export * from "./ArticleSearchHighlights.js"; +export * from "./ArticleSearchResponse.js"; +export * from "./InternalArticle.js"; diff --git a/src/api/resources/unstable/resources/awayStatusReasons/client/Client.ts b/src/api/resources/unstable/resources/awayStatusReasons/client/Client.ts index 9ff1532d..5be942d3 100644 --- a/src/api/resources/unstable/resources/awayStatusReasons/client/Client.ts +++ b/src/api/resources/unstable/resources/awayStatusReasons/client/Client.ts @@ -1,84 +1,34 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace AwayStatusReasons { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace AwayStatusReasonsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Away Status Reasons */ -export class AwayStatusReasons { - constructor(protected readonly _options: AwayStatusReasons.Options = {}) {} +export class AwayStatusReasonsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: AwayStatusReasonsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * Returns a list of all away status reasons configured for the workspace, including deleted ones. * - * @param {AwayStatusReasons.RequestOptions} requestOptions - Request-specific configuration. + * @param {AwayStatusReasonsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -86,38 +36,36 @@ export class AwayStatusReasons { * await client.unstable.awayStatusReasons.listAwayStatusReasons() */ public listAwayStatusReasons( - requestOptions?: AwayStatusReasons.RequestOptions, + requestOptions?: AwayStatusReasonsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAwayStatusReasons(requestOptions)); } private async __listAwayStatusReasons( - requestOptions?: AwayStatusReasons.RequestOptions, + requestOptions?: AwayStatusReasonsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "away_status_reasons", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.AwayStatusReason[], rawResponse: _response.rawResponse }; @@ -139,32 +87,6 @@ export class AwayStatusReasons { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /away_status_reasons."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/away_status_reasons"); } } diff --git a/src/api/resources/unstable/resources/awayStatusReasons/index.ts b/src/api/resources/unstable/resources/awayStatusReasons/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/awayStatusReasons/index.ts +++ b/src/api/resources/unstable/resources/awayStatusReasons/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/brands/client/Client.ts b/src/api/resources/unstable/resources/brands/client/Client.ts new file mode 100644 index 00000000..29540dc4 --- /dev/null +++ b/src/api/resources/unstable/resources/brands/client/Client.ts @@ -0,0 +1,167 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; + +export declare namespace BrandsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Brands + */ +export class BrandsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: BrandsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Retrieves all brands for the workspace, including the default brand. + * The default brand id always matches the workspace + * + * @param {BrandsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.brands.listBrands() + */ + public listBrands( + requestOptions?: BrandsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listBrands(requestOptions)); + } + + private async __listBrands( + requestOptions?: BrandsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "brands", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.BrandList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/brands"); + } + + /** + * Fetches a specific brand by its unique identifier + * + * @param {Intercom.unstable.RetrieveBrandRequest} request + * @param {BrandsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.brands.retrieveBrand({ + * id: "id" + * }) + */ + public retrieveBrand( + request: Intercom.unstable.RetrieveBrandRequest, + requestOptions?: BrandsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveBrand(request, requestOptions)); + } + + private async __retrieveBrand( + request: Intercom.unstable.RetrieveBrandRequest, + requestOptions?: BrandsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `brands/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.Brand, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/brands/{id}"); + } +} diff --git a/src/api/resources/unstable/resources/brands/client/index.ts b/src/api/resources/unstable/resources/brands/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/unstable/resources/brands/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/brands/client/requests/RetrieveBrandRequest.ts b/src/api/resources/unstable/resources/brands/client/requests/RetrieveBrandRequest.ts new file mode 100644 index 00000000..fc52ec4e --- /dev/null +++ b/src/api/resources/unstable/resources/brands/client/requests/RetrieveBrandRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "id" + * } + */ +export interface RetrieveBrandRequest { + /** The unique identifier of the brand */ + id: string; +} diff --git a/src/api/resources/unstable/resources/brands/client/requests/index.ts b/src/api/resources/unstable/resources/brands/client/requests/index.ts new file mode 100644 index 00000000..813c2ce1 --- /dev/null +++ b/src/api/resources/unstable/resources/brands/client/requests/index.ts @@ -0,0 +1 @@ +export type { RetrieveBrandRequest } from "./RetrieveBrandRequest.js"; diff --git a/src/api/resources/unstable/resources/brands/index.ts b/src/api/resources/unstable/resources/brands/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/unstable/resources/brands/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/brands/types/Brand.ts b/src/api/resources/unstable/resources/brands/types/Brand.ts new file mode 100644 index 00000000..53a416af --- /dev/null +++ b/src/api/resources/unstable/resources/brands/types/Brand.ts @@ -0,0 +1,23 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Represents a branding configuration for the workspace + */ +export interface Brand { + /** The type of object */ + type?: string; + /** Unique brand identifier. For default brand, matches the workspace ID */ + id?: string; + /** Display name of the brand */ + name?: string; + /** Whether this is the workspace's default brand */ + is_default?: boolean; + /** Unix timestamp of brand creation */ + created_at?: number; + /** Unix timestamp of last modification */ + updated_at?: number; + /** Associated help center identifier */ + help_center_id?: string; + /** Default email settings ID for this brand */ + default_address_settings_id?: string; +} diff --git a/src/api/resources/unstable/resources/brands/types/BrandList.ts b/src/api/resources/unstable/resources/brands/types/BrandList.ts new file mode 100644 index 00000000..3d7330de --- /dev/null +++ b/src/api/resources/unstable/resources/brands/types/BrandList.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * A list of brands + */ +export interface BrandList { + /** The type of object */ + type?: string; + data?: Intercom.unstable.Brand[]; +} diff --git a/src/api/resources/unstable/resources/brands/types/index.ts b/src/api/resources/unstable/resources/brands/types/index.ts new file mode 100644 index 00000000..c0d308e0 --- /dev/null +++ b/src/api/resources/unstable/resources/brands/types/index.ts @@ -0,0 +1,2 @@ +export * from "./Brand.js"; +export * from "./BrandList.js"; diff --git a/src/api/resources/unstable/resources/calls/client/Client.ts b/src/api/resources/unstable/resources/calls/client/Client.ts new file mode 100644 index 00000000..24f1b6f6 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/Client.ts @@ -0,0 +1,710 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; + +export declare namespace CallsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Calls + */ +export class CallsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CallsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Retrieve a paginated list of calls. + * + * @param {Intercom.unstable.ListCallsRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.calls.listCalls({ + * page: 1, + * per_page: 1 + * }) + */ + public listCalls( + request: Intercom.unstable.ListCallsRequest = {}, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listCalls(request, requestOptions)); + } + + private async __listCalls( + request: Intercom.unstable.ListCallsRequest = {}, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { page, per_page: perPage } = request; + const _queryParams: Record = {}; + if (page != null) { + _queryParams.page = page.toString(); + } + + if (perPage != null) { + _queryParams.per_page = perPage.toString(); + } + + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "calls", + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.CallList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls"); + } + + /** + * Retrieve a single call by id. + * + * @param {Intercom.unstable.ShowCallRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.showCall({ + * id: "id" + * }) + */ + public showCall( + request: Intercom.unstable.ShowCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCall(request, requestOptions)); + } + + private async __showCall( + request: Intercom.unstable.ShowCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.Call, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{id}"); + } + + /** + * Redirects to a signed URL for the call's recording if it exists. + * + * @param {Intercom.unstable.ShowCallRecordingRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.showCallRecording({ + * id: "id" + * }) + */ + public showCallRecording( + request: Intercom.unstable.ShowCallRecordingRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCallRecording(request, requestOptions)); + } + + private async __showCallRecording( + request: Intercom.unstable.ShowCallRecordingRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(id)}/recording`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: undefined, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{id}/recording"); + } + + /** + * Returns the transcript for the specified call as a downloadable text file. + * + * @param {Intercom.unstable.ShowCallTranscriptRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.showCallTranscript({ + * id: "id" + * }) + */ + public showCallTranscript( + request: Intercom.unstable.ShowCallTranscriptRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__showCallTranscript(request, requestOptions)); + } + + private async __showCallTranscript( + request: Intercom.unstable.ShowCallTranscriptRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `calls/${core.url.encodePathParam(id)}/transcript`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + responseType: "text", + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as string, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/calls/{id}/transcript"); + } + + /** + * Retrieve calls by a list of conversation ids and include transcripts when available. + * A maximum of 20 `conversation_ids` can be provided. If none are provided or more than 20 are provided, a 400 error is returned. + * + * @param {Intercom.unstable.ListCallsWithTranscriptsRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.BadRequestError} + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.calls.listCallsWithTranscripts({ + * conversation_ids: ["64619700005694", "64619700005695"] + * }) + */ + public listCallsWithTranscripts( + request: Intercom.unstable.ListCallsWithTranscriptsRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listCallsWithTranscripts(request, requestOptions)); + } + + private async __listCallsWithTranscripts( + request: Intercom.unstable.ListCallsWithTranscriptsRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "calls/search", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.unstable.ListCallsWithTranscriptsResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.unstable.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/calls/search"); + } + + /** + * Register a Fin Voice call with Intercom. This endpoint creates an external reference + * that links an external call identifier to an Intercom call and conversation. + * + * The call can be from different sources: + * - AWS Connect (default) + * - Five9 + * - Zoom Phone + * + * @param {Intercom.unstable.RegisterFinVoiceCallRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.BadRequestError} + * @throws {@link Intercom.unstable.ConflictError} + * + * @example + * await client.unstable.calls.registerFinVoiceCall({ + * phone_number: "+1234567890", + * call_id: "call-123-abc" + * }) + */ + public registerFinVoiceCall( + request?: Intercom.unstable.RegisterFinVoiceCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__registerFinVoiceCall(request, requestOptions)); + } + + private async __registerFinVoiceCall( + request?: Intercom.unstable.RegisterFinVoiceCallRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "fin_voice/register", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.AiCallResponse, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.unstable.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 409: + throw new Intercom.unstable.ConflictError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/fin_voice/register"); + } + + /** + * Retrieve information about a Fin Voice call using the external reference ID. + * + * @param {Intercom.unstable.CollectFinVoiceCallByIdRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.collectFinVoiceCallById({ + * id: 1 + * }) + */ + public collectFinVoiceCallById( + request: Intercom.unstable.CollectFinVoiceCallByIdRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallById(request, requestOptions)); + } + + private async __collectFinVoiceCallById( + request: Intercom.unstable.CollectFinVoiceCallByIdRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `fin_voice/collect/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.AiCallResponse, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/fin_voice/collect/{id}"); + } + + /** + * Retrieve information about a Fin Voice call using the external call identifier. + * + * @param {Intercom.unstable.CollectFinVoiceCallByExternalIdRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.collectFinVoiceCallByExternalId({ + * external_id: "external_id" + * }) + */ + public collectFinVoiceCallByExternalId( + request: Intercom.unstable.CollectFinVoiceCallByExternalIdRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallByExternalId(request, requestOptions)); + } + + private async __collectFinVoiceCallByExternalId( + request: Intercom.unstable.CollectFinVoiceCallByExternalIdRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { external_id: externalId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `fin_voice/external_id/${core.url.encodePathParam(externalId)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.AiCallResponse, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/fin_voice/external_id/{external_id}", + ); + } + + /** + * Retrieve information about a Fin Voice call using the phone number. + * + * Returns the most recent matched call for the given phone number, ordered by creation date. + * + * @param {Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest} request + * @param {CallsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.calls.collectFinVoiceCallByPhoneNumber({ + * phone_number: "phone_number" + * }) + */ + public collectFinVoiceCallByPhoneNumber( + request: Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest, + requestOptions?: CallsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__collectFinVoiceCallByPhoneNumber(request, requestOptions)); + } + + private async __collectFinVoiceCallByPhoneNumber( + request: Intercom.unstable.CollectFinVoiceCallByPhoneNumberRequest, + requestOptions?: CallsClient.RequestOptions, + ): Promise> { + const { phone_number: phoneNumber } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `fin_voice/phone_number/${core.url.encodePathParam(phoneNumber)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.Error_, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/fin_voice/phone_number/{phone_number}", + ); + } +} diff --git a/src/api/resources/unstable/resources/calls/client/index.ts b/src/api/resources/unstable/resources/calls/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByExternalIdRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByExternalIdRequest.ts new file mode 100644 index 00000000..1cdf7af4 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByExternalIdRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * external_id: "external_id" + * } + */ +export interface CollectFinVoiceCallByExternalIdRequest { + /** The external call identifier from the call provider */ + external_id: string; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByIdRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByIdRequest.ts new file mode 100644 index 00000000..f3587f16 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByIdRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: 1 + * } + */ +export interface CollectFinVoiceCallByIdRequest { + /** The external reference ID */ + id: number; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByPhoneNumberRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByPhoneNumberRequest.ts new file mode 100644 index 00000000..145f26e3 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/CollectFinVoiceCallByPhoneNumberRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * phone_number: "phone_number" + * } + */ +export interface CollectFinVoiceCallByPhoneNumberRequest { + /** Phone number in E.164 format */ + phone_number: string; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/ListCallsRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/ListCallsRequest.ts new file mode 100644 index 00000000..74c29012 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/ListCallsRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * page: 1, + * per_page: 1 + * } + */ +export interface ListCallsRequest { + /** The page of results to fetch. Defaults to first page */ + page?: number; + /** How many results to display per page. Defaults to 25. Max 25. */ + per_page?: number; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts new file mode 100644 index 00000000..92d644c1 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/ListCallsWithTranscriptsRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * conversation_ids: ["64619700005694", "64619700005695"] + * } + */ +export interface ListCallsWithTranscriptsRequest { + /** A list of conversation ids to fetch calls for. Maximum 20. */ + conversation_ids: string[]; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/ShowCallRecordingRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/ShowCallRecordingRequest.ts new file mode 100644 index 00000000..e17a6c0f --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/ShowCallRecordingRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "id" + * } + */ +export interface ShowCallRecordingRequest { + /** The id of the call */ + id: string; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/ShowCallRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/ShowCallRequest.ts new file mode 100644 index 00000000..ee5cddee --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/ShowCallRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "id" + * } + */ +export interface ShowCallRequest { + /** The id of the call to retrieve */ + id: string; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/ShowCallTranscriptRequest.ts b/src/api/resources/unstable/resources/calls/client/requests/ShowCallTranscriptRequest.ts new file mode 100644 index 00000000..a21f329d --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/ShowCallTranscriptRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "id" + * } + */ +export interface ShowCallTranscriptRequest { + /** The id of the call */ + id: string; +} diff --git a/src/api/resources/unstable/resources/calls/client/requests/index.ts b/src/api/resources/unstable/resources/calls/client/requests/index.ts new file mode 100644 index 00000000..d1c18782 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/client/requests/index.ts @@ -0,0 +1,8 @@ +export type { CollectFinVoiceCallByExternalIdRequest } from "./CollectFinVoiceCallByExternalIdRequest.js"; +export type { CollectFinVoiceCallByIdRequest } from "./CollectFinVoiceCallByIdRequest.js"; +export type { CollectFinVoiceCallByPhoneNumberRequest } from "./CollectFinVoiceCallByPhoneNumberRequest.js"; +export type { ListCallsRequest } from "./ListCallsRequest.js"; +export type { ListCallsWithTranscriptsRequest } from "./ListCallsWithTranscriptsRequest.js"; +export type { ShowCallRecordingRequest } from "./ShowCallRecordingRequest.js"; +export type { ShowCallRequest } from "./ShowCallRequest.js"; +export type { ShowCallTranscriptRequest } from "./ShowCallTranscriptRequest.js"; diff --git a/src/api/resources/unstable/resources/calls/index.ts b/src/api/resources/unstable/resources/calls/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/unstable/resources/calls/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/calls/types/Call.ts b/src/api/resources/unstable/resources/calls/types/Call.ts new file mode 100644 index 00000000..18bb1be3 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/types/Call.ts @@ -0,0 +1,42 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * Represents a phone call in Intercom + */ +export interface Call { + /** String representing the object's type. Always has the value `call`. */ + type?: string; + /** The id of the call. */ + id?: string; + /** The id of the conversation associated with the call, if any. */ + conversation_id?: string; + /** The id of the admin associated with the call, if any. */ + admin_id?: string; + /** The id of the contact associated with the call, if any. */ + contact_id?: string; + /** The current state of the call. */ + state?: string; + initiated_at?: Intercom.unstable.Datetime; + answered_at?: Intercom.unstable.Datetime; + ended_at?: Intercom.unstable.Datetime; + created_at?: Intercom.unstable.Datetime; + updated_at?: Intercom.unstable.Datetime; + /** API URL to download or redirect to the call recording if available. */ + recording_url?: string; + /** API URL to the call transcript if available. */ + transcription_url?: string; + /** The type of call. */ + call_type?: string; + /** The direction of the call. */ + direction?: string; + /** The reason for the call end, if applicable. */ + ended_reason?: string; + /** The phone number involved in the call, in E.164 format. */ + phone?: string; + /** API URL to the AI Agent (Fin) call recording if available. */ + fin_recording_url?: string; + /** API URL to the AI Agent (Fin) call transcript if available. */ + fin_transcription_url?: string; +} diff --git a/src/api/resources/unstable/resources/calls/types/ListCallsWithTranscriptsResponse.ts b/src/api/resources/unstable/resources/calls/types/ListCallsWithTranscriptsResponse.ts new file mode 100644 index 00000000..ec066741 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/types/ListCallsWithTranscriptsResponse.ts @@ -0,0 +1,21 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +export interface ListCallsWithTranscriptsResponse { + type?: string; + data?: ListCallsWithTranscriptsResponse.Data.Item[]; +} + +export namespace ListCallsWithTranscriptsResponse { + export type Data = Data.Item[]; + + export namespace Data { + export interface Item extends Intercom.unstable.Call { + /** The call transcript if available, otherwise an empty array. */ + transcript?: Record[]; + /** The status of the transcript if available. */ + transcript_status?: string; + } + } +} diff --git a/src/api/resources/unstable/resources/calls/types/index.ts b/src/api/resources/unstable/resources/calls/types/index.ts new file mode 100644 index 00000000..a7b7c7f7 --- /dev/null +++ b/src/api/resources/unstable/resources/calls/types/index.ts @@ -0,0 +1,2 @@ +export * from "./Call.js"; +export * from "./ListCallsWithTranscriptsResponse.js"; diff --git a/src/api/resources/unstable/resources/companies/client/Client.ts b/src/api/resources/unstable/resources/companies/client/Client.ts index b5593293..575c345d 100644 --- a/src/api/resources/unstable/resources/companies/client/Client.ts +++ b/src/api/resources/unstable/resources/companies/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Companies { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace CompaniesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Companies */ -export class Companies { - constructor(protected readonly _options: Companies.Options = {}) {} +export class CompaniesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CompaniesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a single company by passing in `company_id` or `name`. @@ -89,7 +39,7 @@ export class Companies { * `https://api.intercom.io/companies?segment_id={segment_id}` * * @param {Intercom.unstable.RetrieveCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -99,71 +49,70 @@ export class Companies { * name: "my company", * company_id: "12345", * tag_id: "678910", - * segment_id: "98765" + * segment_id: "98765", + * page: 1, + * per_page: 1 * }) */ public retrieveCompany( request: Intercom.unstable.RetrieveCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveCompany(request, requestOptions)); } private async __retrieveCompany( request: Intercom.unstable.RetrieveCompanyRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { name, company_id: companyId, tag_id: tagId, segment_id: segmentId, page, per_page: perPage } = request; const _queryParams: Record = {}; if (name != null) { - _queryParams["name"] = name; + _queryParams.name = name; } if (companyId != null) { - _queryParams["company_id"] = companyId; + _queryParams.company_id = companyId; } if (tagId != null) { - _queryParams["tag_id"] = tagId; + _queryParams.tag_id = tagId; } if (segmentId != null) { - _queryParams["segment_id"] = segmentId; + _queryParams.segment_id = segmentId; } if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.CompanyList, rawResponse: _response.rawResponse }; @@ -187,21 +136,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies"); } /** @@ -216,7 +151,7 @@ export class Companies { * {% /admonition %} * * @param {unknown} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -228,40 +163,40 @@ export class Companies { */ public createOrUpdateCompany( request?: unknown, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createOrUpdateCompany(request, requestOptions)); } private async __createOrUpdateCompany( request?: unknown, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Company, rawResponse: _response.rawResponse }; @@ -285,28 +220,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/companies"); } /** * You can fetch a single company. * * @param {Intercom.unstable.RetrieveACompanyByIdRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -318,40 +239,38 @@ export class Companies { */ public retrieveACompanyById( request: Intercom.unstable.RetrieveACompanyByIdRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveACompanyById(request, requestOptions)); } private async __retrieveACompanyById( request: Intercom.unstable.RetrieveACompanyByIdRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(id)}`, + `companies/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Company, rawResponse: _response.rawResponse }; @@ -375,21 +294,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/{id}"); } /** @@ -400,7 +305,7 @@ export class Companies { * {% /admonition %} * * @param {Intercom.unstable.UpdateCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -412,40 +317,38 @@ export class Companies { */ public updateCompany( request: Intercom.unstable.UpdateCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateCompany(request, requestOptions)); } private async __updateCompany( request: Intercom.unstable.UpdateCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(id)}`, + `companies/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Company, rawResponse: _response.rawResponse }; @@ -469,28 +372,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /companies/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/companies/{id}"); } /** * You can delete a single company. * * @param {Intercom.unstable.DeleteCompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -502,40 +391,38 @@ export class Companies { */ public deleteCompany( request: Intercom.unstable.DeleteCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteCompany(request, requestOptions)); } private async __deleteCompany( request: Intercom.unstable.DeleteCompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(id)}`, + `companies/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -562,28 +449,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /companies/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/companies/{id}"); } /** * You can fetch a list of all contacts that belong to a company. * * @param {Intercom.unstable.ListAttachedContactsRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -595,40 +468,38 @@ export class Companies { */ public listAttachedContacts( request: Intercom.unstable.ListAttachedContactsRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedContacts(request, requestOptions)); } private async __listAttachedContacts( request: Intercom.unstable.ListAttachedContactsRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(id)}/contacts`, + `companies/${core.url.encodePathParam(id)}/contacts`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -655,28 +526,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/{id}/contacts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/{id}/contacts"); } /** * You can fetch a list of all segments that belong to a company. * * @param {Intercom.unstable.ListAttachedSegmentsForCompaniesRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -688,40 +545,38 @@ export class Companies { */ public listAttachedSegmentsForCompanies( request: Intercom.unstable.ListAttachedSegmentsForCompaniesRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAttachedSegmentsForCompanies(request, requestOptions)); } private async __listAttachedSegmentsForCompanies( request: Intercom.unstable.ListAttachedSegmentsForCompaniesRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `companies/${encodeURIComponent(id)}/segments`, + `companies/${core.url.encodePathParam(id)}/segments`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -748,21 +603,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/{id}/segments."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/{id}/segments"); } /** @@ -777,65 +618,64 @@ export class Companies { * {% /admonition %} * * @param {Intercom.unstable.ListAllCompaniesRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.companies.listAllCompanies({ + * page: 1, + * per_page: 1, * order: "desc" * }) */ public listAllCompanies( request: Intercom.unstable.ListAllCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAllCompanies(request, requestOptions)); } private async __listAllCompanies( request: Intercom.unstable.ListAllCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { page, per_page: perPage, order } = request; const _queryParams: Record = {}; if (page != null) { - _queryParams["page"] = page.toString(); + _queryParams.page = page.toString(); } if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (order != null) { - _queryParams["order"] = order; + _queryParams.order = order; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies/list", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.CompanyList, rawResponse: _response.rawResponse }; @@ -857,21 +697,7 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /companies/list."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/companies/list"); } /** @@ -892,55 +718,54 @@ export class Companies { * {% /admonition %} * * @param {Intercom.unstable.ScrollOverAllCompaniesRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example - * await client.unstable.companies.scrollOverAllCompanies() + * await client.unstable.companies.scrollOverAllCompanies({ + * scroll_param: "scroll_param" + * }) */ public scrollOverAllCompanies( request: Intercom.unstable.ScrollOverAllCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__scrollOverAllCompanies(request, requestOptions)); } private async __scrollOverAllCompanies( request: Intercom.unstable.ScrollOverAllCompaniesRequest = {}, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { scroll_param: scrollParam } = request; const _queryParams: Record = {}; if (scrollParam != null) { - _queryParams["scroll_param"] = scrollParam; + _queryParams.scroll_param = scrollParam; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "companies/scroll", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -965,28 +790,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /companies/scroll."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/scroll"); } /** * You can attach a company to a single contact. * * @param {Intercom.unstable.AttachContactToACompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -1012,41 +823,41 @@ export class Companies { */ public attachContactToACompany( request: Intercom.unstable.AttachContactToACompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachContactToACompany(request, requestOptions)); } private async __attachContactToACompany( request: Intercom.unstable.AttachContactToACompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/companies`, + `contacts/${core.url.encodePathParam(id)}/companies`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Company, rawResponse: _response.rawResponse }; @@ -1072,28 +883,14 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/{id}/companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{id}/companies"); } /** * You can detach a company from a single contact. * * @param {Intercom.unstable.DetachContactFromACompanyRequest} request - * @param {Companies.RequestOptions} requestOptions - Request-specific configuration. + * @param {CompaniesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -1106,40 +903,38 @@ export class Companies { */ public detachContactFromACompany( request: Intercom.unstable.DetachContactFromACompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachContactFromACompany(request, requestOptions)); } private async __detachContactFromACompany( request: Intercom.unstable.DetachContactFromACompanyRequest, - requestOptions?: Companies.RequestOptions, + requestOptions?: CompaniesClient.RequestOptions, ): Promise> { const { contact_id: contactId, id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/companies/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(contactId)}/companies/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Company, rawResponse: _response.rawResponse }; @@ -1163,34 +958,11 @@ export class Companies { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/companies/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/companies/{id}", + ); } } diff --git a/src/api/resources/unstable/resources/companies/client/index.ts b/src/api/resources/unstable/resources/companies/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/companies/client/index.ts +++ b/src/api/resources/unstable/resources/companies/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/companies/client/requests/AttachContactToACompanyRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/AttachContactToACompanyRequest.ts index d82657ba..fbab4ca6 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/AttachContactToACompanyRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/AttachContactToACompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -22,9 +20,7 @@ * } */ export interface AttachContactToACompanyRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ id: string; /** The unique identifier for the company which is given by Intercom */ company_id: string; diff --git a/src/api/resources/unstable/resources/companies/client/requests/DeleteCompanyRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/DeleteCompanyRequest.ts index abe9080b..e1ad8abe 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/DeleteCompanyRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/DeleteCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/DetachContactFromACompanyRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/DetachContactFromACompanyRequest.ts index 3cbcb14d..b80801fa 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/DetachContactFromACompanyRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/DetachContactFromACompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DetachContactFromACompanyRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/ListAllCompaniesRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/ListAllCompaniesRequest.ts index 0829eab0..86b2ef07 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/ListAllCompaniesRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/ListAllCompaniesRequest.ts @@ -1,24 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { + * page: 1, + * per_page: 1, * order: "desc" * } */ export interface ListAllCompaniesRequest { - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to return per page. Defaults to 15 - */ + /** How many results to return per page. Defaults to 15 */ per_page?: number; - /** - * `asc` or `desc`. Return the companies in ascending or descending order. Defaults to desc - */ + /** `asc` or `desc`. Return the companies in ascending or descending order. Defaults to desc */ order?: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/ListAttachedContactsRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/ListAttachedContactsRequest.ts index 0dc176ea..e49c7dca 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/ListAttachedContactsRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/ListAttachedContactsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListAttachedContactsRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/ListAttachedSegmentsForCompaniesRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/ListAttachedSegmentsForCompaniesRequest.ts index 3e2c05a4..31d3c9d9 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/ListAttachedSegmentsForCompaniesRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/ListAttachedSegmentsForCompaniesRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListAttachedSegmentsForCompaniesRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/RetrieveACompanyByIdRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/RetrieveACompanyByIdRequest.ts index 8b4afb24..f53eaada 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/RetrieveACompanyByIdRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/RetrieveACompanyByIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveACompanyByIdRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/RetrieveCompanyRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/RetrieveCompanyRequest.ts index 557a2e00..a3314297 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/RetrieveCompanyRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/RetrieveCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -8,32 +6,22 @@ * name: "my company", * company_id: "12345", * tag_id: "678910", - * segment_id: "98765" + * segment_id: "98765", + * page: 1, + * per_page: 1 * } */ export interface RetrieveCompanyRequest { - /** - * The `name` of the company to filter by. - */ + /** The `name` of the company to filter by. */ name?: string; - /** - * The `company_id` of the company to filter by. - */ + /** The `company_id` of the company to filter by. */ company_id?: string; - /** - * The `tag_id` of the company to filter by. - */ + /** The `tag_id` of the company to filter by. */ tag_id?: string; - /** - * The `segment_id` of the company to filter by. - */ + /** The `segment_id` of the company to filter by. */ segment_id?: string; - /** - * The page of results to fetch. Defaults to first page - */ + /** The page of results to fetch. Defaults to first page */ page?: number; - /** - * How many results to display per page. Defaults to 15 - */ + /** How many results to display per page. Defaults to 15 */ per_page?: number; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/ScrollOverAllCompaniesRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/ScrollOverAllCompaniesRequest.ts index 9d7a6877..68f2ed8b 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/ScrollOverAllCompaniesRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/ScrollOverAllCompaniesRequest.ts @@ -1,14 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * scroll_param: "scroll_param" + * } */ export interface ScrollOverAllCompaniesRequest { - /** - * - */ + /** */ scroll_param?: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/UpdateCompanyRequest.ts b/src/api/resources/unstable/resources/companies/client/requests/UpdateCompanyRequest.ts index 1b2d26a4..b63f71c5 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/UpdateCompanyRequest.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/UpdateCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface UpdateCompanyRequest { - /** - * The unique identifier for the company which is given by Intercom - */ + /** The unique identifier for the company which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/companies/client/requests/index.ts b/src/api/resources/unstable/resources/companies/client/requests/index.ts index 2db00d94..7bdff9f7 100644 --- a/src/api/resources/unstable/resources/companies/client/requests/index.ts +++ b/src/api/resources/unstable/resources/companies/client/requests/index.ts @@ -1,10 +1,10 @@ -export { type RetrieveCompanyRequest } from "./RetrieveCompanyRequest"; -export { type RetrieveACompanyByIdRequest } from "./RetrieveACompanyByIdRequest"; -export { type UpdateCompanyRequest } from "./UpdateCompanyRequest"; -export { type DeleteCompanyRequest } from "./DeleteCompanyRequest"; -export { type ListAttachedContactsRequest } from "./ListAttachedContactsRequest"; -export { type ListAttachedSegmentsForCompaniesRequest } from "./ListAttachedSegmentsForCompaniesRequest"; -export { type ListAllCompaniesRequest } from "./ListAllCompaniesRequest"; -export { type ScrollOverAllCompaniesRequest } from "./ScrollOverAllCompaniesRequest"; -export { type AttachContactToACompanyRequest } from "./AttachContactToACompanyRequest"; -export { type DetachContactFromACompanyRequest } from "./DetachContactFromACompanyRequest"; +export type { AttachContactToACompanyRequest } from "./AttachContactToACompanyRequest.js"; +export type { DeleteCompanyRequest } from "./DeleteCompanyRequest.js"; +export type { DetachContactFromACompanyRequest } from "./DetachContactFromACompanyRequest.js"; +export type { ListAllCompaniesRequest } from "./ListAllCompaniesRequest.js"; +export type { ListAttachedContactsRequest } from "./ListAttachedContactsRequest.js"; +export type { ListAttachedSegmentsForCompaniesRequest } from "./ListAttachedSegmentsForCompaniesRequest.js"; +export type { RetrieveACompanyByIdRequest } from "./RetrieveACompanyByIdRequest.js"; +export type { RetrieveCompanyRequest } from "./RetrieveCompanyRequest.js"; +export type { ScrollOverAllCompaniesRequest } from "./ScrollOverAllCompaniesRequest.js"; +export type { UpdateCompanyRequest } from "./UpdateCompanyRequest.js"; diff --git a/src/api/resources/unstable/resources/companies/index.ts b/src/api/resources/unstable/resources/companies/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/companies/index.ts +++ b/src/api/resources/unstable/resources/companies/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/companies/types/Company.ts b/src/api/resources/unstable/resources/companies/types/Company.ts index ebce2925..d2569495 100644 --- a/src/api/resources/unstable/resources/companies/types/Company.ts +++ b/src/api/resources/unstable/resources/companies/types/Company.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Companies allow you to represent organizations using your product. Each company will have its own description and be associated with contacts. You can fetch, create, update and list companies. @@ -45,6 +43,8 @@ export interface Company { tags?: Company.Tags; /** The list of segments associated with the company */ segments?: Company.Segments; + /** The list of notes associated with the company */ + notes?: Company.Notes; } export namespace Company { @@ -74,4 +74,13 @@ export namespace Company { type?: "segment.list"; segments?: Intercom.unstable.Segment[]; } + + /** + * The list of notes associated with the company + */ + export interface Notes { + /** The type of the object */ + type?: "note.list"; + notes?: Intercom.unstable.CompanyNote[]; + } } diff --git a/src/api/resources/unstable/resources/companies/types/index.ts b/src/api/resources/unstable/resources/companies/types/index.ts index d15bbd39..19a19f61 100644 --- a/src/api/resources/unstable/resources/companies/types/index.ts +++ b/src/api/resources/unstable/resources/companies/types/index.ts @@ -1 +1 @@ -export * from "./Company"; +export * from "./Company.js"; diff --git a/src/api/resources/unstable/resources/contacts/client/Client.ts b/src/api/resources/unstable/resources/contacts/client/Client.ts index 432c912e..531e8b52 100644 --- a/src/api/resources/unstable/resources/contacts/client/Client.ts +++ b/src/api/resources/unstable/resources/contacts/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; - -export declare namespace Contacts { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } +export declare namespace ContactsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your contacts */ -export class Contacts { - constructor(protected readonly _options: Contacts.Options = {}) {} +export class ContactsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ContactsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of companies that are associated to a contact. * * @param {Intercom.unstable.ListCompaniesForAContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -91,40 +41,38 @@ export class Contacts { */ public listCompaniesForAContact( request: Intercom.unstable.ListCompaniesForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listCompaniesForAContact(request, requestOptions)); } private async __listCompaniesForAContact( request: Intercom.unstable.ListCompaniesForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/companies`, + `contacts/${core.url.encodePathParam(id)}/companies`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -151,28 +99,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{id}/companies."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{id}/companies"); } /** * You can fetch a list of segments that are associated to a contact. * * @param {Intercom.unstable.ListSegmentsForAContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -184,40 +118,38 @@ export class Contacts { */ public listSegmentsForAContact( request: Intercom.unstable.ListSegmentsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listSegmentsForAContact(request, requestOptions)); } private async __listSegmentsForAContact( request: Intercom.unstable.ListSegmentsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/segments`, + `contacts/${core.url.encodePathParam(contactId)}/segments`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactSegments, rawResponse: _response.rawResponse }; @@ -241,23 +173,12 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/segments.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/segments", + ); } /** @@ -270,7 +191,7 @@ export class Contacts { * 2.Opt-in subscription types that the user has opted-in to receiving. * * @param {Intercom.unstable.ListSubscriptionsForAContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -282,40 +203,38 @@ export class Contacts { */ public listSubscriptionsForAContact( request: Intercom.unstable.ListSubscriptionsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listSubscriptionsForAContact(request, requestOptions)); } private async __listSubscriptionsForAContact( request: Intercom.unstable.ListSubscriptionsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -342,30 +261,19 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/{contact_id}/subscriptions.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/{contact_id}/subscriptions", + ); } /** * You can fetch a list of all tags that are attached to a specific contact. * * @param {Intercom.unstable.ListTagsForAContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -377,40 +285,38 @@ export class Contacts { */ public listTagsForAContact( request: Intercom.unstable.ListTagsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listTagsForAContact(request, requestOptions)); } private async __listTagsForAContact( request: Intercom.unstable.ListTagsForAContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { contact_id: contactId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags`, + `contacts/${core.url.encodePathParam(contactId)}/tags`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TagList, rawResponse: _response.rawResponse }; @@ -434,28 +340,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{contact_id}/tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{contact_id}/tags"); } /** * You can fetch the details of a single contact. * * @param {Intercom.unstable.ShowContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -466,40 +358,38 @@ export class Contacts { */ public showContact( request: Intercom.unstable.ShowContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__showContact(request, requestOptions)); } private async __showContact( request: Intercom.unstable.ShowContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -524,21 +414,7 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{id}"); } /** @@ -551,7 +427,7 @@ export class Contacts { * {% /admonition %} * * @param {Intercom.unstable.UpdateContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -574,41 +450,41 @@ export class Contacts { */ public updateContact( request: Intercom.unstable.UpdateContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateContact(request, requestOptions)); } private async __updateContact( request: Intercom.unstable.UpdateContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -633,28 +509,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /contacts/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/contacts/{id}"); } /** * You can delete a single contact. * * @param {Intercom.unstable.DeleteContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -665,40 +527,38 @@ export class Contacts { */ public deleteContact( request: Intercom.unstable.DeleteContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteContact(request, requestOptions)); } private async __deleteContact( request: Intercom.unstable.DeleteContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactDeleted, rawResponse: _response.rawResponse }; @@ -720,28 +580,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /contacts/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/contacts/{id}"); } /** * You can merge a contact with a `role` of `lead` into a contact with a `role` of `user`. * * @param {Intercom.unstable.MergeContactsRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -753,40 +599,40 @@ export class Contacts { */ public mergeContact( request: Intercom.unstable.MergeContactsRequest = {}, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__mergeContact(request, requestOptions)); } private async __mergeContact( request: Intercom.unstable.MergeContactsRequest = {}, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts/merge", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -811,21 +657,7 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/merge."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/merge"); } /** @@ -931,7 +763,7 @@ export class Contacts { * | $ | String | Ends With | * * @param {Intercom.unstable.SearchRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -952,40 +784,40 @@ export class Contacts { */ public searchContacts( request: Intercom.unstable.SearchRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__searchContacts(request, requestOptions)); } private async __searchContacts( request: Intercom.unstable.SearchRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactList, rawResponse: _response.rawResponse }; @@ -1007,21 +839,7 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/search"); } /** @@ -1031,7 +849,7 @@ export class Contacts { * See the [pagination section](https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#pagination-for-list-apis) for more details on how to use the `starting_after` param. * {% /admonition %} * - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -1039,38 +857,36 @@ export class Contacts { * await client.unstable.contacts.listContacts() */ public listContacts( - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listContacts(requestOptions)); } private async __listContacts( - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactList, rawResponse: _response.rawResponse }; @@ -1092,28 +908,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts"); } /** * You can create a new contact (ie. user or lead). * * @param {Intercom.CreateContactRequestTwo} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -1124,40 +926,40 @@ export class Contacts { */ public createContact( request?: Intercom.CreateContactRequestTwo, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createContact(request, requestOptions)); } private async __createContact( request?: Intercom.CreateContactRequestTwo, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "contacts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -1182,28 +984,14 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts"); } /** * You can fetch the details of a single contact by external ID. Note that this endpoint only supports users and not leads. * * @param {Intercom.unstable.ShowContactByExternalIdRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -1214,40 +1002,38 @@ export class Contacts { */ public showContactByExternalId( request: Intercom.unstable.ShowContactByExternalIdRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__showContactByExternalId(request, requestOptions)); } private async __showContactByExternalId( request: Intercom.unstable.ShowContactByExternalIdRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { external_id: externalId } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/find_by_external_id/${encodeURIComponent(externalId)}`, + `contacts/find_by_external_id/${core.url.encodePathParam(externalId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -1272,30 +1058,19 @@ export class Contacts { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /contacts/find_by_external_id/{external_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/contacts/find_by_external_id/{external_id}", + ); } /** * You can archive a single contact. * * @param {Intercom.unstable.ArchiveContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.contacts.archiveContact({ @@ -1304,40 +1079,38 @@ export class Contacts { */ public archiveContact( request: Intercom.unstable.ArchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__archiveContact(request, requestOptions)); } private async __archiveContact( request: Intercom.unstable.ArchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/archive`, + `contacts/${core.url.encodePathParam(id)}/archive`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactArchived, rawResponse: _response.rawResponse }; @@ -1351,28 +1124,14 @@ export class Contacts { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/{id}/archive."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{id}/archive"); } /** * You can unarchive a single contact. * * @param {Intercom.unstable.UnarchiveContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.contacts.unarchiveContact({ @@ -1381,40 +1140,38 @@ export class Contacts { */ public unarchiveContact( request: Intercom.unstable.UnarchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__unarchiveContact(request, requestOptions)); } private async __unarchiveContact( request: Intercom.unstable.UnarchiveContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/unarchive`, + `contacts/${core.url.encodePathParam(id)}/unarchive`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactUnarchived, rawResponse: _response.rawResponse }; @@ -1428,28 +1185,14 @@ export class Contacts { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/{id}/unarchive."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{id}/unarchive"); } /** * Block a single contact.
**Note:** conversations of the contact will also be archived during the process.
More details in [FAQ How do I block Inbox spam?](https://www.intercom.com/help/en/articles/8838656-inbox-faqs) * * @param {Intercom.unstable.BlockContactRequest} request - * @param {Contacts.RequestOptions} requestOptions - Request-specific configuration. + * @param {ContactsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.contacts.blockContact({ @@ -1458,40 +1201,38 @@ export class Contacts { */ public blockContact( request: Intercom.unstable.BlockContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__blockContact(request, requestOptions)); } private async __blockContact( request: Intercom.unstable.BlockContactRequest, - requestOptions?: Contacts.RequestOptions, + requestOptions?: ContactsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/block`, + `contacts/${core.url.encodePathParam(id)}/block`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ContactBlocked, rawResponse: _response.rawResponse }; @@ -1505,32 +1246,6 @@ export class Contacts { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/{id}/block."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{id}/block"); } } diff --git a/src/api/resources/unstable/resources/contacts/client/index.ts b/src/api/resources/unstable/resources/contacts/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/contacts/client/index.ts +++ b/src/api/resources/unstable/resources/contacts/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ArchiveContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ArchiveContactRequest.ts index f44c40c3..15dad8b9 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ArchiveContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ArchiveContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ArchiveContactRequest { - /** - * id - */ + /** id */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/BlockContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/BlockContactRequest.ts index 497e928a..75e78626 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/BlockContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/BlockContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface BlockContactRequest { - /** - * id - */ + /** id */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/DeleteContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/DeleteContactRequest.ts index e70f0504..55b557be 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/DeleteContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/DeleteContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteContactRequest { - /** - * id - */ + /** id */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ListCompaniesForAContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ListCompaniesForAContactRequest.ts index af4ebe19..1e96546f 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ListCompaniesForAContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ListCompaniesForAContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListCompaniesForAContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ListSegmentsForAContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ListSegmentsForAContactRequest.ts index 22e71773..2d363b13 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ListSegmentsForAContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ListSegmentsForAContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListSegmentsForAContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ListSubscriptionsForAContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ListSubscriptionsForAContactRequest.ts index 3e48e0c9..6413b23e 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ListSubscriptionsForAContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ListSubscriptionsForAContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListSubscriptionsForAContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ListTagsForAContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ListTagsForAContactRequest.ts index f91dffdc..719e4d06 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ListTagsForAContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ListTagsForAContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListTagsForAContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/MergeContactsRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/MergeContactsRequest.ts index a9009e6a..520d7f83 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/MergeContactsRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/MergeContactsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts index af3dff76..d6f2b0d8 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ShowContactByExternalIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ShowContactByExternalIdRequest { - /** - * The external ID of the user that you want to retrieve - */ + /** The external ID of the user that you want to retrieve */ external_id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/ShowContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/ShowContactRequest.ts index 6abbc7ab..170a185f 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/ShowContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/ShowContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ShowContactRequest { - /** - * id - */ + /** id */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/UnarchiveContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/UnarchiveContactRequest.ts index e6a5af5e..28b61c31 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/UnarchiveContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/UnarchiveContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface UnarchiveContactRequest { - /** - * id - */ + /** id */ id: string; } diff --git a/src/api/resources/unstable/resources/contacts/client/requests/UpdateContactRequest.ts b/src/api/resources/unstable/resources/contacts/client/requests/UpdateContactRequest.ts index b130cd58..e33aba66 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/UpdateContactRequest.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/UpdateContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -21,9 +19,7 @@ * } */ export interface UpdateContactRequest { - /** - * id - */ + /** id */ id: string; /** The role of the contact. */ role?: string; diff --git a/src/api/resources/unstable/resources/contacts/client/requests/index.ts b/src/api/resources/unstable/resources/contacts/client/requests/index.ts index 2c00f2f2..faea767c 100644 --- a/src/api/resources/unstable/resources/contacts/client/requests/index.ts +++ b/src/api/resources/unstable/resources/contacts/client/requests/index.ts @@ -1,12 +1,12 @@ -export { type ListCompaniesForAContactRequest } from "./ListCompaniesForAContactRequest"; -export { type ListSegmentsForAContactRequest } from "./ListSegmentsForAContactRequest"; -export { type ListSubscriptionsForAContactRequest } from "./ListSubscriptionsForAContactRequest"; -export { type ListTagsForAContactRequest } from "./ListTagsForAContactRequest"; -export { type ShowContactRequest } from "./ShowContactRequest"; -export { type UpdateContactRequest } from "./UpdateContactRequest"; -export { type DeleteContactRequest } from "./DeleteContactRequest"; -export { type MergeContactsRequest } from "./MergeContactsRequest"; -export { type ShowContactByExternalIdRequest } from "./ShowContactByExternalIdRequest"; -export { type ArchiveContactRequest } from "./ArchiveContactRequest"; -export { type UnarchiveContactRequest } from "./UnarchiveContactRequest"; -export { type BlockContactRequest } from "./BlockContactRequest"; +export type { ArchiveContactRequest } from "./ArchiveContactRequest.js"; +export type { BlockContactRequest } from "./BlockContactRequest.js"; +export type { DeleteContactRequest } from "./DeleteContactRequest.js"; +export type { ListCompaniesForAContactRequest } from "./ListCompaniesForAContactRequest.js"; +export type { ListSegmentsForAContactRequest } from "./ListSegmentsForAContactRequest.js"; +export type { ListSubscriptionsForAContactRequest } from "./ListSubscriptionsForAContactRequest.js"; +export type { ListTagsForAContactRequest } from "./ListTagsForAContactRequest.js"; +export type { MergeContactsRequest } from "./MergeContactsRequest.js"; +export type { ShowContactByExternalIdRequest } from "./ShowContactByExternalIdRequest.js"; +export type { ShowContactRequest } from "./ShowContactRequest.js"; +export type { UnarchiveContactRequest } from "./UnarchiveContactRequest.js"; +export type { UpdateContactRequest } from "./UpdateContactRequest.js"; diff --git a/src/api/resources/unstable/resources/contacts/index.ts b/src/api/resources/unstable/resources/contacts/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/contacts/index.ts +++ b/src/api/resources/unstable/resources/contacts/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/contacts/types/Contact.ts b/src/api/resources/unstable/resources/contacts/types/Contact.ts index 156e327d..0cf076af 100644 --- a/src/api/resources/unstable/resources/contacts/types/Contact.ts +++ b/src/api/resources/unstable/resources/contacts/types/Contact.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Contacts represent your leads and users in Intercom. diff --git a/src/api/resources/unstable/resources/contacts/types/CreateContactResponse.ts b/src/api/resources/unstable/resources/contacts/types/CreateContactResponse.ts index 1455fa8f..e7bb8739 100644 --- a/src/api/resources/unstable/resources/contacts/types/CreateContactResponse.ts +++ b/src/api/resources/unstable/resources/contacts/types/CreateContactResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export interface CreateContactResponse extends Intercom.unstable.Contact { /** If the user has enabled push messaging. */ diff --git a/src/api/resources/unstable/resources/contacts/types/MergeContactResponse.ts b/src/api/resources/unstable/resources/contacts/types/MergeContactResponse.ts index b67e7baa..6a253944 100644 --- a/src/api/resources/unstable/resources/contacts/types/MergeContactResponse.ts +++ b/src/api/resources/unstable/resources/contacts/types/MergeContactResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export interface MergeContactResponse extends Intercom.unstable.Contact { /** If the user has enabled push messaging. */ diff --git a/src/api/resources/unstable/resources/contacts/types/ShowContactByExternalIdResponse.ts b/src/api/resources/unstable/resources/contacts/types/ShowContactByExternalIdResponse.ts index d11d1d83..2e8b3f12 100644 --- a/src/api/resources/unstable/resources/contacts/types/ShowContactByExternalIdResponse.ts +++ b/src/api/resources/unstable/resources/contacts/types/ShowContactByExternalIdResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export interface ShowContactByExternalIdResponse extends Intercom.unstable.Contact { /** If the user has enabled push messaging. */ diff --git a/src/api/resources/unstable/resources/contacts/types/ShowContactResponse.ts b/src/api/resources/unstable/resources/contacts/types/ShowContactResponse.ts index 58bc07cc..e8ffabcc 100644 --- a/src/api/resources/unstable/resources/contacts/types/ShowContactResponse.ts +++ b/src/api/resources/unstable/resources/contacts/types/ShowContactResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export interface ShowContactResponse extends Intercom.unstable.Contact { /** If the user has enabled push messaging. */ diff --git a/src/api/resources/unstable/resources/contacts/types/UpdateContactResponse.ts b/src/api/resources/unstable/resources/contacts/types/UpdateContactResponse.ts index 8919485b..c67687b2 100644 --- a/src/api/resources/unstable/resources/contacts/types/UpdateContactResponse.ts +++ b/src/api/resources/unstable/resources/contacts/types/UpdateContactResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export interface UpdateContactResponse extends Intercom.unstable.Contact { /** If the user has enabled push messaging. */ diff --git a/src/api/resources/unstable/resources/contacts/types/index.ts b/src/api/resources/unstable/resources/contacts/types/index.ts index 12ec2438..bf8c1f71 100644 --- a/src/api/resources/unstable/resources/contacts/types/index.ts +++ b/src/api/resources/unstable/resources/contacts/types/index.ts @@ -1,6 +1,6 @@ -export * from "./ShowContactResponse"; -export * from "./UpdateContactResponse"; -export * from "./MergeContactResponse"; -export * from "./CreateContactResponse"; -export * from "./ShowContactByExternalIdResponse"; -export * from "./Contact"; +export * from "./Contact.js"; +export * from "./CreateContactResponse.js"; +export * from "./MergeContactResponse.js"; +export * from "./ShowContactByExternalIdResponse.js"; +export * from "./ShowContactResponse.js"; +export * from "./UpdateContactResponse.js"; diff --git a/src/api/resources/unstable/resources/conversations/client/Client.ts b/src/api/resources/unstable/resources/conversations/client/Client.ts index 87442ffe..70ca206d 100644 --- a/src/api/resources/unstable/resources/conversations/client/Client.ts +++ b/src/api/resources/unstable/resources/conversations/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Conversations { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ConversationsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Conversations */ -export class Conversations { - constructor(protected readonly _options: Conversations.Options = {}) {} +export class ConversationsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ConversationsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all conversations. @@ -85,60 +35,60 @@ export class Conversations { * {% /admonition %} * * @param {Intercom.unstable.ListConversationsRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} * * @example - * await client.unstable.conversations.listConversations() + * await client.unstable.conversations.listConversations({ + * per_page: 1, + * starting_after: "starting_after" + * }) */ public listConversations( request: Intercom.unstable.ListConversationsRequest = {}, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listConversations(request, requestOptions)); } private async __listConversations( request: Intercom.unstable.ListConversationsRequest = {}, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { per_page: perPage, starting_after: startingAfter } = request; const _queryParams: Record = {}; if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (startingAfter != null) { - _queryParams["starting_after"] = startingAfter; + _queryParams.starting_after = startingAfter; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ConversationList, rawResponse: _response.rawResponse }; @@ -165,21 +115,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /conversations."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/conversations"); } /** @@ -193,8 +129,9 @@ export class Conversations { * * This will return the Message model that has been created. * + * * @param {Intercom.unstable.CreateConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -220,40 +157,40 @@ export class Conversations { */ public createConversation( request: Intercom.unstable.CreateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createConversation(request, requestOptions)); } private async __createConversation( request: Intercom.unstable.CreateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Message, rawResponse: _response.rawResponse }; @@ -282,21 +219,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations"); } /** @@ -312,7 +235,7 @@ export class Conversations { * For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a [paid feature](https://www.intercom.com/help/en/articles/8205718-fin-resolutions#h_97f8c2e671). * * @param {Intercom.unstable.RetrieveConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -321,51 +244,53 @@ export class Conversations { * @example * await client.unstable.conversations.retrieveConversation({ * id: 1, - * display_as: "plaintext" + * display_as: "plaintext", + * include_translations: true * }) */ public retrieveConversation( request: Intercom.unstable.RetrieveConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveConversation(request, requestOptions)); } private async __retrieveConversation( request: Intercom.unstable.RetrieveConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { - const { id, display_as: displayAs } = request; + const { id, display_as: displayAs, include_translations: includeTranslations } = request; const _queryParams: Record = {}; if (displayAs != null) { - _queryParams["display_as"] = displayAs; + _queryParams.display_as = displayAs; + } + + if (includeTranslations != null) { + _queryParams.include_translations = includeTranslations.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}`, + `conversations/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -394,21 +319,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /conversations/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/conversations/{id}"); } /** @@ -425,8 +336,9 @@ export class Conversations { * See _`update a conversation with an association to a custom object instance`_ in the request/response examples to see the custom object association format. * {% /admonition %} * + * * @param {Intercom.unstable.UpdateConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -455,47 +367,46 @@ export class Conversations { */ public updateConversation( request: Intercom.unstable.UpdateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateConversation(request, requestOptions)); } private async __updateConversation( request: Intercom.unstable.UpdateConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id, display_as: displayAs, ..._body } = request; const _queryParams: Record = {}; if (displayAs != null) { - _queryParams["display_as"] = displayAs; + _queryParams.display_as = displayAs; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}`, + `conversations/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", - queryParameters: _queryParams, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -524,28 +435,14 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /conversations/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/conversations/{id}"); } /** * You can delete a single conversation. * * @param {Intercom.unstable.DeleteConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -557,40 +454,38 @@ export class Conversations { */ public deleteConversation( request: Intercom.unstable.DeleteConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteConversation(request, requestOptions)); } private async __deleteConversation( request: Intercom.unstable.DeleteConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}`, + `conversations/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -620,21 +515,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /conversations/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/conversations/{id}"); } /** @@ -739,7 +620,7 @@ export class Conversations { * | $ | String | Ends With | * * @param {Intercom.unstable.SearchRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.conversations.searchConversations({ @@ -758,40 +639,40 @@ export class Conversations { */ public searchConversations( request: Intercom.unstable.SearchRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__searchConversations(request, requestOptions)); } private async __searchConversations( request: Intercom.unstable.SearchRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.ConversationList, rawResponse: _response.rawResponse }; @@ -805,28 +686,14 @@ export class Conversations { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/search"); } /** * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. * * @param {Intercom.unstable.ReplyConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -899,41 +766,41 @@ export class Conversations { */ public replyConversation( request: Intercom.unstable.ReplyConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__replyConversation(request, requestOptions)); } private async __replyConversation( request: Intercom.unstable.ReplyConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}/reply`, + `conversations/${core.url.encodePathParam(id)}/reply`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -962,21 +829,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations/{id}/reply."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/{id}/reply"); } /** @@ -987,7 +840,7 @@ export class Conversations { * - Assign a conversation to an admin and/or team. * * @param {Intercom.unstable.ManageConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -1035,41 +888,41 @@ export class Conversations { */ public manageConversation( request: Intercom.unstable.ManageConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__manageConversation(request, requestOptions)); } private async __manageConversation( request: Intercom.unstable.ManageConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}/parts`, + `conversations/${core.url.encodePathParam(id)}/parts`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -1098,21 +951,7 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations/{id}/parts."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/{id}/parts"); } /** @@ -1122,8 +961,9 @@ export class Conversations { * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. * {% /admonition %} * + * * @param {Intercom.unstable.AttachContactToConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -1149,41 +989,41 @@ export class Conversations { */ public attachContactToConversation( request: Intercom.unstable.AttachContactToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachContactToConversation(request, requestOptions)); } private async __attachContactToConversation( request: Intercom.unstable.AttachContactToConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}/customers`, + `conversations/${core.url.encodePathParam(id)}/customers`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -1212,23 +1052,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{id}/customers.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{id}/customers", + ); } /** @@ -1238,8 +1067,9 @@ export class Conversations { * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with `role` set to `lead`. * {% /admonition %} * + * * @param {Intercom.unstable.DetachContactFromConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.ForbiddenError} @@ -1255,41 +1085,41 @@ export class Conversations { */ public detachContactFromConversation( request: Intercom.unstable.DetachContactFromConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachContactFromConversation(request, requestOptions)); } private async __detachContactFromConversation( request: Intercom.unstable.DetachContactFromConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/customers/${encodeURIComponent(contactId)}`, + `conversations/${core.url.encodePathParam(conversationId)}/customers/${core.url.encodePathParam(contactId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -1323,23 +1153,12 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /conversations/{conversation_id}/customers/{contact_id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/conversations/{conversation_id}/customers/{contact_id}", + ); } /** @@ -1349,8 +1168,9 @@ export class Conversations { * If you are redacting a conversation part, it must have a `body`. If you are redacting a source message, it must have been created by a contact. We will return a `conversation_part_not_redactable` error if these criteria are not met. * {% /admonition %} * + * * @param {Intercom.unstable.RedactConversationRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -1371,40 +1191,40 @@ export class Conversations { */ public redactConversation( request: Intercom.unstable.RedactConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__redactConversation(request, requestOptions)); } private async __redactConversation( request: Intercom.unstable.RedactConversationRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "conversations/redact", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Conversation, rawResponse: _response.rawResponse }; @@ -1428,28 +1248,14 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /conversations/redact."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/redact"); } /** * You can convert a conversation to a ticket. * * @param {Intercom.unstable.ConvertConversationToTicketRequest} request - * @param {Conversations.RequestOptions} requestOptions - Request-specific configuration. + * @param {ConversationsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @@ -1467,41 +1273,41 @@ export class Conversations { */ public convertConversationToTicket( request: Intercom.unstable.ConvertConversationToTicketRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__convertConversationToTicket(request, requestOptions)); } private async __convertConversationToTicket( request: Intercom.unstable.ConvertConversationToTicketRequest, - requestOptions?: Conversations.RequestOptions, + requestOptions?: ConversationsClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(id)}/convert`, + `conversations/${core.url.encodePathParam(id)}/convert`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Ticket | undefined, rawResponse: _response.rawResponse }; @@ -1520,34 +1326,6 @@ export class Conversations { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{id}/convert.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/conversations/{id}/convert"); } } diff --git a/src/api/resources/unstable/resources/conversations/client/index.ts b/src/api/resources/unstable/resources/conversations/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/conversations/client/index.ts +++ b/src/api/resources/unstable/resources/conversations/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/conversations/client/requests/AttachContactToConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/AttachContactToConversationRequest.ts index d887df62..e7d06d91 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/AttachContactToConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/AttachContactToConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -24,9 +22,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface AttachContactToConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ id: string; /** The `id` of the admin who is adding the new participant. */ admin_id?: string; diff --git a/src/api/resources/unstable/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts index 2e317651..5985d835 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/ConvertConversationToTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -18,9 +16,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface ConvertConversationToTicketRequest { - /** - * The id of the conversation to target - */ + /** The id of the conversation to target */ id: number; /** The ID of the type of ticket you want to convert the conversation to */ ticket_type_id: string; diff --git a/src/api/resources/unstable/resources/conversations/client/requests/CreateConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/CreateConversationRequest.ts index 93ec0636..0f8bcd9a 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/CreateConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/CreateConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -38,14 +36,12 @@ export namespace CreateConversationRequest { } export namespace From { - /** - * The role associated to the contact - user or lead. - */ - export type Type = "lead" | "user" | "contact"; + /** The role associated to the contact - user or lead. */ export const Type = { Lead: "lead", User: "user", Contact: "contact", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/DeleteConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/DeleteConversationRequest.ts index 9ef40c85..1a07b952 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/DeleteConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/DeleteConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteConversationRequest { - /** - * id - */ + /** id */ id: number; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/DetachContactFromConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/DetachContactFromConversationRequest.ts index e245b23d..415bfae9 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/DetachContactFromConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/DetachContactFromConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -32,13 +30,9 @@ * } */ export interface DetachContactFromConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ conversation_id: string; - /** - * The identifier for the contact as given by Intercom. - */ + /** The identifier for the contact as given by Intercom. */ contact_id: string; /** The `id` of the admin who is performing the action. */ admin_id: string; diff --git a/src/api/resources/unstable/resources/conversations/client/requests/ListConversationsRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/ListConversationsRequest.ts index f3c7f741..4908f563 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/ListConversationsRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/ListConversationsRequest.ts @@ -1,18 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * per_page: 1, + * starting_after: "starting_after" + * } */ export interface ListConversationsRequest { - /** - * How many results per page - */ + /** How many results per page */ per_page?: number; - /** - * String used to get the next page of conversations. - */ + /** String used to get the next page of conversations. */ starting_after?: string; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/ManageConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/ManageConversationRequest.ts index 59c70d65..54ff3cf5 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/ManageConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/ManageConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -56,9 +54,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface ManageConversationRequest { - /** - * The identifier for the conversation as given by Intercom. - */ + /** The identifier for the conversation as given by Intercom. */ id: string; body: Intercom.unstable.ManageConversationRequestBody; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/ReplyConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/ReplyConversationRequest.ts index fb35a919..3653ec6d 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/ReplyConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/ReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -71,9 +69,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface ReplyConversationRequest { - /** - * The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation - */ + /** The Intercom provisioned identifier for the conversation or the string "last" to reply to the last part of the conversation */ id: string; body: Intercom.unstable.ReplyConversationRequestBody; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/RetrieveConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/RetrieveConversationRequest.ts index 8849068d..1d207c59 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/RetrieveConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/RetrieveConversationRequest.ts @@ -1,21 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * id: 1, - * display_as: "plaintext" + * display_as: "plaintext", + * include_translations: true * } */ export interface RetrieveConversationRequest { - /** - * The id of the conversation to target - */ + /** The id of the conversation to target */ id: number; - /** - * Set to plaintext to retrieve conversation messages in plain text. - */ + /** Set to plaintext to retrieve conversation messages in plain text. This affects both the body and subject fields. */ display_as?: string; + /** If set to true, conversation parts will be translated to the detected language of the conversation. */ + include_translations?: boolean; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/UpdateConversationRequest.ts b/src/api/resources/unstable/resources/conversations/client/requests/UpdateConversationRequest.ts index 76276853..9e2a3dea 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/UpdateConversationRequest.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/UpdateConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -39,17 +37,15 @@ import * as Intercom from "../../../../../../index"; * } */ export interface UpdateConversationRequest { - /** - * The id of the conversation to target - */ + /** The id of the conversation to target */ id: number; - /** - * Set to plaintext to retrieve conversation messages in plain text. - */ + /** Set to plaintext to retrieve conversation messages in plain text. This affects both the body and subject fields. */ display_as?: string; /** Mark a conversation as read within Intercom. */ read?: boolean; /** The title given to the conversation */ title?: string; custom_attributes?: Intercom.unstable.CustomAttributes; + /** The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. Set to nil to remove company. */ + company_id?: string; } diff --git a/src/api/resources/unstable/resources/conversations/client/requests/index.ts b/src/api/resources/unstable/resources/conversations/client/requests/index.ts index b297425a..0d6b5317 100644 --- a/src/api/resources/unstable/resources/conversations/client/requests/index.ts +++ b/src/api/resources/unstable/resources/conversations/client/requests/index.ts @@ -1,10 +1,10 @@ -export { type ListConversationsRequest } from "./ListConversationsRequest"; -export { type CreateConversationRequest } from "./CreateConversationRequest"; -export { type RetrieveConversationRequest } from "./RetrieveConversationRequest"; -export { type UpdateConversationRequest } from "./UpdateConversationRequest"; -export { type DeleteConversationRequest } from "./DeleteConversationRequest"; -export { type ReplyConversationRequest } from "./ReplyConversationRequest"; -export { type ManageConversationRequest } from "./ManageConversationRequest"; -export { type AttachContactToConversationRequest } from "./AttachContactToConversationRequest"; -export { type DetachContactFromConversationRequest } from "./DetachContactFromConversationRequest"; -export { type ConvertConversationToTicketRequest } from "./ConvertConversationToTicketRequest"; +export type { AttachContactToConversationRequest } from "./AttachContactToConversationRequest.js"; +export type { ConvertConversationToTicketRequest } from "./ConvertConversationToTicketRequest.js"; +export type { CreateConversationRequest } from "./CreateConversationRequest.js"; +export type { DeleteConversationRequest } from "./DeleteConversationRequest.js"; +export type { DetachContactFromConversationRequest } from "./DetachContactFromConversationRequest.js"; +export type { ListConversationsRequest } from "./ListConversationsRequest.js"; +export type { ManageConversationRequest } from "./ManageConversationRequest.js"; +export type { ReplyConversationRequest } from "./ReplyConversationRequest.js"; +export type { RetrieveConversationRequest } from "./RetrieveConversationRequest.js"; +export type { UpdateConversationRequest } from "./UpdateConversationRequest.js"; diff --git a/src/api/resources/unstable/resources/conversations/index.ts b/src/api/resources/unstable/resources/conversations/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/conversations/index.ts +++ b/src/api/resources/unstable/resources/conversations/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/conversations/types/Conversation.ts b/src/api/resources/unstable/resources/conversations/types/Conversation.ts index 2531c62d..8a79bcda 100644 --- a/src/api/resources/unstable/resources/conversations/types/Conversation.ts +++ b/src/api/resources/unstable/resources/conversations/types/Conversation.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Conversations are how you can communicate with users in Intercom. They are created when a contact replies to an outbound message, or when one admin directly sends a message to a single contact. @@ -34,6 +32,8 @@ export interface Conversation { admin_assignee_id?: number; /** The id of the team assigned to the conversation. If it's not assigned to a team it will return null. */ team_assignee_id?: string; + /** The ID of the company that the conversation is associated with. The unique identifier for the company which is given by Intercom. */ + company_id?: string; tags?: Intercom.unstable.Tags; conversation_rating?: Intercom.unstable.ConversationRating; source?: Intercom.unstable.ConversationSource; @@ -51,21 +51,17 @@ export interface Conversation { } export namespace Conversation { - /** - * Can be set to "open", "closed" or "snoozed". - */ - export type State = "open" | "closed" | "snoozed"; + /** Can be set to "open", "closed" or "snoozed". */ export const State = { Open: "open", Closed: "closed", Snoozed: "snoozed", } as const; - /** - * If marked as priority, it will return priority or else not_priority. - */ - export type Priority = "priority" | "not_priority"; + export type State = (typeof State)[keyof typeof State]; + /** If marked as priority, it will return priority or else not_priority. */ export const Priority = { Priority: "priority", NotPriority: "not_priority", } as const; + export type Priority = (typeof Priority)[keyof typeof Priority]; } diff --git a/src/api/resources/unstable/resources/conversations/types/ManageConversationRequestBody.ts b/src/api/resources/unstable/resources/conversations/types/ManageConversationRequestBody.ts index cceeedbb..ec011db3 100644 --- a/src/api/resources/unstable/resources/conversations/types/ManageConversationRequestBody.ts +++ b/src/api/resources/unstable/resources/conversations/types/ManageConversationRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export type ManageConversationRequestBody = | Intercom.unstable.ManageConversationRequestBody.Close diff --git a/src/api/resources/unstable/resources/conversations/types/index.ts b/src/api/resources/unstable/resources/conversations/types/index.ts index b2325882..7f9a27b5 100644 --- a/src/api/resources/unstable/resources/conversations/types/index.ts +++ b/src/api/resources/unstable/resources/conversations/types/index.ts @@ -1,2 +1,2 @@ -export * from "./ManageConversationRequestBody"; -export * from "./Conversation"; +export * from "./Conversation.js"; +export * from "./ManageConversationRequestBody.js"; diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/Client.ts b/src/api/resources/unstable/resources/customChannelEvents/client/Client.ts index fab44a35..fdb99c2e 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/Client.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/Client.ts @@ -1,83 +1,33 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace CustomChannelEvents { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace CustomChannelEventsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class CustomChannelEvents { - constructor(protected readonly _options: CustomChannelEvents.Options = {}) {} +export class CustomChannelEventsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CustomChannelEventsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * Notifies Intercom that a new conversation was created in your custom channel/platform. This triggers conversation creation and workflow automations within Intercom for your custom channel integration. - * > **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. * * @param {Intercom.unstable.CustomChannelBaseEvent} request - * @param {CustomChannelEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -98,40 +48,40 @@ export class CustomChannelEvents { */ public notifyNewConversation( request: Intercom.unstable.CustomChannelBaseEvent, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__notifyNewConversation(request, requestOptions)); } private async __notifyNewConversation( request: Intercom.unstable.CustomChannelBaseEvent, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "custom_channel_events/notify_new_conversation", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -165,31 +115,20 @@ export class CustomChannelEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /custom_channel_events/notify_new_conversation.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_new_conversation", + ); } /** * Notifies Intercom that a new message was sent in a conversation on your custom channel/platform. This allows Intercom to process the message and trigger any relevant workflow automations. - * > **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. * * @param {Intercom.unstable.NotifyNewMessageRequest} request - * @param {CustomChannelEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -211,40 +150,40 @@ export class CustomChannelEvents { */ public notifyNewMessage( request: Intercom.unstable.NotifyNewMessageRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__notifyNewMessage(request, requestOptions)); } private async __notifyNewMessage( request: Intercom.unstable.NotifyNewMessageRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "custom_channel_events/notify_new_message", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -278,31 +217,20 @@ export class CustomChannelEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /custom_channel_events/notify_new_message.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_new_message", + ); } /** * Notifies Intercom that a user selected a quick reply option in your custom channel/platform. This allows Intercom to process the response and trigger any relevant workflow automations. - * > **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. * * @param {Intercom.unstable.NotifyQuickReplySelectedRequest} request - * @param {CustomChannelEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -324,40 +252,40 @@ export class CustomChannelEvents { */ public notifyQuickReplySelected( request: Intercom.unstable.NotifyQuickReplySelectedRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__notifyQuickReplySelected(request, requestOptions)); } private async __notifyQuickReplySelected( request: Intercom.unstable.NotifyQuickReplySelectedRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "custom_channel_events/notify_quick_reply_selected", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -391,31 +319,20 @@ export class CustomChannelEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /custom_channel_events/notify_quick_reply_selected.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_quick_reply_selected", + ); } /** * Notifies Intercom that a user provided a response to an attribute collector in your custom channel/platform. This allows Intercom to process the attribute and trigger any relevant workflow automations. - * > **Note:** This endpoint is restricted to customers with access to the closed beta for "Fin over API". + * > **Note:** This endpoint is currently under managed availability. Please reach out to your accounts team to discuss access and tailored, hands-on support. * * @param {Intercom.unstable.NotifyAttributeCollectedRequest} request - * @param {CustomChannelEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomChannelEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -440,40 +357,40 @@ export class CustomChannelEvents { */ public notifyAttributeCollected( request: Intercom.unstable.NotifyAttributeCollectedRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__notifyAttributeCollected(request, requestOptions)); } private async __notifyAttributeCollected( request: Intercom.unstable.NotifyAttributeCollectedRequest, - requestOptions?: CustomChannelEvents.RequestOptions, + requestOptions?: CustomChannelEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "custom_channel_events/notify_attribute_collected", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -507,34 +424,11 @@ export class CustomChannelEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /custom_channel_events/notify_attribute_collected.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_channel_events/notify_attribute_collected", + ); } } diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/index.ts b/src/api/resources/unstable/resources/customChannelEvents/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/index.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts index f3a2660d..f0ad7f82 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyAttributeCollectedRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts index 1ed15c6e..8a4f252a 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyNewMessageRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts index 499b11d6..049df316 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/requests/NotifyQuickReplySelectedRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/customChannelEvents/client/requests/index.ts b/src/api/resources/unstable/resources/customChannelEvents/client/requests/index.ts index 007800f3..702922d9 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/client/requests/index.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/client/requests/index.ts @@ -1,3 +1,3 @@ -export { type NotifyNewMessageRequest } from "./NotifyNewMessageRequest"; -export { type NotifyQuickReplySelectedRequest } from "./NotifyQuickReplySelectedRequest"; -export { type NotifyAttributeCollectedRequest } from "./NotifyAttributeCollectedRequest"; +export type { NotifyAttributeCollectedRequest } from "./NotifyAttributeCollectedRequest.js"; +export type { NotifyNewMessageRequest } from "./NotifyNewMessageRequest.js"; +export type { NotifyQuickReplySelectedRequest } from "./NotifyQuickReplySelectedRequest.js"; diff --git a/src/api/resources/unstable/resources/customChannelEvents/index.ts b/src/api/resources/unstable/resources/customChannelEvents/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/customChannelEvents/index.ts +++ b/src/api/resources/unstable/resources/customChannelEvents/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/Client.ts b/src/api/resources/unstable/resources/customObjectInstances/client/Client.ts index 8d8d1ca5..a8ff8f05 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/Client.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/Client.ts @@ -1,72 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace CustomObjectInstances { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace CustomObjectInstancesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** @@ -75,14 +21,18 @@ export declare namespace CustomObjectInstances { * From now on, to access this endpoint, you need additional permissions. Please head over to the [Developer Hub](https://app.intercom.com/a/apps/_/developer-hub) app package authentication settings to configure the required permissions. * {% /admonition %} */ -export class CustomObjectInstances { - constructor(protected readonly _options: CustomObjectInstances.Options = {}) {} +export class CustomObjectInstancesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: CustomObjectInstancesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * Fetch a Custom Object Instance by external_id. * * @param {Intercom.unstable.GetCustomObjectInstancesByExternalIdRequest} request - * @param {CustomObjectInstances.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -95,7 +45,7 @@ export class CustomObjectInstances { */ public getCustomObjectInstancesByExternalId( request: Intercom.unstable.GetCustomObjectInstancesByExternalIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise( this.__getCustomObjectInstancesByExternalId(request, requestOptions), @@ -104,36 +54,33 @@ export class CustomObjectInstances { private async __getCustomObjectInstancesByExternalId( request: Intercom.unstable.GetCustomObjectInstancesByExternalIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): Promise> { const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request; const _queryParams: Record = {}; - _queryParams["external_id"] = externalId; + _queryParams.external_id = externalId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `custom_object_instances/${encodeURIComponent(customObjectTypeIdentifier)}`, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -160,30 +107,19 @@ export class CustomObjectInstances { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /custom_object_instances/{custom_object_type_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/custom_object_instances/{custom_object_type_identifier}", + ); } /** * Create or update a custom object instance * * @param {Intercom.unstable.CreateOrUpdateCustomObjectInstanceRequest} request - * @param {CustomObjectInstances.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -202,41 +138,41 @@ export class CustomObjectInstances { */ public createCustomObjectInstances( request: Intercom.unstable.CreateOrUpdateCustomObjectInstanceRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createCustomObjectInstances(request, requestOptions)); } private async __createCustomObjectInstances( request: Intercom.unstable.CreateOrUpdateCustomObjectInstanceRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): Promise> { const { custom_object_type_identifier: customObjectTypeIdentifier, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `custom_object_instances/${encodeURIComponent(customObjectTypeIdentifier)}`, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -263,30 +199,19 @@ export class CustomObjectInstances { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /custom_object_instances/{custom_object_type_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/custom_object_instances/{custom_object_type_identifier}", + ); } /** * Delete a single Custom Object instance by external_id. * * @param {Intercom.unstable.DeleteCustomObjectInstancesByIdRequest} request - * @param {CustomObjectInstances.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -299,43 +224,40 @@ export class CustomObjectInstances { */ public deleteCustomObjectInstancesById( request: Intercom.unstable.DeleteCustomObjectInstancesByIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteCustomObjectInstancesById(request, requestOptions)); } private async __deleteCustomObjectInstancesById( request: Intercom.unstable.DeleteCustomObjectInstancesByIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): Promise> { const { custom_object_type_identifier: customObjectTypeIdentifier, external_id: externalId } = request; const _queryParams: Record = {}; - _queryParams["external_id"] = externalId; + _queryParams.external_id = externalId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `custom_object_instances/${encodeURIComponent(customObjectTypeIdentifier)}`, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -362,30 +284,19 @@ export class CustomObjectInstances { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /custom_object_instances/{custom_object_type_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/custom_object_instances/{custom_object_type_identifier}", + ); } /** * Fetch a Custom Object Instance by id. * * @param {Intercom.unstable.GetCustomObjectInstancesByIdRequest} request - * @param {CustomObjectInstances.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -398,40 +309,38 @@ export class CustomObjectInstances { */ public getCustomObjectInstancesById( request: Intercom.unstable.GetCustomObjectInstancesByIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getCustomObjectInstancesById(request, requestOptions)); } private async __getCustomObjectInstancesById( request: Intercom.unstable.GetCustomObjectInstancesByIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): Promise> { const { custom_object_type_identifier: customObjectTypeIdentifier, id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `custom_object_instances/${encodeURIComponent(customObjectTypeIdentifier)}/${encodeURIComponent(id)}`, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -458,30 +367,19 @@ export class CustomObjectInstances { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /custom_object_instances/{custom_object_type_identifier}/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/custom_object_instances/{custom_object_type_identifier}/{id}", + ); } /** * Delete a single Custom Object instance using the Intercom defined id. * * @param {Intercom.unstable.DeleteCustomObjectInstancesByExternalIdRequest} request - * @param {CustomObjectInstances.RequestOptions} requestOptions - Request-specific configuration. + * @param {CustomObjectInstancesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -494,7 +392,7 @@ export class CustomObjectInstances { */ public deleteCustomObjectInstancesByExternalId( request: Intercom.unstable.DeleteCustomObjectInstancesByExternalIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise( this.__deleteCustomObjectInstancesByExternalId(request, requestOptions), @@ -503,33 +401,31 @@ export class CustomObjectInstances { private async __deleteCustomObjectInstancesByExternalId( request: Intercom.unstable.DeleteCustomObjectInstancesByExternalIdRequest, - requestOptions?: CustomObjectInstances.RequestOptions, + requestOptions?: CustomObjectInstancesClient.RequestOptions, ): Promise> { const { custom_object_type_identifier: customObjectTypeIdentifier, id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `custom_object_instances/${encodeURIComponent(customObjectTypeIdentifier)}/${encodeURIComponent(id)}`, + `custom_object_instances/${core.url.encodePathParam(customObjectTypeIdentifier)}/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -556,34 +452,11 @@ export class CustomObjectInstances { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /custom_object_instances/{custom_object_type_identifier}/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/custom_object_instances/{custom_object_type_identifier}/{id}", + ); } } diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/index.ts b/src/api/resources/unstable/resources/customObjectInstances/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/index.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts index 6366c551..97fa7ad7 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/CreateOrUpdateCustomObjectInstanceRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -16,9 +14,7 @@ * } */ export interface CreateOrUpdateCustomObjectInstanceRequest { - /** - * The unique identifier of the custom object type that defines the structure of the custom object instance. - */ + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ custom_object_type_identifier: string; /** A unique identifier for the Custom Object instance in the external system it originated from. */ external_id?: string; diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts index 4674b582..4a66d40e 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByExternalIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DeleteCustomObjectInstancesByExternalIdRequest { - /** - * The unique identifier of the custom object type that defines the structure of the custom object instance. - */ + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ custom_object_type_identifier: string; - /** - * The Intercom defined id of the custom object instance - */ + /** The Intercom defined id of the custom object instance */ id: string; } diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts index b14cf673..d97bc1ce 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/DeleteCustomObjectInstancesByIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,9 +8,7 @@ * } */ export interface DeleteCustomObjectInstancesByIdRequest { - /** - * The unique identifier of the custom object type that defines the structure of the custom object instance. - */ + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ custom_object_type_identifier: string; external_id: string; } diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts index 5ca2f7d0..2d9d0fe3 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByExternalIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,9 +8,7 @@ * } */ export interface GetCustomObjectInstancesByExternalIdRequest { - /** - * The unique identifier of the custom object type that defines the structure of the custom object instance. - */ + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ custom_object_type_identifier: string; external_id: string; } diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts index 9350898c..69c8d4cf 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/GetCustomObjectInstancesByIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface GetCustomObjectInstancesByIdRequest { - /** - * The unique identifier of the custom object type that defines the structure of the custom object instance. - */ + /** The unique identifier of the custom object type that defines the structure of the custom object instance. */ custom_object_type_identifier: string; - /** - * The id or external_id of the custom object instance - */ + /** The id or external_id of the custom object instance */ id: string; } diff --git a/src/api/resources/unstable/resources/customObjectInstances/client/requests/index.ts b/src/api/resources/unstable/resources/customObjectInstances/client/requests/index.ts index 5382e3d2..07816781 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/client/requests/index.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/client/requests/index.ts @@ -1,5 +1,5 @@ -export { type GetCustomObjectInstancesByExternalIdRequest } from "./GetCustomObjectInstancesByExternalIdRequest"; -export { type CreateOrUpdateCustomObjectInstanceRequest } from "./CreateOrUpdateCustomObjectInstanceRequest"; -export { type DeleteCustomObjectInstancesByIdRequest } from "./DeleteCustomObjectInstancesByIdRequest"; -export { type GetCustomObjectInstancesByIdRequest } from "./GetCustomObjectInstancesByIdRequest"; -export { type DeleteCustomObjectInstancesByExternalIdRequest } from "./DeleteCustomObjectInstancesByExternalIdRequest"; +export type { CreateOrUpdateCustomObjectInstanceRequest } from "./CreateOrUpdateCustomObjectInstanceRequest.js"; +export type { DeleteCustomObjectInstancesByExternalIdRequest } from "./DeleteCustomObjectInstancesByExternalIdRequest.js"; +export type { DeleteCustomObjectInstancesByIdRequest } from "./DeleteCustomObjectInstancesByIdRequest.js"; +export type { GetCustomObjectInstancesByExternalIdRequest } from "./GetCustomObjectInstancesByExternalIdRequest.js"; +export type { GetCustomObjectInstancesByIdRequest } from "./GetCustomObjectInstancesByIdRequest.js"; diff --git a/src/api/resources/unstable/resources/customObjectInstances/index.ts b/src/api/resources/unstable/resources/customObjectInstances/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/index.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/customObjectInstances/types/CustomObjectInstance.ts b/src/api/resources/unstable/resources/customObjectInstances/types/CustomObjectInstance.ts index aab4a843..a4363acf 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/types/CustomObjectInstance.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/types/CustomObjectInstance.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A Custom Object Instance represents an instance of a custom object type. This allows you to create and set custom attributes to store data about your customers that is not already captured by Intercom. The parent object includes recommended default attributes and you can add your own custom attributes. diff --git a/src/api/resources/unstable/resources/customObjectInstances/types/index.ts b/src/api/resources/unstable/resources/customObjectInstances/types/index.ts index d5c782f8..861f9ce5 100644 --- a/src/api/resources/unstable/resources/customObjectInstances/types/index.ts +++ b/src/api/resources/unstable/resources/customObjectInstances/types/index.ts @@ -1 +1 @@ -export * from "./CustomObjectInstance"; +export * from "./CustomObjectInstance.js"; diff --git a/src/api/resources/unstable/resources/dataAttributes/client/Client.ts b/src/api/resources/unstable/resources/dataAttributes/client/Client.ts index 03670ff6..1778c2d1 100644 --- a/src/api/resources/unstable/resources/dataAttributes/client/Client.ts +++ b/src/api/resources/unstable/resources/dataAttributes/client/Client.ts @@ -1,137 +1,87 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace DataAttributes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace DataAttributesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Data Attributes */ -export class DataAttributes { - constructor(protected readonly _options: DataAttributes.Options = {}) {} +export class DataAttributesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: DataAttributesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. * * @param {Intercom.unstable.LisDataAttributesRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example - * await client.unstable.dataAttributes.lisDataAttributes() + * await client.unstable.dataAttributes.lisDataAttributes({ + * model: "contact", + * include_archived: true + * }) */ public lisDataAttributes( request: Intercom.unstable.LisDataAttributesRequest = {}, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__lisDataAttributes(request, requestOptions)); } private async __lisDataAttributes( request: Intercom.unstable.LisDataAttributesRequest = {}, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { const { model, include_archived: includeArchived } = request; const _queryParams: Record = {}; if (model != null) { - _queryParams["model"] = model; + _queryParams.model = model; } if (includeArchived != null) { - _queryParams["include_archived"] = includeArchived.toString(); + _queryParams.include_archived = includeArchived.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "data_attributes", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataAttributeList, rawResponse: _response.rawResponse }; @@ -153,112 +103,59 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /data_attributes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/data_attributes"); } /** * You can create a data attributes for a `contact` or a `company`. * - * @param {Intercom.unstable.CreateDataAttributeRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {unknown} request + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.dataAttributes.createDataAttribute({ - * name: "Mithril Shirt", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.unstable.dataAttributes.createDataAttribute({ - * name: "The One Ring", - * model: "contact", - * data_type: "integer" - * }) - * - * @example - * await client.unstable.dataAttributes.createDataAttribute({ - * name: "!nv@l!d n@me", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.unstable.dataAttributes.createDataAttribute({ - * name: "The One Ring", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.unstable.dataAttributes.createDataAttribute({ - * name: "The Second Ring", - * model: "company", - * data_type: "string" - * }) - * - * @example - * await client.unstable.dataAttributes.createDataAttribute({ - * name: "My Data Attribute", - * model: "contact", - * data_type: "string", - * description: "Just a plain old ring", - * options: ["options"] + * "key": "value" * }) */ public createDataAttribute( - request: Intercom.unstable.CreateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + request?: unknown, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createDataAttribute(request, requestOptions)); } private async __createDataAttribute( - request: Intercom.unstable.CreateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + request?: unknown, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "data_attributes", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataAttribute, rawResponse: _response.rawResponse }; @@ -282,21 +179,7 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /data_attributes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/data_attributes"); } /** @@ -308,7 +191,7 @@ export class DataAttributes { * > It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead. * * @param {Intercom.unstable.UpdateDataAttributeRequest} request - * @param {DataAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -318,63 +201,48 @@ export class DataAttributes { * @example * await client.unstable.dataAttributes.updateDataAttribute({ * id: 1, - * archived: false, - * description: "Just a plain old ring", - * options: ["options", "options"] - * }) - * - * @example - * await client.unstable.dataAttributes.updateDataAttribute({ - * id: 1, - * archived: false, - * description: "Too few options", - * options: ["option1", "option2"] - * }) - * - * @example - * await client.unstable.dataAttributes.updateDataAttribute({ - * id: 1, - * archived: true, - * description: "Trying to archieve" + * body: { + * "key": "value" + * } * }) */ public updateDataAttribute( request: Intercom.unstable.UpdateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateDataAttribute(request, requestOptions)); } private async __updateDataAttribute( request: Intercom.unstable.UpdateDataAttributeRequest, - requestOptions?: DataAttributes.RequestOptions, + requestOptions?: DataAttributesClient.RequestOptions, ): Promise> { - const { id, ..._body } = request; + const { id, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `data_attributes/${encodeURIComponent(id)}`, + `data_attributes/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataAttribute, rawResponse: _response.rawResponse }; @@ -405,32 +273,6 @@ export class DataAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /data_attributes/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/data_attributes/{id}"); } } diff --git a/src/api/resources/unstable/resources/dataAttributes/client/index.ts b/src/api/resources/unstable/resources/dataAttributes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/dataAttributes/client/index.ts +++ b/src/api/resources/unstable/resources/dataAttributes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts b/src/api/resources/unstable/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts deleted file mode 100644 index d0856471..00000000 --- a/src/api/resources/unstable/resources/dataAttributes/client/requests/CreateDataAttributeRequest.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * @example - * { - * name: "Mithril Shirt", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The One Ring", - * model: "contact", - * data_type: "integer" - * } - * - * @example - * { - * name: "!nv@l!d n@me", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The One Ring", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "The Second Ring", - * model: "company", - * data_type: "string" - * } - * - * @example - * { - * name: "My Data Attribute", - * model: "contact", - * data_type: "string", - * description: "Just a plain old ring", - * options: ["options"] - * } - */ -export interface CreateDataAttributeRequest { - /** The name of the data attribute. */ - name: string; - /** The model that the data attribute belongs to. */ - model: CreateDataAttributeRequest.Model; - /** The type of data stored for this attribute. */ - data_type: CreateDataAttributeRequest.DataType; - /** The readable description you see in the UI for the attribute. */ - description?: string; - /** To create list attributes. Provide a set of hashes with `value` as the key of the options you want to make. `data_type` must be `string`. */ - options?: string[]; - /** Can this attribute be updated by the Messenger */ - messenger_writable?: boolean; -} - -export namespace CreateDataAttributeRequest { - /** - * The model that the data attribute belongs to. - */ - export type Model = "contact" | "company"; - export const Model = { - Contact: "contact", - Company: "company", - } as const; - /** - * The type of data stored for this attribute. - */ - export type DataType = "string" | "integer" | "float" | "boolean" | "datetime" | "date"; - export const DataType = { - String: "string", - Integer: "integer", - Float: "float", - Boolean: "boolean", - Datetime: "datetime", - Date: "date", - } as const; -} diff --git a/src/api/resources/unstable/resources/dataAttributes/client/requests/LisDataAttributesRequest.ts b/src/api/resources/unstable/resources/dataAttributes/client/requests/LisDataAttributesRequest.ts index 4764c380..89b6ac5f 100644 --- a/src/api/resources/unstable/resources/dataAttributes/client/requests/LisDataAttributesRequest.ts +++ b/src/api/resources/unstable/resources/dataAttributes/client/requests/LisDataAttributesRequest.ts @@ -1,20 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example - * {} + * { + * model: "contact", + * include_archived: true + * } */ export interface LisDataAttributesRequest { - /** - * Specify the data attribute model to return. - */ + /** Specify the data attribute model to return. */ model?: Intercom.unstable.LisDataAttributesRequestModel; - /** - * Include archived attributes in the list. By default we return only non archived data attributes. - */ + /** Include archived attributes in the list. By default we return only non archived data attributes. */ include_archived?: boolean; } diff --git a/src/api/resources/unstable/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts b/src/api/resources/unstable/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts index 80ea0b29..a2d7f595 100644 --- a/src/api/resources/unstable/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts +++ b/src/api/resources/unstable/resources/dataAttributes/client/requests/UpdateDataAttributeRequest.ts @@ -1,50 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * id: 1, - * archived: false, - * description: "Just a plain old ring", - * options: ["options", "options"] - * } - * - * @example - * { - * id: 1, - * archived: false, - * description: "Too few options", - * options: ["option1", "option2"] - * } - * - * @example - * { - * id: 1, - * archived: false, - * description: "Just a plain old ring", - * options: ["options", "options"] - * } - * - * @example - * { - * id: 1, - * archived: true, - * description: "Trying to archieve" + * body: { + * "key": "value" + * } * } */ export interface UpdateDataAttributeRequest { - /** - * The data attribute id - */ + /** The data attribute id */ id: number; - /** Whether the attribute is to be archived or not. */ - archived?: boolean; - /** The readable description you see in the UI for the attribute. */ - description?: string; - /** To create list attributes. Provide a set of hashes with `value` as the key of the options you want to make. `data_type` must be `string`. */ - options?: string[]; - /** Can this attribute be updated by the Messenger */ - messenger_writable?: boolean; + body?: unknown; } diff --git a/src/api/resources/unstable/resources/dataAttributes/client/requests/index.ts b/src/api/resources/unstable/resources/dataAttributes/client/requests/index.ts index 5b0976fe..7776c48b 100644 --- a/src/api/resources/unstable/resources/dataAttributes/client/requests/index.ts +++ b/src/api/resources/unstable/resources/dataAttributes/client/requests/index.ts @@ -1,3 +1,2 @@ -export { type LisDataAttributesRequest } from "./LisDataAttributesRequest"; -export { type CreateDataAttributeRequest } from "./CreateDataAttributeRequest"; -export { type UpdateDataAttributeRequest } from "./UpdateDataAttributeRequest"; +export type { LisDataAttributesRequest } from "./LisDataAttributesRequest.js"; +export type { UpdateDataAttributeRequest } from "./UpdateDataAttributeRequest.js"; diff --git a/src/api/resources/unstable/resources/dataAttributes/index.ts b/src/api/resources/unstable/resources/dataAttributes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/dataAttributes/index.ts +++ b/src/api/resources/unstable/resources/dataAttributes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/dataAttributes/types/DataAttribute.ts b/src/api/resources/unstable/resources/dataAttributes/types/DataAttribute.ts index cacf2b7b..090b36d1 100644 --- a/src/api/resources/unstable/resources/dataAttributes/types/DataAttribute.ts +++ b/src/api/resources/unstable/resources/dataAttributes/types/DataAttribute.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Data Attributes are metadata used to describe your contact, company and conversation models. These include standard and custom attributes. By using the data attributes endpoint, you can get the global list of attributes for your workspace, as well as create and archive custom attributes. @@ -43,18 +41,13 @@ export interface DataAttribute { } export namespace DataAttribute { - /** - * Value is `contact` for user/lead attributes and `company` for company attributes. - */ - export type Model = "contact" | "company"; + /** Value is `contact` for user/lead attributes and `company` for company attributes. */ export const Model = { Contact: "contact", Company: "company", } as const; - /** - * The data type of the attribute. - */ - export type DataType = "string" | "integer" | "float" | "boolean" | "date"; + export type Model = (typeof Model)[keyof typeof Model]; + /** The data type of the attribute. */ export const DataType = { String: "string", Integer: "integer", @@ -62,4 +55,5 @@ export namespace DataAttribute { Boolean: "boolean", Date: "date", } as const; + export type DataType = (typeof DataType)[keyof typeof DataType]; } diff --git a/src/api/resources/unstable/resources/dataAttributes/types/LisDataAttributesRequestModel.ts b/src/api/resources/unstable/resources/dataAttributes/types/LisDataAttributesRequestModel.ts index 9ee462c6..06e53b91 100644 --- a/src/api/resources/unstable/resources/dataAttributes/types/LisDataAttributesRequestModel.ts +++ b/src/api/resources/unstable/resources/dataAttributes/types/LisDataAttributesRequestModel.ts @@ -1,10 +1,9 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -export type LisDataAttributesRequestModel = "contact" | "company" | "conversation"; export const LisDataAttributesRequestModel = { Contact: "contact", Company: "company", Conversation: "conversation", } as const; +export type LisDataAttributesRequestModel = + (typeof LisDataAttributesRequestModel)[keyof typeof LisDataAttributesRequestModel]; diff --git a/src/api/resources/unstable/resources/dataAttributes/types/index.ts b/src/api/resources/unstable/resources/dataAttributes/types/index.ts index f452bb6b..7e5f4e72 100644 --- a/src/api/resources/unstable/resources/dataAttributes/types/index.ts +++ b/src/api/resources/unstable/resources/dataAttributes/types/index.ts @@ -1,2 +1,2 @@ -export * from "./LisDataAttributesRequestModel"; -export * from "./DataAttribute"; +export * from "./DataAttribute.js"; +export * from "./LisDataAttributesRequestModel.js"; diff --git a/src/api/resources/unstable/resources/dataEvents/client/Client.ts b/src/api/resources/unstable/resources/dataEvents/client/Client.ts index 7349e445..ad66e987 100644 --- a/src/api/resources/unstable/resources/dataEvents/client/Client.ts +++ b/src/api/resources/unstable/resources/dataEvents/client/Client.ts @@ -1,80 +1,30 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import { toJson } from "../../../../../../core/json"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import { toJson } from "../../../../../../core/json.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace DataEvents { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace DataEventsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Data Events */ -export class DataEvents { - constructor(protected readonly _options: DataEvents.Options = {}) {} +export class DataEventsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: DataEventsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * @@ -93,7 +43,7 @@ export class DataEvents { * You can optionally define the result page size as well with the `per_page` parameter. * * @param {Intercom.unstable.LisDataEventsRequest} request - * @param {DataEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -107,48 +57,45 @@ export class DataEvents { */ public lisDataEvents( request: Intercom.unstable.LisDataEventsRequest, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__lisDataEvents(request, requestOptions)); } private async __lisDataEvents( request: Intercom.unstable.LisDataEventsRequest, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): Promise> { const { filter, type: type_, summary } = request; const _queryParams: Record = {}; - _queryParams["filter"] = typeof filter === "string" ? filter : toJson(filter); - _queryParams["type"] = type_; + _queryParams.filter = typeof filter === "string" ? filter : toJson(filter); + _queryParams.type = type_; if (summary != null) { - _queryParams["summary"] = summary.toString(); + _queryParams.summary = summary.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataEventSummary, rawResponse: _response.rawResponse }; @@ -170,21 +117,7 @@ export class DataEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /events."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/events"); } /** @@ -230,8 +163,9 @@ export class DataEvents { * - Event lists containing duplicate events will have those duplicates ignored. * - Server errors will return a `500` response code and may contain an error message in the body. * + * * @param {Intercom.CreateDataEventRequestTwo} request - * @param {DataEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -242,40 +176,40 @@ export class DataEvents { */ public createDataEvent( request?: Intercom.CreateDataEventRequestTwo, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createDataEvent(request, requestOptions)); } private async __createDataEvent( request?: Intercom.CreateDataEventRequestTwo, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -297,28 +231,15 @@ export class DataEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /events."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/events"); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. * + * * @param {Intercom.unstable.CreateDataEventSummariesRequest} request - * @param {DataEvents.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataEventsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -327,40 +248,40 @@ export class DataEvents { */ public dataEventSummaries( request: Intercom.unstable.CreateDataEventSummariesRequest = {}, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__dataEventSummaries(request, requestOptions)); } private async __dataEventSummaries( request: Intercom.unstable.CreateDataEventSummariesRequest = {}, - requestOptions?: DataEvents.RequestOptions, + requestOptions?: DataEventsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "events/summaries", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -382,32 +303,6 @@ export class DataEvents { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /events/summaries."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/events/summaries"); } } diff --git a/src/api/resources/unstable/resources/dataEvents/client/index.ts b/src/api/resources/unstable/resources/dataEvents/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/dataEvents/client/index.ts +++ b/src/api/resources/unstable/resources/dataEvents/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/dataEvents/client/requests/CreateDataEventSummariesRequest.ts b/src/api/resources/unstable/resources/dataEvents/client/requests/CreateDataEventSummariesRequest.ts index 9e731802..ca40dbe7 100644 --- a/src/api/resources/unstable/resources/dataEvents/client/requests/CreateDataEventSummariesRequest.ts +++ b/src/api/resources/unstable/resources/dataEvents/client/requests/CreateDataEventSummariesRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/unstable/resources/dataEvents/client/requests/LisDataEventsRequest.ts b/src/api/resources/unstable/resources/dataEvents/client/requests/LisDataEventsRequest.ts index 713df5e3..0dc68cfc 100644 --- a/src/api/resources/unstable/resources/dataEvents/client/requests/LisDataEventsRequest.ts +++ b/src/api/resources/unstable/resources/dataEvents/client/requests/LisDataEventsRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -15,12 +13,8 @@ import * as Intercom from "../../../../../../index"; */ export interface LisDataEventsRequest { filter: Intercom.unstable.LisDataEventsRequestFilter; - /** - * The value must be user - */ + /** The value must be user */ type: string; - /** - * summary flag - */ + /** summary flag */ summary?: boolean; } diff --git a/src/api/resources/unstable/resources/dataEvents/client/requests/index.ts b/src/api/resources/unstable/resources/dataEvents/client/requests/index.ts index 59b33a62..06ee457d 100644 --- a/src/api/resources/unstable/resources/dataEvents/client/requests/index.ts +++ b/src/api/resources/unstable/resources/dataEvents/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type LisDataEventsRequest } from "./LisDataEventsRequest"; -export { type CreateDataEventSummariesRequest } from "./CreateDataEventSummariesRequest"; +export type { CreateDataEventSummariesRequest } from "./CreateDataEventSummariesRequest.js"; +export type { LisDataEventsRequest } from "./LisDataEventsRequest.js"; diff --git a/src/api/resources/unstable/resources/dataEvents/index.ts b/src/api/resources/unstable/resources/dataEvents/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/dataEvents/index.ts +++ b/src/api/resources/unstable/resources/dataEvents/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/dataEvents/types/DataEvent.ts b/src/api/resources/unstable/resources/dataEvents/types/DataEvent.ts index 124221eb..a88a24e6 100644 --- a/src/api/resources/unstable/resources/dataEvents/types/DataEvent.ts +++ b/src/api/resources/unstable/resources/dataEvents/types/DataEvent.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Data events are used to notify Intercom of changes to your data. diff --git a/src/api/resources/unstable/resources/dataEvents/types/LisDataEventsRequestFilter.ts b/src/api/resources/unstable/resources/dataEvents/types/LisDataEventsRequestFilter.ts index a12948ea..57f5d409 100644 --- a/src/api/resources/unstable/resources/dataEvents/types/LisDataEventsRequestFilter.ts +++ b/src/api/resources/unstable/resources/dataEvents/types/LisDataEventsRequestFilter.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type LisDataEventsRequestFilter = | { diff --git a/src/api/resources/unstable/resources/dataEvents/types/index.ts b/src/api/resources/unstable/resources/dataEvents/types/index.ts index 57668594..dbd381c1 100644 --- a/src/api/resources/unstable/resources/dataEvents/types/index.ts +++ b/src/api/resources/unstable/resources/dataEvents/types/index.ts @@ -1,2 +1,2 @@ -export * from "./LisDataEventsRequestFilter"; -export * from "./DataEvent"; +export * from "./DataEvent.js"; +export * from "./LisDataEventsRequestFilter.js"; diff --git a/src/api/resources/unstable/resources/dataExport/client/Client.ts b/src/api/resources/unstable/resources/dataExport/client/Client.ts index 6f6a2ebe..9381c9f5 100644 --- a/src/api/resources/unstable/resources/dataExport/client/Client.ts +++ b/src/api/resources/unstable/resources/dataExport/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import type * as Intercom from "../../../../../index.js"; -export declare namespace DataExport { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace DataExportClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Data Exports */ -export class DataExport { - constructor(protected readonly _options: DataExport.Options = {}) {} +export class DataExportClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: DataExportClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * To create your export job, you need to send a `POST` request to the export endpoint `https://api.intercom.io/export/content/data`. @@ -93,7 +43,7 @@ export class DataExport { * > Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99. * * @param {Intercom.unstable.CreateDataExportsRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.dataExport.createDataExport({ @@ -103,40 +53,40 @@ export class DataExport { */ public createDataExport( request: Intercom.unstable.CreateDataExportsRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createDataExport(request, requestOptions)); } private async __createDataExport( request: Intercom.unstable.CreateDataExportsRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "export/content/data", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataExport, rawResponse: _response.rawResponse }; @@ -150,21 +100,7 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /export/content/data."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/export/content/data"); } /** @@ -175,7 +111,7 @@ export class DataExport { * > All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available. * * @param {Intercom.unstable.GetDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.dataExport.getDataExport({ @@ -184,40 +120,38 @@ export class DataExport { */ public getDataExport( request: Intercom.unstable.GetDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getDataExport(request, requestOptions)); } private async __getDataExport( request: Intercom.unstable.GetDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `export/content/data/${encodeURIComponent(jobIdentifier)}`, + `export/content/data/${core.url.encodePathParam(jobIdentifier)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataExport, rawResponse: _response.rawResponse }; @@ -231,30 +165,19 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /export/content/data/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/export/content/data/{job_identifier}", + ); } /** * You can cancel your job * * @param {Intercom.unstable.CancelDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.dataExport.cancelDataExport({ @@ -263,40 +186,38 @@ export class DataExport { */ public cancelDataExport( request: Intercom.unstable.CancelDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__cancelDataExport(request, requestOptions)); } private async __cancelDataExport( request: Intercom.unstable.CancelDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `export/cancel/${encodeURIComponent(jobIdentifier)}`, + `export/cancel/${core.url.encodePathParam(jobIdentifier)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DataExport, rawResponse: _response.rawResponse }; @@ -310,23 +231,12 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /export/cancel/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/export/cancel/{job_identifier}", + ); } /** @@ -339,7 +249,7 @@ export class DataExport { * > You will have to specify the header Accept: `application/octet-stream` when hitting this endpoint. * * @param {Intercom.unstable.DownloadDataExportRequest} request - * @param {DataExport.RequestOptions} requestOptions - Request-specific configuration. + * @param {DataExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.dataExport.downloadDataExport({ @@ -348,40 +258,38 @@ export class DataExport { */ public downloadDataExport( request: Intercom.unstable.DownloadDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__downloadDataExport(request, requestOptions)); } private async __downloadDataExport( request: Intercom.unstable.DownloadDataExportRequest, - requestOptions?: DataExport.RequestOptions, + requestOptions?: DataExportClient.RequestOptions, ): Promise> { const { job_identifier: jobIdentifier } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `download/content/data/${encodeURIComponent(jobIdentifier)}`, + `download/content/data/${core.url.encodePathParam(jobIdentifier)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -395,34 +303,11 @@ export class DataExport { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /download/content/data/{job_identifier}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/download/content/data/{job_identifier}", + ); } } diff --git a/src/api/resources/unstable/resources/dataExport/client/index.ts b/src/api/resources/unstable/resources/dataExport/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/dataExport/client/index.ts +++ b/src/api/resources/unstable/resources/dataExport/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/dataExport/client/requests/CancelDataExportRequest.ts b/src/api/resources/unstable/resources/dataExport/client/requests/CancelDataExportRequest.ts index 39ed6925..4e387ec1 100644 --- a/src/api/resources/unstable/resources/dataExport/client/requests/CancelDataExportRequest.ts +++ b/src/api/resources/unstable/resources/dataExport/client/requests/CancelDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface CancelDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/unstable/resources/dataExport/client/requests/CreateDataExportsRequest.ts b/src/api/resources/unstable/resources/dataExport/client/requests/CreateDataExportsRequest.ts index 78a96196..8854b7c9 100644 --- a/src/api/resources/unstable/resources/dataExport/client/requests/CreateDataExportsRequest.ts +++ b/src/api/resources/unstable/resources/dataExport/client/requests/CreateDataExportsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/unstable/resources/dataExport/client/requests/DownloadDataExportRequest.ts b/src/api/resources/unstable/resources/dataExport/client/requests/DownloadDataExportRequest.ts index 4a7ee828..98aab0f3 100644 --- a/src/api/resources/unstable/resources/dataExport/client/requests/DownloadDataExportRequest.ts +++ b/src/api/resources/unstable/resources/dataExport/client/requests/DownloadDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DownloadDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/unstable/resources/dataExport/client/requests/GetDataExportRequest.ts b/src/api/resources/unstable/resources/dataExport/client/requests/GetDataExportRequest.ts index b03dfb16..e75f9c9d 100644 --- a/src/api/resources/unstable/resources/dataExport/client/requests/GetDataExportRequest.ts +++ b/src/api/resources/unstable/resources/dataExport/client/requests/GetDataExportRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface GetDataExportRequest { - /** - * job_identifier - */ + /** job_identifier */ job_identifier: string; } diff --git a/src/api/resources/unstable/resources/dataExport/client/requests/index.ts b/src/api/resources/unstable/resources/dataExport/client/requests/index.ts index 4f6d12f0..4a322611 100644 --- a/src/api/resources/unstable/resources/dataExport/client/requests/index.ts +++ b/src/api/resources/unstable/resources/dataExport/client/requests/index.ts @@ -1,4 +1,4 @@ -export { type CreateDataExportsRequest } from "./CreateDataExportsRequest"; -export { type GetDataExportRequest } from "./GetDataExportRequest"; -export { type CancelDataExportRequest } from "./CancelDataExportRequest"; -export { type DownloadDataExportRequest } from "./DownloadDataExportRequest"; +export type { CancelDataExportRequest } from "./CancelDataExportRequest.js"; +export type { CreateDataExportsRequest } from "./CreateDataExportsRequest.js"; +export type { DownloadDataExportRequest } from "./DownloadDataExportRequest.js"; +export type { GetDataExportRequest } from "./GetDataExportRequest.js"; diff --git a/src/api/resources/unstable/resources/dataExport/index.ts b/src/api/resources/unstable/resources/dataExport/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/dataExport/index.ts +++ b/src/api/resources/unstable/resources/dataExport/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/dataExport/types/DataExport.ts b/src/api/resources/unstable/resources/dataExport/types/DataExport.ts index bd19f8c9..c846e2bb 100644 --- a/src/api/resources/unstable/resources/dataExport/types/DataExport.ts +++ b/src/api/resources/unstable/resources/dataExport/types/DataExport.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The data export api is used to view all message sent & viewed in a given timeframe. @@ -17,10 +15,7 @@ export interface DataExport { } export namespace DataExport { - /** - * The current state of your job. - */ - export type Status = "pending" | "in_progress" | "failed" | "completed" | "no_data" | "canceled"; + /** The current state of your job. */ export const Status = { Pending: "pending", InProgress: "in_progress", @@ -29,4 +24,5 @@ export namespace DataExport { NoData: "no_data", Canceled: "canceled", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/unstable/resources/dataExport/types/index.ts b/src/api/resources/unstable/resources/dataExport/types/index.ts index 7cea751a..881ccc6c 100644 --- a/src/api/resources/unstable/resources/dataExport/types/index.ts +++ b/src/api/resources/unstable/resources/dataExport/types/index.ts @@ -1 +1 @@ -export * from "./DataExport"; +export * from "./DataExport.js"; diff --git a/src/api/resources/unstable/resources/emails/client/Client.ts b/src/api/resources/unstable/resources/emails/client/Client.ts new file mode 100644 index 00000000..80dc6bdf --- /dev/null +++ b/src/api/resources/unstable/resources/emails/client/Client.ts @@ -0,0 +1,166 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; + +export declare namespace EmailsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Emails + */ +export class EmailsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: EmailsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * Lists all sender email address settings for the workspace + * + * @param {EmailsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.emails.listEmails() + */ + public listEmails( + requestOptions?: EmailsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listEmails(requestOptions)); + } + + private async __listEmails( + requestOptions?: EmailsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "emails", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.EmailList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/emails"); + } + + /** + * Fetches a specific email setting by its unique identifier + * + * @param {Intercom.unstable.RetrieveEmailRequest} request + * @param {EmailsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.emails.retrieveEmail({ + * id: "id" + * }) + */ + public retrieveEmail( + request: Intercom.unstable.RetrieveEmailRequest, + requestOptions?: EmailsClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveEmail(request, requestOptions)); + } + + private async __retrieveEmail( + request: Intercom.unstable.RetrieveEmailRequest, + requestOptions?: EmailsClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `emails/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.EmailSetting, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/emails/{id}"); + } +} diff --git a/src/api/resources/unstable/resources/emails/client/index.ts b/src/api/resources/unstable/resources/emails/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/unstable/resources/emails/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/emails/client/requests/RetrieveEmailRequest.ts b/src/api/resources/unstable/resources/emails/client/requests/RetrieveEmailRequest.ts new file mode 100644 index 00000000..7e8d58ab --- /dev/null +++ b/src/api/resources/unstable/resources/emails/client/requests/RetrieveEmailRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "id" + * } + */ +export interface RetrieveEmailRequest { + /** The unique identifier of the email setting */ + id: string; +} diff --git a/src/api/resources/unstable/resources/emails/client/requests/index.ts b/src/api/resources/unstable/resources/emails/client/requests/index.ts new file mode 100644 index 00000000..28137871 --- /dev/null +++ b/src/api/resources/unstable/resources/emails/client/requests/index.ts @@ -0,0 +1 @@ +export type { RetrieveEmailRequest } from "./RetrieveEmailRequest.js"; diff --git a/src/api/resources/unstable/resources/emails/index.ts b/src/api/resources/unstable/resources/emails/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/unstable/resources/emails/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/emails/types/EmailList.ts b/src/api/resources/unstable/resources/emails/types/EmailList.ts new file mode 100644 index 00000000..41aa6d09 --- /dev/null +++ b/src/api/resources/unstable/resources/emails/types/EmailList.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * A list of email settings + */ +export interface EmailList { + /** The type of object */ + type?: string; + data?: Intercom.unstable.EmailSetting[]; +} diff --git a/src/api/resources/unstable/resources/emails/types/EmailSetting.ts b/src/api/resources/unstable/resources/emails/types/EmailSetting.ts new file mode 100644 index 00000000..bd584aec --- /dev/null +++ b/src/api/resources/unstable/resources/emails/types/EmailSetting.ts @@ -0,0 +1,27 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Represents a sender email address configuration + */ +export interface EmailSetting { + /** The type of object */ + type?: string; + /** Unique email setting identifier */ + id?: string; + /** Full sender email address */ + email?: string; + /** Whether the email address has been verified */ + verified?: boolean; + /** Domain portion of the email address */ + domain?: string; + /** Associated brand identifier */ + brand_id?: string; + /** Whether email forwarding is active */ + forwarding_enabled?: boolean; + /** Unix timestamp of last forwarded email received (null if never) */ + forwarded_email_last_received_at?: number; + /** Unix timestamp of creation */ + created_at?: number; + /** Unix timestamp of last modification */ + updated_at?: number; +} diff --git a/src/api/resources/unstable/resources/emails/types/index.ts b/src/api/resources/unstable/resources/emails/types/index.ts new file mode 100644 index 00000000..ffc91a1b --- /dev/null +++ b/src/api/resources/unstable/resources/emails/types/index.ts @@ -0,0 +1,2 @@ +export * from "./EmailList.js"; +export * from "./EmailSetting.js"; diff --git a/src/api/resources/unstable/resources/export/client/Client.ts b/src/api/resources/unstable/resources/export/client/Client.ts index b067f559..af0ecc87 100644 --- a/src/api/resources/unstable/resources/export/client/Client.ts +++ b/src/api/resources/unstable/resources/export/client/Client.ts @@ -1,80 +1,30 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Export { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace ExportClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } -export class Export { - constructor(protected readonly _options: Export.Options = {}) {} +export class ExportClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ExportClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * @param {Intercom.unstable.PostExportReportingDataEnqueueRequest} request - * @param {Export.RequestOptions} requestOptions - Request-specific configuration. + * @param {ExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -83,47 +33,47 @@ export class Export { * @example * await client.unstable.export.enqueueANewReportingDataExportJob({ * dataset_id: "conversation", - * attribute_ids: ["conversation.id", "conversation.first_user_conversation_part_created_at"], + * attribute_ids: ["conversation_id", "conversation_started_at"], * start_time: 1717490000, * end_time: 1717510000 * }) */ public enqueueANewReportingDataExportJob( request: Intercom.unstable.PostExportReportingDataEnqueueRequest, - requestOptions?: Export.RequestOptions, + requestOptions?: ExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__enqueueANewReportingDataExportJob(request, requestOptions)); } private async __enqueueANewReportingDataExportJob( request: Intercom.unstable.PostExportReportingDataEnqueueRequest, - requestOptions?: Export.RequestOptions, + requestOptions?: ExportClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "export/reporting_data/enqueue", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -155,64 +105,51 @@ export class Export { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /export/reporting_data/enqueue.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/export/reporting_data/enqueue", + ); } /** - * @param {Export.RequestOptions} requestOptions - Request-specific configuration. + * @param {ExportClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.export.listAvailableDatasetsAndAttributes() */ public listAvailableDatasetsAndAttributes( - requestOptions?: Export.RequestOptions, + requestOptions?: ExportClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAvailableDatasetsAndAttributes(requestOptions)); } private async __listAvailableDatasetsAndAttributes( - requestOptions?: Export.RequestOptions, + requestOptions?: ExportClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "export/reporting_data/get_datasets", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -229,34 +166,11 @@ export class Export { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /export/reporting_data/get_datasets.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/export/reporting_data/get_datasets", + ); } } diff --git a/src/api/resources/unstable/resources/export/client/index.ts b/src/api/resources/unstable/resources/export/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/export/client/index.ts +++ b/src/api/resources/unstable/resources/export/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts b/src/api/resources/unstable/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts index 55c7d4f8..57767a44 100644 --- a/src/api/resources/unstable/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts +++ b/src/api/resources/unstable/resources/export/client/requests/PostExportReportingDataEnqueueRequest.ts @@ -1,12 +1,10 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { * dataset_id: "conversation", - * attribute_ids: ["conversation.id", "conversation.first_user_conversation_part_created_at"], + * attribute_ids: ["conversation_id", "conversation_started_at"], * start_time: 1717490000, * end_time: 1717510000 * } diff --git a/src/api/resources/unstable/resources/export/client/requests/index.ts b/src/api/resources/unstable/resources/export/client/requests/index.ts index bcda81be..a18772b7 100644 --- a/src/api/resources/unstable/resources/export/client/requests/index.ts +++ b/src/api/resources/unstable/resources/export/client/requests/index.ts @@ -1 +1 @@ -export { type PostExportReportingDataEnqueueRequest } from "./PostExportReportingDataEnqueueRequest"; +export type { PostExportReportingDataEnqueueRequest } from "./PostExportReportingDataEnqueueRequest.js"; diff --git a/src/api/resources/unstable/resources/export/index.ts b/src/api/resources/unstable/resources/export/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/export/index.ts +++ b/src/api/resources/unstable/resources/export/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts b/src/api/resources/unstable/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts index ab8c3ba6..725ac29a 100644 --- a/src/api/resources/unstable/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts +++ b/src/api/resources/unstable/resources/export/types/GetExportReportingDataGetDatasetsResponse.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface GetExportReportingDataGetDatasetsResponse { type?: string; diff --git a/src/api/resources/unstable/resources/export/types/PostExportReportingDataEnqueueResponse.ts b/src/api/resources/unstable/resources/export/types/PostExportReportingDataEnqueueResponse.ts index 55a28e65..c15d988e 100644 --- a/src/api/resources/unstable/resources/export/types/PostExportReportingDataEnqueueResponse.ts +++ b/src/api/resources/unstable/resources/export/types/PostExportReportingDataEnqueueResponse.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface PostExportReportingDataEnqueueResponse { job_identifier?: string; diff --git a/src/api/resources/unstable/resources/export/types/index.ts b/src/api/resources/unstable/resources/export/types/index.ts index cc8706ee..27e82ed3 100644 --- a/src/api/resources/unstable/resources/export/types/index.ts +++ b/src/api/resources/unstable/resources/export/types/index.ts @@ -1,2 +1,2 @@ -export * from "./PostExportReportingDataEnqueueResponse"; -export * from "./GetExportReportingDataGetDatasetsResponse"; +export * from "./GetExportReportingDataGetDatasetsResponse.js"; +export * from "./PostExportReportingDataEnqueueResponse.js"; diff --git a/src/api/resources/unstable/resources/helpCenter/client/Client.ts b/src/api/resources/unstable/resources/helpCenter/client/Client.ts index 776053b4..73d06f5d 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/Client.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/Client.ts @@ -1,86 +1,36 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; - -export declare namespace HelpCenter { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } +export declare namespace HelpCenterClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Help Center */ -export class HelpCenter { - constructor(protected readonly _options: HelpCenter.Options = {}) {} +export class HelpCenterClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: HelpCenterClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all collections by making a GET request to `https://api.intercom.io/help_center/collections`. * * Collections will be returned in descending order on the `updated_at` attribute. This means if you need to iterate through results then we'll show the most recently updated collections first. * - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -88,38 +38,36 @@ export class HelpCenter { * await client.unstable.helpCenter.listAllCollections() */ public listAllCollections( - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listAllCollections(requestOptions)); } private async __listAllCollections( - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/collections", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.CollectionList, rawResponse: _response.rawResponse }; @@ -141,28 +89,14 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /help_center/collections."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/help_center/collections"); } /** * You can create a new collection by making a POST request to `https://api.intercom.io/help_center/collections.` * * @param {Intercom.unstable.CreateCollectionRequest} request - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -180,40 +114,40 @@ export class HelpCenter { */ public createCollection( request: Intercom.unstable.CreateCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createCollection(request, requestOptions)); } private async __createCollection( request: Intercom.unstable.CreateCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/collections", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Collection, rawResponse: _response.rawResponse }; @@ -237,28 +171,14 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /help_center/collections."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/help_center/collections"); } /** * You can fetch the details of a single collection by making a GET request to `https://api.intercom.io/help_center/collections/`. * * @param {Intercom.unstable.RetrieveCollectionRequest} request - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -270,40 +190,38 @@ export class HelpCenter { */ public retrieveCollection( request: Intercom.unstable.RetrieveCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveCollection(request, requestOptions)); } private async __retrieveCollection( request: Intercom.unstable.RetrieveCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(id)}`, + `help_center/collections/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Collection, rawResponse: _response.rawResponse }; @@ -327,30 +245,14 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/collections/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/help_center/collections/{id}"); } /** * You can update the details of a single collection by making a PUT request to `https://api.intercom.io/collections/`. * * @param {Intercom.unstable.UpdateCollectionRequest} request - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -363,41 +265,41 @@ export class HelpCenter { */ public updateCollection( request: Intercom.unstable.UpdateCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateCollection(request, requestOptions)); } private async __updateCollection( request: Intercom.unstable.UpdateCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(id)}`, + `help_center/collections/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Collection, rawResponse: _response.rawResponse }; @@ -421,30 +323,14 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /help_center/collections/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/help_center/collections/{id}"); } /** * You can delete a single collection by making a DELETE request to `https://api.intercom.io/collections/`. * * @param {Intercom.unstable.DeleteCollectionRequest} request - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -456,40 +342,38 @@ export class HelpCenter { */ public deleteCollection( request: Intercom.unstable.DeleteCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteCollection(request, requestOptions)); } private async __deleteCollection( request: Intercom.unstable.DeleteCollectionRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/collections/${encodeURIComponent(id)}`, + `help_center/collections/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -516,30 +400,19 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /help_center/collections/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/help_center/collections/{id}", + ); } /** * You can fetch the details of a single Help Center by making a GET request to `https://api.intercom.io/help_center/help_center/`. * * @param {Intercom.unstable.RetrieveHelpCenterRequest} request - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -551,40 +424,38 @@ export class HelpCenter { */ public retrieveHelpCenter( request: Intercom.unstable.RetrieveHelpCenterRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveHelpCenter(request, requestOptions)); } private async __retrieveHelpCenter( request: Intercom.unstable.RetrieveHelpCenterRequest, - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `help_center/help_centers/${encodeURIComponent(id)}`, + `help_center/help_centers/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.HelpCenter, rawResponse: _response.rawResponse }; @@ -608,29 +479,18 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling GET /help_center/help_centers/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "GET", + "/help_center/help_centers/{id}", + ); } /** * You can list all Help Centers by making a GET request to `https://api.intercom.io/help_center/help_centers`. * - * @param {HelpCenter.RequestOptions} requestOptions - Request-specific configuration. + * @param {HelpCenterClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -638,38 +498,36 @@ export class HelpCenter { * await client.unstable.helpCenter.listHelpCenters() */ public listHelpCenters( - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listHelpCenters(requestOptions)); } private async __listHelpCenters( - requestOptions?: HelpCenter.RequestOptions, + requestOptions?: HelpCenterClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "help_center/help_centers", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.HelpCenterList, rawResponse: _response.rawResponse }; @@ -691,32 +549,6 @@ export class HelpCenter { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /help_center/help_centers."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/help_center/help_centers"); } } diff --git a/src/api/resources/unstable/resources/helpCenter/client/index.ts b/src/api/resources/unstable/resources/helpCenter/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/index.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/CreateCollectionRequest.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/CreateCollectionRequest.ts index 7b50caa9..79a825bf 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/CreateCollectionRequest.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/CreateCollectionRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/DeleteCollectionRequest.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/DeleteCollectionRequest.ts index eaf33993..fb363f5c 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/DeleteCollectionRequest.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/DeleteCollectionRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ + /** The unique identifier for the collection which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveCollectionRequest.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveCollectionRequest.ts index 4737b56b..b444789d 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveCollectionRequest.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveCollectionRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ + /** The unique identifier for the collection which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveHelpCenterRequest.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveHelpCenterRequest.ts index 42057096..b4787e86 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveHelpCenterRequest.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/RetrieveHelpCenterRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveHelpCenterRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ + /** The unique identifier for the collection which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/UpdateCollectionRequest.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/UpdateCollectionRequest.ts index 58505b62..9caeacc0 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/UpdateCollectionRequest.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/UpdateCollectionRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -18,9 +16,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface UpdateCollectionRequest { - /** - * The unique identifier for the collection which is given by Intercom. - */ + /** The unique identifier for the collection which is given by Intercom. */ id: number; /** The name of the collection. For multilingual collections, this will be the name of the default language's content. */ name?: string; diff --git a/src/api/resources/unstable/resources/helpCenter/client/requests/index.ts b/src/api/resources/unstable/resources/helpCenter/client/requests/index.ts index b39271fa..d2d1c0aa 100644 --- a/src/api/resources/unstable/resources/helpCenter/client/requests/index.ts +++ b/src/api/resources/unstable/resources/helpCenter/client/requests/index.ts @@ -1,5 +1,5 @@ -export { type CreateCollectionRequest } from "./CreateCollectionRequest"; -export { type RetrieveCollectionRequest } from "./RetrieveCollectionRequest"; -export { type UpdateCollectionRequest } from "./UpdateCollectionRequest"; -export { type DeleteCollectionRequest } from "./DeleteCollectionRequest"; -export { type RetrieveHelpCenterRequest } from "./RetrieveHelpCenterRequest"; +export type { CreateCollectionRequest } from "./CreateCollectionRequest.js"; +export type { DeleteCollectionRequest } from "./DeleteCollectionRequest.js"; +export type { RetrieveCollectionRequest } from "./RetrieveCollectionRequest.js"; +export type { RetrieveHelpCenterRequest } from "./RetrieveHelpCenterRequest.js"; +export type { UpdateCollectionRequest } from "./UpdateCollectionRequest.js"; diff --git a/src/api/resources/unstable/resources/helpCenter/index.ts b/src/api/resources/unstable/resources/helpCenter/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/helpCenter/index.ts +++ b/src/api/resources/unstable/resources/helpCenter/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/helpCenter/types/Collection.ts b/src/api/resources/unstable/resources/helpCenter/types/Collection.ts index ef0fa2ec..475021d4 100644 --- a/src/api/resources/unstable/resources/helpCenter/types/Collection.ts +++ b/src/api/resources/unstable/resources/helpCenter/types/Collection.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Collections are top level containers for Articles within the Help Center. diff --git a/src/api/resources/unstable/resources/helpCenter/types/HelpCenter.ts b/src/api/resources/unstable/resources/helpCenter/types/HelpCenter.ts index 30cba20e..3715e87f 100644 --- a/src/api/resources/unstable/resources/helpCenter/types/HelpCenter.ts +++ b/src/api/resources/unstable/resources/helpCenter/types/HelpCenter.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Help Centers contain collections @@ -20,4 +18,8 @@ export interface HelpCenter { website_turned_on?: boolean; /** The display name of the Help Center only seen by teammates. */ display_name?: string; + /** The URL for the help center, if you have a custom domain then this will show the URL using the custom domain. */ + url?: string; + /** Custom domain configured for the help center */ + custom_domain?: string; } diff --git a/src/api/resources/unstable/resources/helpCenter/types/HelpCenterList.ts b/src/api/resources/unstable/resources/helpCenter/types/HelpCenterList.ts index ee6c2a05..75bc4786 100644 --- a/src/api/resources/unstable/resources/helpCenter/types/HelpCenterList.ts +++ b/src/api/resources/unstable/resources/helpCenter/types/HelpCenterList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A list of Help Centers belonging to the App diff --git a/src/api/resources/unstable/resources/helpCenter/types/index.ts b/src/api/resources/unstable/resources/helpCenter/types/index.ts index 65d348a7..097e7b49 100644 --- a/src/api/resources/unstable/resources/helpCenter/types/index.ts +++ b/src/api/resources/unstable/resources/helpCenter/types/index.ts @@ -1,3 +1,3 @@ -export * from "./Collection"; -export * from "./HelpCenter"; -export * from "./HelpCenterList"; +export * from "./Collection.js"; +export * from "./HelpCenter.js"; +export * from "./HelpCenterList.js"; diff --git a/src/api/resources/unstable/resources/index.ts b/src/api/resources/unstable/resources/index.ts index a7c8f375..47fc9e84 100644 --- a/src/api/resources/unstable/resources/index.ts +++ b/src/api/resources/unstable/resources/index.ts @@ -1,78 +1,93 @@ -export * as admins from "./admins"; -export * from "./admins/types"; -export * as aiContent from "./aiContent"; -export * from "./aiContent/types"; -export * as articles from "./articles"; -export * from "./articles/types"; -export * as export_ from "./export"; -export * from "./export/types"; -export * as helpCenter from "./helpCenter"; -export * from "./helpCenter/types"; -export * as companies from "./companies"; -export * from "./companies/types"; -export * as contacts from "./contacts"; -export * from "./contacts/types"; -export * as notes from "./notes"; -export * from "./notes/types"; -export * as subscriptionTypes from "./subscriptionTypes"; -export * from "./subscriptionTypes/types"; -export * as tags from "./tags"; -export * from "./tags/types"; -export * as conversations from "./conversations"; -export * from "./conversations/types"; -export * as customObjectInstances from "./customObjectInstances"; -export * from "./customObjectInstances/types"; -export * as dataAttributes from "./dataAttributes"; -export * from "./dataAttributes/types"; -export * as dataEvents from "./dataEvents"; -export * from "./dataEvents/types"; -export * as dataExport from "./dataExport"; -export * from "./dataExport/types"; -export * as jobs from "./jobs"; -export * from "./jobs/types"; -export * as messages from "./messages"; -export * from "./messages/types"; -export * as news from "./news"; -export * from "./news/types"; -export * as segments from "./segments"; -export * from "./segments/types"; -export * as teams from "./teams"; -export * from "./teams/types"; -export * as tickets from "./tickets"; -export * from "./tickets/types"; -export * as aiAgent from "./aiAgent"; -export * from "./aiAgent/types"; -export * as aiContentSource from "./aiContentSource"; -export * from "./aiContentSource/types"; -export * as awayStatusReasons from "./awayStatusReasons"; -export * as customChannelEvents from "./customChannelEvents"; -export * as switch_ from "./switch"; -export * as ticketStates from "./ticketStates"; -export * as ticketTypeAttributes from "./ticketTypeAttributes"; -export * as ticketTypes from "./ticketTypes"; -export * as visitors from "./visitors"; -export * from "./admins/client/requests"; -export * from "./aiContent/client/requests"; -export * from "./articles/client/requests"; -export * from "./export/client/requests"; -export * from "./helpCenter/client/requests"; -export * from "./companies/client/requests"; -export * from "./contacts/client/requests"; -export * from "./notes/client/requests"; -export * from "./subscriptionTypes/client/requests"; -export * from "./tags/client/requests"; -export * from "./conversations/client/requests"; -export * from "./customChannelEvents/client/requests"; -export * from "./customObjectInstances/client/requests"; -export * from "./dataAttributes/client/requests"; -export * from "./dataEvents/client/requests"; -export * from "./dataExport/client/requests"; -export * from "./jobs/client/requests"; -export * from "./messages/client/requests"; -export * from "./news/client/requests"; -export * from "./segments/client/requests"; -export * from "./teams/client/requests"; -export * from "./ticketTypeAttributes/client/requests"; -export * from "./ticketTypes/client/requests"; -export * from "./tickets/client/requests"; -export * from "./visitors/client/requests"; +export * from "./admins/client/requests/index.js"; +export * as admins from "./admins/index.js"; +export * from "./admins/types/index.js"; +export * as aiAgent from "./aiAgent/index.js"; +export * from "./aiAgent/types/index.js"; +export * from "./aiContent/client/requests/index.js"; +export * as aiContent from "./aiContent/index.js"; +export * from "./aiContent/types/index.js"; +export * as aiContentSource from "./aiContentSource/index.js"; +export * from "./aiContentSource/types/index.js"; +export * from "./articles/client/requests/index.js"; +export * as articles from "./articles/index.js"; +export * from "./articles/types/index.js"; +export * as awayStatusReasons from "./awayStatusReasons/index.js"; +export * from "./brands/client/requests/index.js"; +export * as brands from "./brands/index.js"; +export * from "./brands/types/index.js"; +export * from "./calls/client/requests/index.js"; +export * as calls from "./calls/index.js"; +export * from "./calls/types/index.js"; +export * from "./companies/client/requests/index.js"; +export * as companies from "./companies/index.js"; +export * from "./companies/types/index.js"; +export * from "./contacts/client/requests/index.js"; +export * as contacts from "./contacts/index.js"; +export * from "./contacts/types/index.js"; +export * from "./conversations/client/requests/index.js"; +export * as conversations from "./conversations/index.js"; +export * from "./conversations/types/index.js"; +export * from "./customChannelEvents/client/requests/index.js"; +export * as customChannelEvents from "./customChannelEvents/index.js"; +export * from "./customObjectInstances/client/requests/index.js"; +export * as customObjectInstances from "./customObjectInstances/index.js"; +export * from "./customObjectInstances/types/index.js"; +export * from "./dataAttributes/client/requests/index.js"; +export * as dataAttributes from "./dataAttributes/index.js"; +export * from "./dataAttributes/types/index.js"; +export * from "./dataEvents/client/requests/index.js"; +export * as dataEvents from "./dataEvents/index.js"; +export * from "./dataEvents/types/index.js"; +export * from "./dataExport/client/requests/index.js"; +export * as dataExport from "./dataExport/index.js"; +export * from "./dataExport/types/index.js"; +export * from "./emails/client/requests/index.js"; +export * as emails from "./emails/index.js"; +export * from "./emails/types/index.js"; +export * from "./export/client/requests/index.js"; +export * as export_ from "./export/index.js"; +export * from "./export/types/index.js"; +export * from "./helpCenter/client/requests/index.js"; +export * as helpCenter from "./helpCenter/index.js"; +export * from "./helpCenter/types/index.js"; +export * from "./internalArticles/client/requests/index.js"; +export * as internalArticles from "./internalArticles/index.js"; +export * from "./internalArticles/types/index.js"; +export * from "./jobs/client/requests/index.js"; +export * as jobs from "./jobs/index.js"; +export * from "./jobs/types/index.js"; +export * from "./macros/client/requests/index.js"; +export * as macros from "./macros/index.js"; +export * from "./macros/types/index.js"; +export * from "./messages/client/requests/index.js"; +export * as messages from "./messages/index.js"; +export * from "./messages/types/index.js"; +export * from "./news/client/requests/index.js"; +export * as news from "./news/index.js"; +export * from "./news/types/index.js"; +export * from "./notes/client/requests/index.js"; +export * as notes from "./notes/index.js"; +export * from "./notes/types/index.js"; +export * from "./segments/client/requests/index.js"; +export * as segments from "./segments/index.js"; +export * from "./segments/types/index.js"; +export * from "./subscriptionTypes/client/requests/index.js"; +export * as subscriptionTypes from "./subscriptionTypes/index.js"; +export * from "./subscriptionTypes/types/index.js"; +export * as switch_ from "./switch/index.js"; +export * from "./tags/client/requests/index.js"; +export * as tags from "./tags/index.js"; +export * from "./tags/types/index.js"; +export * from "./teams/client/requests/index.js"; +export * as teams from "./teams/index.js"; +export * from "./teams/types/index.js"; +export * as ticketStates from "./ticketStates/index.js"; +export * from "./tickets/client/requests/index.js"; +export * as tickets from "./tickets/index.js"; +export * from "./tickets/types/index.js"; +export * from "./ticketTypeAttributes/client/requests/index.js"; +export * as ticketTypeAttributes from "./ticketTypeAttributes/index.js"; +export * from "./ticketTypes/client/requests/index.js"; +export * as ticketTypes from "./ticketTypes/index.js"; +export * from "./visitors/client/requests/index.js"; +export * as visitors from "./visitors/index.js"; diff --git a/src/api/resources/unstable/resources/internalArticles/client/Client.ts b/src/api/resources/unstable/resources/internalArticles/client/Client.ts new file mode 100644 index 00000000..bcfe5c32 --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/Client.ts @@ -0,0 +1,491 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; + +export declare namespace InternalArticlesClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Everything about your Internal Articles + */ +export class InternalArticlesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: InternalArticlesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can fetch a list of all internal articles by making a GET request to `https://api.intercom.io/internal_articles`. + * + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.internalArticles.listInternalArticles() + */ + public listInternalArticles( + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listInternalArticles(requestOptions)); + } + + private async __listInternalArticles( + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles", + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.unstable.InternalArticleList, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/internal_articles"); + } + + /** + * You can create a new internal article by making a POST request to `https://api.intercom.io/internal_articles`. + * + * @param {Intercom.unstable.CreateInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.BadRequestError} + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.internalArticles.createInternalArticle({ + * title: "Thanks for everything", + * body: "Body of the Article", + * author_id: 991266252, + * owner_id: 991266252 + * }) + * + * @example + * await client.unstable.internalArticles.createInternalArticle({ + * title: "Thanks for everything", + * body: "Body of the Internal Article", + * author_id: 1295, + * owner_id: 1295 + * }) + */ + public createInternalArticle( + request?: Intercom.unstable.CreateInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createInternalArticle(request, requestOptions)); + } + + private async __createInternalArticle( + request?: Intercom.unstable.CreateInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles", + ), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.unstable.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/internal_articles"); + } + + /** + * You can fetch the details of a single internal article by making a GET request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.unstable.RetrieveInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.internalArticles.retrieveInternalArticle({ + * id: 1 + * }) + */ + public retrieveInternalArticle( + request: Intercom.unstable.RetrieveInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveInternalArticle(request, requestOptions)); + } + + private async __retrieveInternalArticle( + request: Intercom.unstable.RetrieveInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/internal_articles/{id}"); + } + + /** + * You can update the details of a single internal article by making a PUT request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.unstable.UpdateInternalArticleRequestBody} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.internalArticles.updateInternalArticle({ + * id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * }) + */ + public updateInternalArticle( + request: Intercom.unstable.UpdateInternalArticleRequestBody, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateInternalArticle(request, requestOptions)); + } + + private async __updateInternalArticle( + request: Intercom.unstable.UpdateInternalArticleRequestBody, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(id)}`, + ), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions?.queryParams, + requestType: "json", + body: _body, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.InternalArticle, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/internal_articles/{id}"); + } + + /** + * You can delete a single internal article by making a DELETE request to `https://api.intercom.io/internal_articles/`. + * + * @param {Intercom.unstable.DeleteInternalArticleRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.internalArticles.deleteInternalArticle({ + * id: 1 + * }) + */ + public deleteInternalArticle( + request: Intercom.unstable.DeleteInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteInternalArticle(request, requestOptions)); + } + + private async __deleteInternalArticle( + request: Intercom.unstable.DeleteInternalArticleRequest, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `internal_articles/${core.url.encodePathParam(id)}`, + ), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.unstable.DeletedInternalArticleObject, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/internal_articles/{id}"); + } + + /** + * You can search for internal articles by making a GET request to `https://api.intercom.io/internal_articles/search`. + * + * @param {Intercom.unstable.SearchInternalArticlesRequest} request + * @param {InternalArticlesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * + * @example + * await client.unstable.internalArticles.searchInternalArticles({ + * folder_id: "folder_id" + * }) + */ + public searchInternalArticles( + request: Intercom.unstable.SearchInternalArticlesRequest = {}, + requestOptions?: InternalArticlesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchInternalArticles(request, requestOptions)); + } + + private async __searchInternalArticles( + request: Intercom.unstable.SearchInternalArticlesRequest = {}, + requestOptions?: InternalArticlesClient.RequestOptions, + ): Promise> { + const { folder_id: folderId } = request; + const _queryParams: Record = {}; + if (folderId != null) { + _queryParams.folder_id = folderId; + } + + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "internal_articles/search", + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: _response.body as Intercom.unstable.InternalArticleSearchResponse, + rawResponse: _response.rawResponse, + }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/internal_articles/search"); + } +} diff --git a/src/api/resources/unstable/resources/internalArticles/client/index.ts b/src/api/resources/unstable/resources/internalArticles/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts b/src/api/resources/unstable/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts new file mode 100644 index 00000000..dd3f7586 --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/requests/DeleteInternalArticleRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: 1 + * } + */ +export interface DeleteInternalArticleRequest { + /** The unique identifier for the internal article which is given by Intercom. */ + id: number; +} diff --git a/src/api/resources/unstable/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts b/src/api/resources/unstable/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts new file mode 100644 index 00000000..bf5d0ece --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/requests/RetrieveInternalArticleRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: 1 + * } + */ +export interface RetrieveInternalArticleRequest { + /** The unique identifier for the article which is given by Intercom. */ + id: number; +} diff --git a/src/api/resources/unstable/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts b/src/api/resources/unstable/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts new file mode 100644 index 00000000..6f80cf05 --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/requests/SearchInternalArticlesRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * folder_id: "folder_id" + * } + */ +export interface SearchInternalArticlesRequest { + /** The ID of the folder to search in. */ + folder_id?: string; +} diff --git a/src/api/resources/unstable/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts b/src/api/resources/unstable/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts new file mode 100644 index 00000000..ffd0c32d --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/requests/UpdateInternalArticleRequestBody.ts @@ -0,0 +1,29 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * } + * + * @example + * { + * id: 1, + * title: "Christmas is here!", + * body: "

New gifts in store for the jolly season

" + * } + */ +export interface UpdateInternalArticleRequestBody { + /** The unique identifier for the internal article which is given by Intercom. */ + id: number; + /** The title of the article. */ + title?: string; + /** The content of the article. */ + body?: string; + /** The id of the author of the article. */ + author_id?: number; + /** The id of the author of the article. */ + owner_id?: number; +} diff --git a/src/api/resources/unstable/resources/internalArticles/client/requests/index.ts b/src/api/resources/unstable/resources/internalArticles/client/requests/index.ts new file mode 100644 index 00000000..677bd9fa --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/client/requests/index.ts @@ -0,0 +1,4 @@ +export type { DeleteInternalArticleRequest } from "./DeleteInternalArticleRequest.js"; +export type { RetrieveInternalArticleRequest } from "./RetrieveInternalArticleRequest.js"; +export type { SearchInternalArticlesRequest } from "./SearchInternalArticlesRequest.js"; +export type { UpdateInternalArticleRequestBody } from "./UpdateInternalArticleRequestBody.js"; diff --git a/src/api/resources/unstable/resources/internalArticles/index.ts b/src/api/resources/unstable/resources/internalArticles/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/internalArticles/types/InternalArticleListItem.ts b/src/api/resources/unstable/resources/internalArticles/types/InternalArticleListItem.ts new file mode 100644 index 00000000..b906ff6f --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/types/InternalArticleListItem.ts @@ -0,0 +1,25 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * The data returned about your internal articles when you list them. + */ +export interface InternalArticleListItem { + /** The type of object - `internal_article`. */ + type?: "internal_article"; + /** The unique identifier for the article which is given by Intercom. */ + id?: string; + /** The title of the article. */ + title?: string; + /** The body of the article in HTML. */ + body?: string; + /** The id of the owner of the article. */ + owner_id?: number; + /** The id of the author of the article. */ + author_id?: number; + /** The time when the article was created. */ + created_at?: number; + /** The time when the article was last updated. */ + updated_at?: number; + /** The default locale of the article. */ + locale?: string; +} diff --git a/src/api/resources/unstable/resources/internalArticles/types/InternalArticleSearchResponse.ts b/src/api/resources/unstable/resources/internalArticles/types/InternalArticleSearchResponse.ts new file mode 100644 index 00000000..b7790005 --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/types/InternalArticleSearchResponse.ts @@ -0,0 +1,26 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * The results of an Internal Article search + */ +export interface InternalArticleSearchResponse { + /** The type of the object - `list`. */ + type?: "list"; + /** The total number of Internal Articles matching the search query */ + total_count?: number; + /** An object containing the results of the search. */ + data?: InternalArticleSearchResponse.Data; + pages?: Intercom.unstable.CursorPages; +} + +export namespace InternalArticleSearchResponse { + /** + * An object containing the results of the search. + */ + export interface Data { + /** An array of Internal Article objects */ + internal_articles?: Intercom.unstable.InternalArticle[]; + } +} diff --git a/src/api/resources/unstable/resources/internalArticles/types/index.ts b/src/api/resources/unstable/resources/internalArticles/types/index.ts new file mode 100644 index 00000000..aedeb96e --- /dev/null +++ b/src/api/resources/unstable/resources/internalArticles/types/index.ts @@ -0,0 +1,2 @@ +export * from "./InternalArticleListItem.js"; +export * from "./InternalArticleSearchResponse.js"; diff --git a/src/api/resources/unstable/resources/jobs/client/Client.ts b/src/api/resources/unstable/resources/jobs/client/Client.ts index 3c114bdf..232af1bd 100644 --- a/src/api/resources/unstable/resources/jobs/client/Client.ts +++ b/src/api/resources/unstable/resources/jobs/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Jobs { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace JobsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about jobs */ -export class Jobs { - constructor(protected readonly _options: Jobs.Options = {}) {} +export class JobsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: JobsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * Retrieve the status of job execution. * * @param {Intercom.unstable.JobsStatusRequest} request - * @param {Jobs.RequestOptions} requestOptions - Request-specific configuration. + * @param {JobsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -91,40 +41,38 @@ export class Jobs { */ public status( request: Intercom.unstable.JobsStatusRequest, - requestOptions?: Jobs.RequestOptions, + requestOptions?: JobsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__status(request, requestOptions)); } private async __status( request: Intercom.unstable.JobsStatusRequest, - requestOptions?: Jobs.RequestOptions, + requestOptions?: JobsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `jobs/status/${encodeURIComponent(id)}`, + `jobs/status/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Jobs, rawResponse: _response.rawResponse }; @@ -148,32 +96,6 @@ export class Jobs { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /jobs/status/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/jobs/status/{id}"); } } diff --git a/src/api/resources/unstable/resources/jobs/client/index.ts b/src/api/resources/unstable/resources/jobs/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/jobs/client/index.ts +++ b/src/api/resources/unstable/resources/jobs/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/jobs/client/requests/JobsStatusRequest.ts b/src/api/resources/unstable/resources/jobs/client/requests/JobsStatusRequest.ts index 861e1c7d..80f53a81 100644 --- a/src/api/resources/unstable/resources/jobs/client/requests/JobsStatusRequest.ts +++ b/src/api/resources/unstable/resources/jobs/client/requests/JobsStatusRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface JobsStatusRequest { - /** - * The unique identifier for the job which is given by Intercom - */ + /** The unique identifier for the job which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/jobs/client/requests/index.ts b/src/api/resources/unstable/resources/jobs/client/requests/index.ts index 0d9f97d0..bfed16f9 100644 --- a/src/api/resources/unstable/resources/jobs/client/requests/index.ts +++ b/src/api/resources/unstable/resources/jobs/client/requests/index.ts @@ -1 +1 @@ -export { type JobsStatusRequest } from "./JobsStatusRequest"; +export type { JobsStatusRequest } from "./JobsStatusRequest.js"; diff --git a/src/api/resources/unstable/resources/jobs/index.ts b/src/api/resources/unstable/resources/jobs/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/jobs/index.ts +++ b/src/api/resources/unstable/resources/jobs/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/jobs/types/Jobs.ts b/src/api/resources/unstable/resources/jobs/types/Jobs.ts index e2192f11..c3e63585 100644 --- a/src/api/resources/unstable/resources/jobs/types/Jobs.ts +++ b/src/api/resources/unstable/resources/jobs/types/Jobs.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Jobs are tasks that are processed asynchronously by the Intercom system after being enqueued via the API. This allows for efficient handling of operations that may take time to complete, such as data imports or exports. You can check the status of your jobs to monitor their progress and ensure they are completed successfully. @@ -23,13 +21,11 @@ export interface Jobs { } export namespace Jobs { - /** - * The status of the job execution. - */ - export type Status = "pending" | "success" | "failed"; + /** The status of the job execution. */ export const Status = { Pending: "pending", Success: "success", Failed: "failed", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } diff --git a/src/api/resources/unstable/resources/jobs/types/index.ts b/src/api/resources/unstable/resources/jobs/types/index.ts index c46ba3db..c4ca9992 100644 --- a/src/api/resources/unstable/resources/jobs/types/index.ts +++ b/src/api/resources/unstable/resources/jobs/types/index.ts @@ -1 +1 @@ -export * from "./Jobs"; +export * from "./Jobs.js"; diff --git a/src/api/resources/unstable/resources/macros/client/Client.ts b/src/api/resources/unstable/resources/macros/client/Client.ts new file mode 100644 index 00000000..60a0a207 --- /dev/null +++ b/src/api/resources/unstable/resources/macros/client/Client.ts @@ -0,0 +1,230 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; + +export declare namespace MacrosClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} +} + +/** + * Operations related to saved replies (macros) in conversations + */ +export class MacrosClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: MacrosClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can fetch a list of all macros (saved replies) in your workspace for use in automating responses. + * + * The macros are returned in descending order by updated_at. + * + * **Pagination** + * + * This endpoint uses cursor-based pagination via the `starting_after` parameter. The cursor is a Base64-encoded JSON array containing `[updated_at, id]` of the last item from the previous page. + * + * **Placeholder Transformation** + * + * The API transforms Intercom placeholders to a more standard XML-like format: + * - From: `{{user.name | fallback: 'there'}}` + * - To: `` + * + * @param {Intercom.unstable.ListMacrosRequest} request + * @param {MacrosClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.BadRequestError} + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.ForbiddenError} + * + * @example + * await client.unstable.macros.listMacros({ + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * }) + */ + public listMacros( + request: Intercom.unstable.ListMacrosRequest = {}, + requestOptions?: MacrosClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listMacros(request, requestOptions)); + } + + private async __listMacros( + request: Intercom.unstable.ListMacrosRequest = {}, + requestOptions?: MacrosClient.RequestOptions, + ): Promise> { + const { per_page: perPage, starting_after: startingAfter, updated_since: updatedSince } = request; + const _queryParams: Record = {}; + if (perPage != null) { + _queryParams.per_page = perPage.toString(); + } + + if (startingAfter != null) { + _queryParams.starting_after = startingAfter; + } + + if (updatedSince != null) { + _queryParams.updated_since = updatedSince.toString(); + } + + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + "macros", + ), + method: "GET", + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.MacroList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new Intercom.unstable.BadRequestError(_response.error.body as unknown, _response.rawResponse); + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 403: + throw new Intercom.unstable.ForbiddenError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/macros"); + } + + /** + * You can fetch a single macro (saved reply) by its ID. The macro will only be returned if it is visible to the authenticated user based on its visibility settings. + * + * **Visibility Rules** + * + * A macro is returned based on its `visible_to` setting: + * - `everyone`: Always visible to all team members + * - `specific_teams`: Only visible if the authenticated user belongs to one of the teams specified in `visible_to_team_ids` + * + * If a macro exists but is not visible to the authenticated user, a 404 error is returned. + * + * **Placeholder Transformation** + * + * The API transforms Intercom placeholders to a more standard XML-like format in the `body` field: + * - From: `{{user.name | fallback: 'there'}}` + * - To: `` + * + * Default values in placeholders are HTML-escaped for security. + * + * @param {Intercom.unstable.GetMacroRequest} request + * @param {MacrosClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.UnauthorizedError} + * @throws {@link Intercom.unstable.ForbiddenError} + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.macros.getMacro({ + * id: "123" + * }) + */ + public getMacro( + request: Intercom.unstable.GetMacroRequest, + requestOptions?: MacrosClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getMacro(request, requestOptions)); + } + + private async __getMacro( + request: Intercom.unstable.GetMacroRequest, + requestOptions?: MacrosClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `macros/${core.url.encodePathParam(id)}`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.Macro | undefined, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 401: + throw new Intercom.unstable.UnauthorizedError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 403: + throw new Intercom.unstable.ForbiddenError( + _response.error.body as Intercom.unstable.Error_, + _response.rawResponse, + ); + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/macros/{id}"); + } +} diff --git a/src/api/resources/unstable/resources/macros/client/index.ts b/src/api/resources/unstable/resources/macros/client/index.ts new file mode 100644 index 00000000..195f9aa8 --- /dev/null +++ b/src/api/resources/unstable/resources/macros/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/macros/client/requests/GetMacroRequest.ts b/src/api/resources/unstable/resources/macros/client/requests/GetMacroRequest.ts new file mode 100644 index 00000000..a90a0866 --- /dev/null +++ b/src/api/resources/unstable/resources/macros/client/requests/GetMacroRequest.ts @@ -0,0 +1,27 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "123" + * } + * + * @example + * { + * id: "123" + * } + * + * @example + * { + * id: "123" + * } + * + * @example + * { + * id: "123" + * } + */ +export interface GetMacroRequest { + /** The unique identifier of the macro */ + id: string; +} diff --git a/src/api/resources/unstable/resources/macros/client/requests/ListMacrosRequest.ts b/src/api/resources/unstable/resources/macros/client/requests/ListMacrosRequest.ts new file mode 100644 index 00000000..caf7ed0d --- /dev/null +++ b/src/api/resources/unstable/resources/macros/client/requests/ListMacrosRequest.ts @@ -0,0 +1,53 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + * + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + * + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + * + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + * + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + * + * @example + * { + * per_page: 1, + * starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + * updated_since: 1000000 + * } + */ +export interface ListMacrosRequest { + /** The number of results per page */ + per_page?: number; + /** Base64-encoded cursor containing [updated_at, id] for pagination */ + starting_after?: string; + /** Unix timestamp to filter macros updated after this time */ + updated_since?: number; +} diff --git a/src/api/resources/unstable/resources/macros/client/requests/index.ts b/src/api/resources/unstable/resources/macros/client/requests/index.ts new file mode 100644 index 00000000..10c97f9d --- /dev/null +++ b/src/api/resources/unstable/resources/macros/client/requests/index.ts @@ -0,0 +1,2 @@ +export type { GetMacroRequest } from "./GetMacroRequest.js"; +export type { ListMacrosRequest } from "./ListMacrosRequest.js"; diff --git a/src/api/resources/unstable/resources/macros/index.ts b/src/api/resources/unstable/resources/macros/index.ts new file mode 100644 index 00000000..d9adb1af --- /dev/null +++ b/src/api/resources/unstable/resources/macros/index.ts @@ -0,0 +1,2 @@ +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/macros/types/Macro.ts b/src/api/resources/unstable/resources/macros/types/Macro.ts new file mode 100644 index 00000000..b7941f1a --- /dev/null +++ b/src/api/resources/unstable/resources/macros/types/Macro.ts @@ -0,0 +1,45 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * A macro is a pre-defined response template (saved reply) that can be used to quickly reply to conversations. + */ +export interface Macro { + /** String representing the object's type. Always has the value `macro`. */ + type?: "macro"; + /** The unique identifier for the macro. */ + id?: string; + /** The name of the macro. */ + name?: string; + /** The body of the macro in HTML format with placeholders transformed to XML-like format. */ + body?: string; + /** The plain text version of the macro body with original Intercom placeholder format. */ + body_text?: string; + /** The time the macro was created in ISO 8601 format. */ + created_at?: string; + /** The time the macro was last updated in ISO 8601 format. */ + updated_at?: string; + /** Who can view this macro. */ + visible_to?: Macro.VisibleTo; + /** The team IDs that can view this macro when visible_to is set to specific_teams. */ + visible_to_team_ids?: string[]; + /** Where the macro is available for use. */ + available_on?: Macro.AvailableOn.Item[]; +} + +export namespace Macro { + /** Who can view this macro. */ + export const VisibleTo = { + Everyone: "everyone", + SpecificTeams: "specific_teams", + } as const; + export type VisibleTo = (typeof VisibleTo)[keyof typeof VisibleTo]; + export type AvailableOn = AvailableOn.Item[]; + + export namespace AvailableOn { + export const Item = { + Inbox: "inbox", + Messenger: "messenger", + } as const; + export type Item = (typeof Item)[keyof typeof Item]; + } +} diff --git a/src/api/resources/unstable/resources/macros/types/MacroList.ts b/src/api/resources/unstable/resources/macros/types/MacroList.ts new file mode 100644 index 00000000..0694b02f --- /dev/null +++ b/src/api/resources/unstable/resources/macros/types/MacroList.ts @@ -0,0 +1,39 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * A paginated list of macros (saved replies) in the workspace. + */ +export interface MacroList { + /** Always list */ + type?: "list"; + /** The list of macro objects */ + data?: (Intercom.unstable.Macro | undefined)[]; + /** Pagination information */ + pages?: MacroList.Pages; +} + +export namespace MacroList { + /** + * Pagination information + */ + export interface Pages { + /** The type of pagination */ + type?: "pages"; + /** Number of results per page */ + per_page?: number; + /** Cursor for the next page */ + next?: Pages.Next; + } + + export namespace Pages { + /** + * Cursor for the next page + */ + export interface Next { + /** Base64-encoded cursor containing [updated_at, id] for pagination */ + starting_after?: string; + } + } +} diff --git a/src/api/resources/unstable/resources/macros/types/index.ts b/src/api/resources/unstable/resources/macros/types/index.ts new file mode 100644 index 00000000..46516f7b --- /dev/null +++ b/src/api/resources/unstable/resources/macros/types/index.ts @@ -0,0 +1,2 @@ +export * from "./Macro.js"; +export * from "./MacroList.js"; diff --git a/src/api/resources/unstable/resources/messages/client/Client.ts b/src/api/resources/unstable/resources/messages/client/Client.ts index e49625bc..95d1513f 100644 --- a/src/api/resources/unstable/resources/messages/client/Client.ts +++ b/src/api/resources/unstable/resources/messages/client/Client.ts @@ -1,82 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Messages { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace MessagesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your messages */ -export class Messages { - constructor(protected readonly _options: Messages.Options = {}) {} +export class MessagesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: MessagesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** - * You can create a message that has been initiated by an admin. The conversation can be either an in-app message, an email or sms. + * You can create a message that has been initiated by an admin. The conversation can be either an in-app message, an email, sms or whatsapp. * * > 🚧 Sending for visitors * > @@ -88,8 +38,8 @@ export class Messages { * > * > As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message. * - * @param {Intercom.CreateMessageRequestTwo} request - * @param {Messages.RequestOptions} requestOptions - Request-specific configuration. + * @param {Intercom.unstable.CreateMessageRequest | undefined} request + * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -174,6 +124,32 @@ export class Messages { * await client.unstable.messages.createMessage({ * "from": { * "type": "admin", + * "id": "991267817" + * }, + * "to": { + * "phone": 5547999998888, + * "name": "John Doe" + * }, + * "message_type": "whatsapp", + * "components": [ + * { + * "type": "BODY", + * "parameters": [ + * { + * "type": "text", + * "text": "Username 123" + * } + * ] + * } + * ], + * "template": "keep_live", + * "locale": "en" + * }) + * + * @example + * await client.unstable.messages.createMessage({ + * "from": { + * "type": "admin", * "id": "991267818" * }, * "to": { @@ -227,41 +203,41 @@ export class Messages { * }) */ public createMessage( - request?: Intercom.CreateMessageRequestTwo, - requestOptions?: Messages.RequestOptions, + request?: Intercom.unstable.CreateMessageRequest | undefined, + requestOptions?: MessagesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createMessage(request, requestOptions)); } private async __createMessage( - request?: Intercom.CreateMessageRequestTwo, - requestOptions?: Messages.RequestOptions, + request?: Intercom.unstable.CreateMessageRequest | undefined, + requestOptions?: MessagesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "messages", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", - body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + body: request != null ? request : undefined, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Message, rawResponse: _response.rawResponse }; @@ -295,21 +271,7 @@ export class Messages { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /messages."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/messages"); } /** @@ -320,7 +282,7 @@ export class Messages { * information about delivery state and related message details. * * @param {Intercom.unstable.GetWhatsAppMessageStatusRequest} request - * @param {Messages.RequestOptions} requestOptions - Request-specific configuration. + * @param {MessagesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -329,56 +291,55 @@ export class Messages { * * @example * await client.unstable.messages.getWhatsAppMessageStatus({ - * ruleset_id: "ruleset_id" + * ruleset_id: "ruleset_id", + * per_page: 1, + * starting_after: "starting_after" * }) */ public getWhatsAppMessageStatus( request: Intercom.unstable.GetWhatsAppMessageStatusRequest, - requestOptions?: Messages.RequestOptions, + requestOptions?: MessagesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getWhatsAppMessageStatus(request, requestOptions)); } private async __getWhatsAppMessageStatus( request: Intercom.unstable.GetWhatsAppMessageStatusRequest, - requestOptions?: Messages.RequestOptions, + requestOptions?: MessagesClient.RequestOptions, ): Promise> { const { ruleset_id: rulesetId, per_page: perPage, starting_after: startingAfter } = request; const _queryParams: Record = {}; - _queryParams["ruleset_id"] = rulesetId; + _queryParams.ruleset_id = rulesetId; if (perPage != null) { - _queryParams["per_page"] = perPage.toString(); + _queryParams.per_page = perPage.toString(); } if (startingAfter != null) { - _queryParams["starting_after"] = startingAfter; + _queryParams.starting_after = startingAfter; } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "messages/status", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -415,32 +376,6 @@ export class Messages { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /messages/status."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/messages/status"); } } diff --git a/src/api/resources/unstable/resources/messages/client/index.ts b/src/api/resources/unstable/resources/messages/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/messages/client/index.ts +++ b/src/api/resources/unstable/resources/messages/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/messages/client/requests/GetWhatsAppMessageStatusRequest.ts b/src/api/resources/unstable/resources/messages/client/requests/GetWhatsAppMessageStatusRequest.ts index 9f14d703..4857f1ff 100644 --- a/src/api/resources/unstable/resources/messages/client/requests/GetWhatsAppMessageStatusRequest.ts +++ b/src/api/resources/unstable/resources/messages/client/requests/GetWhatsAppMessageStatusRequest.ts @@ -1,24 +1,18 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example * { - * ruleset_id: "ruleset_id" + * ruleset_id: "ruleset_id", + * per_page: 1, + * starting_after: "starting_after" * } */ export interface GetWhatsAppMessageStatusRequest { - /** - * The unique identifier for the set of messages to check status for - */ + /** The unique identifier for the set of messages to check status for */ ruleset_id: string; - /** - * Number of results per page (default 50, max 100) - */ + /** Number of results per page (default 50, max 100) */ per_page?: number; - /** - * Cursor for pagination, used to fetch the next page of results - */ + /** Cursor for pagination, used to fetch the next page of results */ starting_after?: string; } diff --git a/src/api/resources/unstable/resources/messages/client/requests/index.ts b/src/api/resources/unstable/resources/messages/client/requests/index.ts index 73c16159..3571c87e 100644 --- a/src/api/resources/unstable/resources/messages/client/requests/index.ts +++ b/src/api/resources/unstable/resources/messages/client/requests/index.ts @@ -1 +1 @@ -export { type GetWhatsAppMessageStatusRequest } from "./GetWhatsAppMessageStatusRequest"; +export type { GetWhatsAppMessageStatusRequest } from "./GetWhatsAppMessageStatusRequest.js"; diff --git a/src/api/resources/unstable/resources/messages/index.ts b/src/api/resources/unstable/resources/messages/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/messages/index.ts +++ b/src/api/resources/unstable/resources/messages/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/messages/types/Message.ts b/src/api/resources/unstable/resources/messages/types/Message.ts index 35585c59..14710453 100644 --- a/src/api/resources/unstable/resources/messages/types/Message.ts +++ b/src/api/resources/unstable/resources/messages/types/Message.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Message are how you reach out to contacts in Intercom. They are created when an admin sends an outbound message to a contact. @@ -16,22 +14,21 @@ export interface Message { subject?: string; /** The message body, which may contain HTML. */ body: string; - /** The type of message that was sent. Can be email, inapp, facebook ,twitter or sms. */ + /** The type of message that was sent. Can be email, inapp, facebook, twitter, sms or whatsapp. */ message_type: Message.MessageType; /** The associated conversation_id */ conversation_id?: string; } export namespace Message { - /** - * The type of message that was sent. Can be email, inapp, facebook ,twitter or sms. - */ - export type MessageType = "email" | "inapp" | "facebook" | "twitter" | "sms"; + /** The type of message that was sent. Can be email, inapp, facebook, twitter, sms or whatsapp. */ export const MessageType = { Email: "email", Inapp: "inapp", Facebook: "facebook", Twitter: "twitter", Sms: "sms", + Whatsapp: "whatsapp", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; } diff --git a/src/api/resources/unstable/resources/messages/types/index.ts b/src/api/resources/unstable/resources/messages/types/index.ts index 6596816a..e16d36b7 100644 --- a/src/api/resources/unstable/resources/messages/types/index.ts +++ b/src/api/resources/unstable/resources/messages/types/index.ts @@ -1 +1 @@ -export * from "./Message"; +export * from "./Message.js"; diff --git a/src/api/resources/unstable/resources/news/client/Client.ts b/src/api/resources/unstable/resources/news/client/Client.ts index f42e1729..a0463196 100644 --- a/src/api/resources/unstable/resources/news/client/Client.ts +++ b/src/api/resources/unstable/resources/news/client/Client.ts @@ -1,84 +1,34 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; - -export declare namespace News { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } +export declare namespace NewsClient { + export interface Options extends BaseClientOptions {} + + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your News */ -export class News { - constructor(protected readonly _options: News.Options = {}) {} +export class NewsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: NewsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all news items * - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -86,38 +36,36 @@ export class News { * await client.unstable.news.listNewsItems() */ public listNewsItems( - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listNewsItems(requestOptions)); } private async __listNewsItems( - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/news_items", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.PaginatedResponse, rawResponse: _response.rawResponse }; @@ -139,28 +87,14 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/news_items."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/news_items"); } /** * You can create a news item * * @param {Intercom.unstable.NewsItemRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -181,40 +115,40 @@ export class News { */ public createNewsItem( request: Intercom.unstable.NewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createNewsItem(request, requestOptions)); } private async __createNewsItem( request: Intercom.unstable.NewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/news_items", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.NewsItem, rawResponse: _response.rawResponse }; @@ -236,28 +170,14 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /news/news_items."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/news/news_items"); } /** * You can fetch the details of a single news item. * * @param {Intercom.unstable.RetrieveNewsItemRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -269,40 +189,38 @@ export class News { */ public retrieveNewsItem( request: Intercom.unstable.RetrieveNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveNewsItem(request, requestOptions)); } private async __retrieveNewsItem( request: Intercom.unstable.RetrieveNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(id)}`, + `news/news_items/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.NewsItem, rawResponse: _response.rawResponse }; @@ -326,26 +244,12 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/news_items/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/news_items/{id}"); } /** * @param {Intercom.unstable.UpdateNewsItemRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -374,41 +278,41 @@ export class News { */ public updateNewsItem( request: Intercom.unstable.UpdateNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateNewsItem(request, requestOptions)); } private async __updateNewsItem( request: Intercom.unstable.UpdateNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { const { id, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(id)}`, + `news/news_items/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.NewsItem, rawResponse: _response.rawResponse }; @@ -432,28 +336,14 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /news/news_items/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/news/news_items/{id}"); } /** * You can delete a single news item. * * @param {Intercom.unstable.DeleteNewsItemRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -465,40 +355,38 @@ export class News { */ public deleteNewsItem( request: Intercom.unstable.DeleteNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteNewsItem(request, requestOptions)); } private async __deleteNewsItem( request: Intercom.unstable.DeleteNewsItemRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/news_items/${encodeURIComponent(id)}`, + `news/news_items/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.DeletedObject, rawResponse: _response.rawResponse }; @@ -522,28 +410,14 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /news/news_items/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/news/news_items/{id}"); } /** * You can fetch a list of all news items that are live on a given newsfeed * * @param {Intercom.unstable.ListLiveNewsfeedItemsRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -554,40 +428,38 @@ export class News { */ public listLiveNewsfeedItems( request: Intercom.unstable.ListLiveNewsfeedItemsRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listLiveNewsfeedItems(request, requestOptions)); } private async __listLiveNewsfeedItems( request: Intercom.unstable.ListLiveNewsfeedItemsRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/newsfeeds/${encodeURIComponent(id)}/items`, + `news/newsfeeds/${core.url.encodePathParam(id)}/items`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.PaginatedResponse, rawResponse: _response.rawResponse }; @@ -609,27 +481,13 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/newsfeeds/{id}/items."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/newsfeeds/{id}/items"); } /** * You can fetch a list of all newsfeeds * - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -637,38 +495,36 @@ export class News { * await client.unstable.news.listNewsfeeds() */ public listNewsfeeds( - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listNewsfeeds(requestOptions)); } private async __listNewsfeeds( - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "news/newsfeeds", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.PaginatedResponse, rawResponse: _response.rawResponse }; @@ -690,28 +546,14 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/newsfeeds."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/newsfeeds"); } /** * You can fetch the details of a single newsfeed * * @param {Intercom.unstable.RetrieveNewsfeedRequest} request - * @param {News.RequestOptions} requestOptions - Request-specific configuration. + * @param {NewsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -722,40 +564,38 @@ export class News { */ public retrieveNewsfeed( request: Intercom.unstable.RetrieveNewsfeedRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveNewsfeed(request, requestOptions)); } private async __retrieveNewsfeed( request: Intercom.unstable.RetrieveNewsfeedRequest, - requestOptions?: News.RequestOptions, + requestOptions?: NewsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `news/newsfeeds/${encodeURIComponent(id)}`, + `news/newsfeeds/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Newsfeed, rawResponse: _response.rawResponse }; @@ -777,32 +617,6 @@ export class News { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /news/newsfeeds/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/news/newsfeeds/{id}"); } } diff --git a/src/api/resources/unstable/resources/news/client/index.ts b/src/api/resources/unstable/resources/news/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/news/client/index.ts +++ b/src/api/resources/unstable/resources/news/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/news/client/requests/DeleteNewsItemRequest.ts b/src/api/resources/unstable/resources/news/client/requests/DeleteNewsItemRequest.ts index 5edfca2a..e78e359e 100644 --- a/src/api/resources/unstable/resources/news/client/requests/DeleteNewsItemRequest.ts +++ b/src/api/resources/unstable/resources/news/client/requests/DeleteNewsItemRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ + /** The unique identifier for the news item which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/news/client/requests/ListLiveNewsfeedItemsRequest.ts b/src/api/resources/unstable/resources/news/client/requests/ListLiveNewsfeedItemsRequest.ts index 4101909c..80431667 100644 --- a/src/api/resources/unstable/resources/news/client/requests/ListLiveNewsfeedItemsRequest.ts +++ b/src/api/resources/unstable/resources/news/client/requests/ListLiveNewsfeedItemsRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListLiveNewsfeedItemsRequest { - /** - * The unique identifier for the news feed item which is given by Intercom. - */ + /** The unique identifier for the news feed item which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsItemRequest.ts b/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsItemRequest.ts index b2e33231..4c61a48f 100644 --- a/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsItemRequest.ts +++ b/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsItemRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ + /** The unique identifier for the news item which is given by Intercom. */ id: number; } diff --git a/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsfeedRequest.ts b/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsfeedRequest.ts index a4d0663a..d7162aaa 100644 --- a/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsfeedRequest.ts +++ b/src/api/resources/unstable/resources/news/client/requests/RetrieveNewsfeedRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveNewsfeedRequest { - /** - * The unique identifier for the news feed item which is given by Intercom. - */ + /** The unique identifier for the news feed item which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/news/client/requests/UpdateNewsItemRequest.ts b/src/api/resources/unstable/resources/news/client/requests/UpdateNewsItemRequest.ts index e0962588..8c96cdfa 100644 --- a/src/api/resources/unstable/resources/news/client/requests/UpdateNewsItemRequest.ts +++ b/src/api/resources/unstable/resources/news/client/requests/UpdateNewsItemRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example @@ -28,9 +26,7 @@ import * as Intercom from "../../../../../../index"; * } */ export interface UpdateNewsItemRequest { - /** - * The unique identifier for the news item which is given by Intercom. - */ + /** The unique identifier for the news item which is given by Intercom. */ id: number; body: Intercom.unstable.NewsItemRequest; } diff --git a/src/api/resources/unstable/resources/news/client/requests/index.ts b/src/api/resources/unstable/resources/news/client/requests/index.ts index 94944125..d5c9a5f5 100644 --- a/src/api/resources/unstable/resources/news/client/requests/index.ts +++ b/src/api/resources/unstable/resources/news/client/requests/index.ts @@ -1,5 +1,5 @@ -export { type RetrieveNewsItemRequest } from "./RetrieveNewsItemRequest"; -export { type UpdateNewsItemRequest } from "./UpdateNewsItemRequest"; -export { type DeleteNewsItemRequest } from "./DeleteNewsItemRequest"; -export { type ListLiveNewsfeedItemsRequest } from "./ListLiveNewsfeedItemsRequest"; -export { type RetrieveNewsfeedRequest } from "./RetrieveNewsfeedRequest"; +export type { DeleteNewsItemRequest } from "./DeleteNewsItemRequest.js"; +export type { ListLiveNewsfeedItemsRequest } from "./ListLiveNewsfeedItemsRequest.js"; +export type { RetrieveNewsfeedRequest } from "./RetrieveNewsfeedRequest.js"; +export type { RetrieveNewsItemRequest } from "./RetrieveNewsItemRequest.js"; +export type { UpdateNewsItemRequest } from "./UpdateNewsItemRequest.js"; diff --git a/src/api/resources/unstable/resources/news/index.ts b/src/api/resources/unstable/resources/news/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/news/index.ts +++ b/src/api/resources/unstable/resources/news/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/news/types/NewsItem.ts b/src/api/resources/unstable/resources/news/types/NewsItem.ts index 6650f0c5..a5ecc130 100644 --- a/src/api/resources/unstable/resources/news/types/NewsItem.ts +++ b/src/api/resources/unstable/resources/news/types/NewsItem.ts @@ -1,13 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A News Item is a content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers. */ export interface NewsItem { + /** The type of object. */ + type?: "news-item"; /** The unique identifier for the news item which is given by Intercom. */ id?: string; /** The id of the workspace which the news item belongs to. */ @@ -37,12 +37,10 @@ export interface NewsItem { } export namespace NewsItem { - /** - * News items will not be visible to your users in the assigned newsfeeds until they are set live. - */ - export type State = "draft" | "live"; + /** News items will not be visible to your users in the assigned newsfeeds until they are set live. */ export const State = { Draft: "draft", Live: "live", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/resources/news/types/Newsfeed.ts b/src/api/resources/unstable/resources/news/types/Newsfeed.ts index 10dc3a1f..a42f6306 100644 --- a/src/api/resources/unstable/resources/news/types/Newsfeed.ts +++ b/src/api/resources/unstable/resources/news/types/Newsfeed.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A newsfeed is a collection of news items, targeted to a specific audience. @@ -10,6 +8,8 @@ export interface Newsfeed { /** The unique identifier for the newsfeed which is given by Intercom. */ id?: string; + /** The type of object. */ + type?: "newsfeed"; /** The name of the newsfeed. This name will never be visible to your users. */ name?: string; /** Timestamp for when the newsfeed was created. */ diff --git a/src/api/resources/unstable/resources/news/types/NewsfeedAssignment.ts b/src/api/resources/unstable/resources/news/types/NewsfeedAssignment.ts index 2eb97d45..064483c9 100644 --- a/src/api/resources/unstable/resources/news/types/NewsfeedAssignment.ts +++ b/src/api/resources/unstable/resources/news/types/NewsfeedAssignment.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Assigns a news item to a newsfeed. diff --git a/src/api/resources/unstable/resources/news/types/index.ts b/src/api/resources/unstable/resources/news/types/index.ts index b8c22f3c..fe7a29c8 100644 --- a/src/api/resources/unstable/resources/news/types/index.ts +++ b/src/api/resources/unstable/resources/news/types/index.ts @@ -1,3 +1,3 @@ -export * from "./NewsItem"; -export * from "./Newsfeed"; -export * from "./NewsfeedAssignment"; +export * from "./Newsfeed.js"; +export * from "./NewsfeedAssignment.js"; +export * from "./NewsItem.js"; diff --git a/src/api/resources/unstable/resources/notes/client/Client.ts b/src/api/resources/unstable/resources/notes/client/Client.ts index b82d5191..6daafede 100644 --- a/src/api/resources/unstable/resources/notes/client/Client.ts +++ b/src/api/resources/unstable/resources/notes/client/Client.ts @@ -1,85 +1,103 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Notes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace NotesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Notes */ -export class Notes { - constructor(protected readonly _options: Notes.Options = {}) {} +export class NotesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: NotesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * You can fetch a list of notes that are associated to a company. + * + * @param {Intercom.unstable.ListCompanyNotesRequest} request + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link Intercom.unstable.NotFoundError} + * + * @example + * await client.unstable.notes.listCompanyNotes({ + * id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" + * }) + */ + public listCompanyNotes( + request: Intercom.unstable.ListCompanyNotesRequest, + requestOptions?: NotesClient.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listCompanyNotes(request, requestOptions)); + } + + private async __listCompanyNotes( + request: Intercom.unstable.ListCompanyNotesRequest, + requestOptions?: NotesClient.RequestOptions, + ): Promise> { + const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.IntercomEnvironment.UsProduction, + `companies/${core.url.encodePathParam(id)}/notes`, + ), + method: "GET", + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { data: _response.body as Intercom.unstable.NoteList, rawResponse: _response.rawResponse }; + } + + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 404: + throw new Intercom.unstable.NotFoundError(_response.error.body as unknown, _response.rawResponse); + default: + throw new errors.IntercomError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/companies/{id}/notes"); + } /** * You can fetch a list of notes that are associated to a contact. * * @param {Intercom.unstable.ListNotesRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.NotFoundError} * @@ -90,40 +108,38 @@ export class Notes { */ public listNotes( request: Intercom.unstable.ListNotesRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listNotes(request, requestOptions)); } private async __listNotes( request: Intercom.unstable.ListNotesRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/notes`, + `contacts/${core.url.encodePathParam(id)}/notes`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.NoteList, rawResponse: _response.rawResponse }; @@ -142,28 +158,14 @@ export class Notes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /contacts/{id}/notes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/contacts/{id}/notes"); } /** * You can add a note to a single contact. * * @param {Intercom.unstable.CreateNoteRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.NotFoundError} * @@ -193,41 +195,41 @@ export class Notes { */ public createNote( request: Intercom.unstable.CreateNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createNote(request, requestOptions)); } private async __createNote( request: Intercom.unstable.CreateNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(id)}/notes`, + `contacts/${core.url.encodePathParam(id)}/notes`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Note, rawResponse: _response.rawResponse }; @@ -246,28 +248,14 @@ export class Notes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /contacts/{id}/notes."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{id}/notes"); } /** * You can fetch the details of a single note. * * @param {Intercom.unstable.RetrieveNoteRequest} request - * @param {Notes.RequestOptions} requestOptions - Request-specific configuration. + * @param {NotesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -279,40 +267,38 @@ export class Notes { */ public retrieveNote( request: Intercom.unstable.RetrieveNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveNote(request, requestOptions)); } private async __retrieveNote( request: Intercom.unstable.RetrieveNoteRequest, - requestOptions?: Notes.RequestOptions, + requestOptions?: NotesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `notes/${encodeURIComponent(id)}`, + `notes/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Note, rawResponse: _response.rawResponse }; @@ -336,32 +322,6 @@ export class Notes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /notes/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/notes/{id}"); } } diff --git a/src/api/resources/unstable/resources/notes/client/index.ts b/src/api/resources/unstable/resources/notes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/notes/client/index.ts +++ b/src/api/resources/unstable/resources/notes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/notes/client/requests/CreateNoteRequest.ts b/src/api/resources/unstable/resources/notes/client/requests/CreateNoteRequest.ts index 8fe9c7ae..6802985e 100644 --- a/src/api/resources/unstable/resources/notes/client/requests/CreateNoteRequest.ts +++ b/src/api/resources/unstable/resources/notes/client/requests/CreateNoteRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -28,9 +26,7 @@ * } */ export interface CreateNoteRequest { - /** - * The unique identifier of a given contact. - */ + /** The unique identifier of a given contact. */ id: number; /** The text of the note. */ body: string; diff --git a/src/api/resources/unstable/resources/notes/client/requests/ListCompanyNotesRequest.ts b/src/api/resources/unstable/resources/notes/client/requests/ListCompanyNotesRequest.ts new file mode 100644 index 00000000..5e97337d --- /dev/null +++ b/src/api/resources/unstable/resources/notes/client/requests/ListCompanyNotesRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * { + * id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632" + * } + */ +export interface ListCompanyNotesRequest { + /** The unique identifier for the company which is given by Intercom */ + id: string; +} diff --git a/src/api/resources/unstable/resources/notes/client/requests/ListNotesRequest.ts b/src/api/resources/unstable/resources/notes/client/requests/ListNotesRequest.ts index 7d8052df..52dfe1b3 100644 --- a/src/api/resources/unstable/resources/notes/client/requests/ListNotesRequest.ts +++ b/src/api/resources/unstable/resources/notes/client/requests/ListNotesRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface ListNotesRequest { - /** - * The unique identifier of a contact. - */ + /** The unique identifier of a contact. */ id: number; } diff --git a/src/api/resources/unstable/resources/notes/client/requests/RetrieveNoteRequest.ts b/src/api/resources/unstable/resources/notes/client/requests/RetrieveNoteRequest.ts index 8fc83798..c6fe4988 100644 --- a/src/api/resources/unstable/resources/notes/client/requests/RetrieveNoteRequest.ts +++ b/src/api/resources/unstable/resources/notes/client/requests/RetrieveNoteRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveNoteRequest { - /** - * The unique identifier of a given note - */ + /** The unique identifier of a given note */ id: number; } diff --git a/src/api/resources/unstable/resources/notes/client/requests/index.ts b/src/api/resources/unstable/resources/notes/client/requests/index.ts index 4fa65001..ed230370 100644 --- a/src/api/resources/unstable/resources/notes/client/requests/index.ts +++ b/src/api/resources/unstable/resources/notes/client/requests/index.ts @@ -1,3 +1,4 @@ -export { type ListNotesRequest } from "./ListNotesRequest"; -export { type CreateNoteRequest } from "./CreateNoteRequest"; -export { type RetrieveNoteRequest } from "./RetrieveNoteRequest"; +export type { CreateNoteRequest } from "./CreateNoteRequest.js"; +export type { ListCompanyNotesRequest } from "./ListCompanyNotesRequest.js"; +export type { ListNotesRequest } from "./ListNotesRequest.js"; +export type { RetrieveNoteRequest } from "./RetrieveNoteRequest.js"; diff --git a/src/api/resources/unstable/resources/notes/index.ts b/src/api/resources/unstable/resources/notes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/notes/index.ts +++ b/src/api/resources/unstable/resources/notes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/notes/types/CompanyNote.ts b/src/api/resources/unstable/resources/notes/types/CompanyNote.ts new file mode 100644 index 00000000..d63295c5 --- /dev/null +++ b/src/api/resources/unstable/resources/notes/types/CompanyNote.ts @@ -0,0 +1,33 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../../../index.js"; + +/** + * Notes allow you to annotate and comment on companies. + */ +export interface CompanyNote { + /** String representing the object's type. Always has the value `note`. */ + type?: string; + /** The id of the note. */ + id?: string; + /** The time the note was created. */ + created_at?: number; + /** Represents the company that the note was created about. */ + company?: CompanyNote.Company; + /** Optional. Represents the Admin that created the note. */ + author?: Intercom.unstable.Admin; + /** The body text of the note. */ + body?: string; +} + +export namespace CompanyNote { + /** + * Represents the company that the note was created about. + */ + export interface Company { + /** String representing the object's type. Always has the value `company`. */ + type?: string; + /** The id of the company. */ + id?: string; + } +} diff --git a/src/api/resources/unstable/resources/notes/types/Note.ts b/src/api/resources/unstable/resources/notes/types/Note.ts index d4bc42b2..571bce49 100644 --- a/src/api/resources/unstable/resources/notes/types/Note.ts +++ b/src/api/resources/unstable/resources/notes/types/Note.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Notes allow you to annotate and comment on your contacts. diff --git a/src/api/resources/unstable/resources/notes/types/index.ts b/src/api/resources/unstable/resources/notes/types/index.ts index cf881fa5..0e6d3d17 100644 --- a/src/api/resources/unstable/resources/notes/types/index.ts +++ b/src/api/resources/unstable/resources/notes/types/index.ts @@ -1 +1,2 @@ -export * from "./Note"; +export * from "./CompanyNote.js"; +export * from "./Note.js"; diff --git a/src/api/resources/unstable/resources/segments/client/Client.ts b/src/api/resources/unstable/resources/segments/client/Client.ts index 67d08f1f..64d7c4fb 100644 --- a/src/api/resources/unstable/resources/segments/client/Client.ts +++ b/src/api/resources/unstable/resources/segments/client/Client.ts @@ -1,133 +1,82 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Segments { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace SegmentsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Segments */ -export class Segments { - constructor(protected readonly _options: Segments.Options = {}) {} +export class SegmentsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: SegmentsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch a list of all segments. * * @param {Intercom.unstable.ListSegmentsRequest} request - * @param {Segments.RequestOptions} requestOptions - Request-specific configuration. + * @param {SegmentsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example - * await client.unstable.segments.listSegments() + * await client.unstable.segments.listSegments({ + * include_count: true + * }) */ public listSegments( request: Intercom.unstable.ListSegmentsRequest = {}, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listSegments(request, requestOptions)); } private async __listSegments( request: Intercom.unstable.ListSegmentsRequest = {}, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): Promise> { const { include_count: includeCount } = request; const _queryParams: Record = {}; if (includeCount != null) { - _queryParams["include_count"] = includeCount.toString(); + _queryParams.include_count = includeCount.toString(); } + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "segments", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.SegmentList, rawResponse: _response.rawResponse }; @@ -149,28 +98,14 @@ export class Segments { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /segments."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/segments"); } /** * You can fetch the details of a single segment. * * @param {Intercom.unstable.RetrieveSegmentRequest} request - * @param {Segments.RequestOptions} requestOptions - Request-specific configuration. + * @param {SegmentsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -182,40 +117,38 @@ export class Segments { */ public retrieveSegment( request: Intercom.unstable.RetrieveSegmentRequest, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveSegment(request, requestOptions)); } private async __retrieveSegment( request: Intercom.unstable.RetrieveSegmentRequest, - requestOptions?: Segments.RequestOptions, + requestOptions?: SegmentsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `segments/${encodeURIComponent(id)}`, + `segments/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Segment, rawResponse: _response.rawResponse }; @@ -239,32 +172,6 @@ export class Segments { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /segments/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/segments/{id}"); } } diff --git a/src/api/resources/unstable/resources/segments/client/index.ts b/src/api/resources/unstable/resources/segments/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/segments/client/index.ts +++ b/src/api/resources/unstable/resources/segments/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/segments/client/requests/ListSegmentsRequest.ts b/src/api/resources/unstable/resources/segments/client/requests/ListSegmentsRequest.ts index 116acd5e..7554f000 100644 --- a/src/api/resources/unstable/resources/segments/client/requests/ListSegmentsRequest.ts +++ b/src/api/resources/unstable/resources/segments/client/requests/ListSegmentsRequest.ts @@ -1,14 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example - * {} + * { + * include_count: true + * } */ export interface ListSegmentsRequest { - /** - * It includes the count of contacts that belong to each segment. - */ + /** It includes the count of contacts that belong to each segment. */ include_count?: boolean; } diff --git a/src/api/resources/unstable/resources/segments/client/requests/RetrieveSegmentRequest.ts b/src/api/resources/unstable/resources/segments/client/requests/RetrieveSegmentRequest.ts index 0ba937bf..f7877c1e 100644 --- a/src/api/resources/unstable/resources/segments/client/requests/RetrieveSegmentRequest.ts +++ b/src/api/resources/unstable/resources/segments/client/requests/RetrieveSegmentRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveSegmentRequest { - /** - * The unique identified of a given segment. - */ + /** The unique identified of a given segment. */ id: string; } diff --git a/src/api/resources/unstable/resources/segments/client/requests/index.ts b/src/api/resources/unstable/resources/segments/client/requests/index.ts index d31998d0..3ef3b577 100644 --- a/src/api/resources/unstable/resources/segments/client/requests/index.ts +++ b/src/api/resources/unstable/resources/segments/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type ListSegmentsRequest } from "./ListSegmentsRequest"; -export { type RetrieveSegmentRequest } from "./RetrieveSegmentRequest"; +export type { ListSegmentsRequest } from "./ListSegmentsRequest.js"; +export type { RetrieveSegmentRequest } from "./RetrieveSegmentRequest.js"; diff --git a/src/api/resources/unstable/resources/segments/index.ts b/src/api/resources/unstable/resources/segments/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/segments/index.ts +++ b/src/api/resources/unstable/resources/segments/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/segments/types/Segment.ts b/src/api/resources/unstable/resources/segments/types/Segment.ts index b297f427..5fbb6b53 100644 --- a/src/api/resources/unstable/resources/segments/types/Segment.ts +++ b/src/api/resources/unstable/resources/segments/types/Segment.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A segment is a group of your contacts defined by the rules that you set. @@ -23,12 +21,10 @@ export interface Segment { } export namespace Segment { - /** - * Type of the contact: contact (lead) or user. - */ - export type PersonType = "contact" | "user"; + /** Type of the contact: contact (lead) or user. */ export const PersonType = { Contact: "contact", User: "user", } as const; + export type PersonType = (typeof PersonType)[keyof typeof PersonType]; } diff --git a/src/api/resources/unstable/resources/segments/types/index.ts b/src/api/resources/unstable/resources/segments/types/index.ts index 957aab14..a934b01a 100644 --- a/src/api/resources/unstable/resources/segments/types/index.ts +++ b/src/api/resources/unstable/resources/segments/types/index.ts @@ -1 +1 @@ -export * from "./Segment"; +export * from "./Segment.js"; diff --git a/src/api/resources/unstable/resources/subscriptionTypes/client/Client.ts b/src/api/resources/unstable/resources/subscriptionTypes/client/Client.ts index 38e70154..b43baf9e 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/client/Client.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace SubscriptionTypes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace SubscriptionTypesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about subscription types */ -export class SubscriptionTypes { - constructor(protected readonly _options: SubscriptionTypes.Options = {}) {} +export class SubscriptionTypesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: SubscriptionTypesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: @@ -85,7 +35,7 @@ export class SubscriptionTypes { * This will return a subscription type model for the subscription type that was added to the contact. * * @param {Intercom.unstable.AttachSubscriptionTypeToContactRequest} request - * @param {SubscriptionTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -106,41 +56,41 @@ export class SubscriptionTypes { */ public attachSubscriptionTypeToContact( request: Intercom.unstable.AttachSubscriptionTypeToContactRequest, - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachSubscriptionTypeToContact(request, requestOptions)); } private async __attachSubscriptionTypeToContact( request: Intercom.unstable.AttachSubscriptionTypeToContactRequest, - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.SubscriptionType, rawResponse: _response.rawResponse }; @@ -164,30 +114,19 @@ export class SubscriptionTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/subscriptions.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/contacts/{contact_id}/subscriptions", + ); } /** * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. * * @param {Intercom.unstable.DetachSubscriptionTypeToContactRequest} request - * @param {SubscriptionTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -200,40 +139,38 @@ export class SubscriptionTypes { */ public detachSubscriptionTypeToContact( request: Intercom.unstable.DetachSubscriptionTypeToContactRequest, - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachSubscriptionTypeToContact(request, requestOptions)); } private async __detachSubscriptionTypeToContact( request: Intercom.unstable.DetachSubscriptionTypeToContactRequest, - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): Promise> { const { contact_id: contactId, id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/subscriptions/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(contactId)}/subscriptions/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.SubscriptionType, rawResponse: _response.rawResponse }; @@ -257,29 +194,18 @@ export class SubscriptionTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/subscriptions/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/subscriptions/{id}", + ); } /** * You can list all subscription types. A list of subscription type objects will be returned. * - * @param {SubscriptionTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {SubscriptionTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -287,38 +213,36 @@ export class SubscriptionTypes { * await client.unstable.subscriptionTypes.listSubscriptionTypes() */ public listSubscriptionTypes( - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listSubscriptionTypes(requestOptions)); } private async __listSubscriptionTypes( - requestOptions?: SubscriptionTypes.RequestOptions, + requestOptions?: SubscriptionTypesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "subscription_types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -343,32 +267,6 @@ export class SubscriptionTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /subscription_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/subscription_types"); } } diff --git a/src/api/resources/unstable/resources/subscriptionTypes/client/index.ts b/src/api/resources/unstable/resources/subscriptionTypes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/client/index.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/AttachSubscriptionTypeToContactRequest.ts b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/AttachSubscriptionTypeToContactRequest.ts index 742321c7..18911f33 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/AttachSubscriptionTypeToContactRequest.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/AttachSubscriptionTypeToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,9 +23,7 @@ * } */ export interface AttachSubscriptionTypeToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; /** The unique identifier for the subscription which is given by Intercom */ id: string; diff --git a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/DetachSubscriptionTypeToContactRequest.ts b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/DetachSubscriptionTypeToContactRequest.ts index 8ad29dba..156af2ee 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/DetachSubscriptionTypeToContactRequest.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/DetachSubscriptionTypeToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DetachSubscriptionTypeToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the subscription type which is given by Intercom - */ + /** The unique identifier for the subscription type which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/index.ts b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/index.ts index d5cc644c..ce062982 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/client/requests/index.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type AttachSubscriptionTypeToContactRequest } from "./AttachSubscriptionTypeToContactRequest"; -export { type DetachSubscriptionTypeToContactRequest } from "./DetachSubscriptionTypeToContactRequest"; +export type { AttachSubscriptionTypeToContactRequest } from "./AttachSubscriptionTypeToContactRequest.js"; +export type { DetachSubscriptionTypeToContactRequest } from "./DetachSubscriptionTypeToContactRequest.js"; diff --git a/src/api/resources/unstable/resources/subscriptionTypes/index.ts b/src/api/resources/unstable/resources/subscriptionTypes/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/index.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/subscriptionTypes/types/SubscriptionType.ts b/src/api/resources/unstable/resources/subscriptionTypes/types/SubscriptionType.ts index bcb2bd27..3867aa94 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/types/SubscriptionType.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/types/SubscriptionType.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A subscription type lets customers easily opt out of non-essential communications without missing what's important to them. @@ -24,30 +22,26 @@ export interface SubscriptionType { } export namespace SubscriptionType { - /** - * The state of the subscription type. - */ - export type State = "live" | "draft" | "archived"; + /** The state of the subscription type. */ export const State = { Live: "live", Draft: "draft", Archived: "archived", } as const; - /** - * Describes the type of consent. - */ - export type ConsentType = "opt_out" | "opt_in"; + export type State = (typeof State)[keyof typeof State]; + /** Describes the type of consent. */ export const ConsentType = { OptOut: "opt_out", OptIn: "opt_in", } as const; + export type ConsentType = (typeof ConsentType)[keyof typeof ConsentType]; export type ContentTypes = ContentTypes.Item[]; export namespace ContentTypes { - export type Item = "email" | "sms_message"; export const Item = { Email: "email", SmsMessage: "sms_message", } as const; + export type Item = (typeof Item)[keyof typeof Item]; } } diff --git a/src/api/resources/unstable/resources/subscriptionTypes/types/index.ts b/src/api/resources/unstable/resources/subscriptionTypes/types/index.ts index fe95bab5..b6a27359 100644 --- a/src/api/resources/unstable/resources/subscriptionTypes/types/index.ts +++ b/src/api/resources/unstable/resources/subscriptionTypes/types/index.ts @@ -1 +1 @@ -export * from "./SubscriptionType"; +export * from "./SubscriptionType.js"; diff --git a/src/api/resources/unstable/resources/switch/client/Client.ts b/src/api/resources/unstable/resources/switch/client/Client.ts index 543d2759..0c95ab0e 100644 --- a/src/api/resources/unstable/resources/switch/client/Client.ts +++ b/src/api/resources/unstable/resources/switch/client/Client.ts @@ -1,79 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Switch { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace SwitchClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about Switch */ -export class Switch { - constructor(protected readonly _options: Switch.Options = {}) {} +export class SwitchClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: SwitchClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can use the API to deflect phone calls to the Intercom Messenger. @@ -82,7 +32,7 @@ export class Switch { * If custom attributes are specified, they will be added to the user or lead's custom data attributes. * * @param {unknown} request - * @param {Switch.RequestOptions} requestOptions - Request-specific configuration. + * @param {SwitchClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -95,40 +45,40 @@ export class Switch { */ public createPhoneSwitch( request?: unknown, - requestOptions?: Switch.RequestOptions, + requestOptions?: SwitchClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createPhoneSwitch(request, requestOptions)); } private async __createPhoneSwitch( request?: unknown, - requestOptions?: Switch.RequestOptions, + requestOptions?: SwitchClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "phone_call_redirects", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -160,32 +110,6 @@ export class Switch { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /phone_call_redirects."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/phone_call_redirects"); } } diff --git a/src/api/resources/unstable/resources/switch/index.ts b/src/api/resources/unstable/resources/switch/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/switch/index.ts +++ b/src/api/resources/unstable/resources/switch/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/tags/client/Client.ts b/src/api/resources/unstable/resources/tags/client/Client.ts index 279f075c..681b40df 100644 --- a/src/api/resources/unstable/resources/tags/client/Client.ts +++ b/src/api/resources/unstable/resources/tags/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Tags { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TagsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about tags */ -export class Tags { - constructor(protected readonly _options: Tags.Options = {}) {} +export class TagsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TagsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. * * @param {Intercom.unstable.AttachTagToContactRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -98,41 +48,41 @@ export class Tags { */ public attachTagToContact( request: Intercom.unstable.AttachTagToContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachTagToContact(request, requestOptions)); } private async __attachTagToContact( request: Intercom.unstable.AttachTagToContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { contact_id: contactId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags`, + `contacts/${core.url.encodePathParam(contactId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -156,30 +106,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /contacts/{contact_id}/tags.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/contacts/{contact_id}/tags"); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. * * @param {Intercom.unstable.DetachTagFromContactRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -192,40 +126,38 @@ export class Tags { */ public detachTagFromContact( request: Intercom.unstable.DetachTagFromContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachTagFromContact(request, requestOptions)); } private async __detachTagFromContact( request: Intercom.unstable.DetachTagFromContactRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { contact_id: contactId, id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `contacts/${encodeURIComponent(contactId)}/tags/${encodeURIComponent(id)}`, + `contacts/${core.url.encodePathParam(contactId)}/tags/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -249,30 +181,19 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /contacts/{contact_id}/tags/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/contacts/{contact_id}/tags/{id}", + ); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. * * @param {Intercom.unstable.AttachTagToConversationRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -286,41 +207,41 @@ export class Tags { */ public attachTagToConversation( request: Intercom.unstable.AttachTagToConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachTagToConversation(request, requestOptions)); } private async __attachTagToConversation( request: Intercom.unstable.AttachTagToConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/tags`, + `conversations/${core.url.encodePathParam(conversationId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -344,30 +265,19 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /conversations/{conversation_id}/tags.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/conversations/{conversation_id}/tags", + ); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. * * @param {Intercom.unstable.DetachTagFromConversationRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -381,41 +291,41 @@ export class Tags { */ public detachTagFromConversation( request: Intercom.unstable.DetachTagFromConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachTagFromConversation(request, requestOptions)); } private async __detachTagFromConversation( request: Intercom.unstable.DetachTagFromConversationRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { conversation_id: conversationId, id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `conversations/${encodeURIComponent(conversationId)}/tags/${encodeURIComponent(id)}`, + `conversations/${core.url.encodePathParam(conversationId)}/tags/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -439,66 +349,54 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /conversations/{conversation_id}/tags/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/conversations/{conversation_id}/tags/{id}", + ); } /** * You can fetch a list of all tags for a given workspace. * - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.tags.listTags() */ - public listTags(requestOptions?: Tags.RequestOptions): core.HttpResponsePromise { + public listTags(requestOptions?: TagsClient.RequestOptions): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listTags(requestOptions)); } private async __listTags( - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tags", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TagList, rawResponse: _response.rawResponse }; @@ -520,21 +418,7 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tags"); } /** @@ -553,7 +437,7 @@ export class Tags { * Each operation will return a tag object. * * @param {Intercom.unstable.CreateTagRequestBody} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -587,40 +471,40 @@ export class Tags { */ public createTag( request: Intercom.unstable.CreateTagRequestBody, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createTag(request, requestOptions)); } private async __createTag( request: Intercom.unstable.CreateTagRequestBody, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tags", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -646,21 +530,7 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tags"); } /** @@ -668,7 +538,7 @@ export class Tags { * This will return a tag object. * * @param {Intercom.unstable.FindTagRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -680,40 +550,38 @@ export class Tags { */ public findTag( request: Intercom.unstable.FindTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__findTag(request, requestOptions)); } private async __findTag( request: Intercom.unstable.FindTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tags/${encodeURIComponent(id)}`, + `tags/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -737,28 +605,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tags/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tags/{id}"); } /** * You can delete the details of tags that are on the workspace by passing in the id. * * @param {Intercom.unstable.DeleteTagRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -771,40 +625,38 @@ export class Tags { */ public deleteTag( request: Intercom.unstable.DeleteTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteTag(request, requestOptions)); } private async __deleteTag( request: Intercom.unstable.DeleteTagRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tags/${encodeURIComponent(id)}`, + `tags/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: undefined, rawResponse: _response.rawResponse }; @@ -830,28 +682,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /tags/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/tags/{id}"); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. * * @param {Intercom.unstable.AttachTagToTicketRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -865,41 +703,41 @@ export class Tags { */ public attachTagToTicket( request: Intercom.unstable.AttachTagToTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__attachTagToTicket(request, requestOptions)); } private async __attachTagToTicket( request: Intercom.unstable.AttachTagToTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { ticket_id: ticketId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}/tags`, + `tickets/${core.url.encodePathParam(ticketId)}/tags`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -923,28 +761,14 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/{ticket_id}/tags."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/{ticket_id}/tags"); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. * * @param {Intercom.unstable.DetachTagFromTicketRequest} request - * @param {Tags.RequestOptions} requestOptions - Request-specific configuration. + * @param {TagsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -958,41 +782,41 @@ export class Tags { */ public detachTagFromTicket( request: Intercom.unstable.DetachTagFromTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__detachTagFromTicket(request, requestOptions)); } private async __detachTagFromTicket( request: Intercom.unstable.DetachTagFromTicketRequest, - requestOptions?: Tags.RequestOptions, + requestOptions?: TagsClient.RequestOptions, ): Promise> { const { ticket_id: ticketId, id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(ticketId)}/tags/${encodeURIComponent(id)}`, + `tickets/${core.url.encodePathParam(ticketId)}/tags/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Tag, rawResponse: _response.rawResponse }; @@ -1016,34 +840,11 @@ export class Tags { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling DELETE /tickets/{ticket_id}/tags/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "DELETE", + "/tickets/{ticket_id}/tags/{id}", + ); } } diff --git a/src/api/resources/unstable/resources/tags/client/index.ts b/src/api/resources/unstable/resources/tags/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/tags/client/index.ts +++ b/src/api/resources/unstable/resources/tags/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToContactRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToContactRequest.ts index 2d9e27cc..94218c40 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToContactRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -22,9 +20,7 @@ * } */ export interface AttachTagToContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToConversationRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToConversationRequest.ts index f3533c92..c6084c34 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToConversationRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -18,9 +16,7 @@ * } */ export interface AttachTagToConversationRequest { - /** - * conversation_id - */ + /** conversation_id */ conversation_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToTicketRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToTicketRequest.ts index 55d90d6b..4082336b 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/AttachTagToTicketRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/AttachTagToTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -18,9 +16,7 @@ * } */ export interface AttachTagToTicketRequest { - /** - * ticket_id - */ + /** ticket_id */ ticket_id: string; /** The unique identifier for the tag which is given by Intercom */ id: string; diff --git a/src/api/resources/unstable/resources/tags/client/requests/DeleteTagRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/DeleteTagRequest.ts index 95921be7..1c226490 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/DeleteTagRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/DeleteTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteTagRequest { - /** - * The unique identifier of a given tag - */ + /** The unique identifier of a given tag */ id: string; } diff --git a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromContactRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromContactRequest.ts index a4d90398..6737ddff 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromContactRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -10,12 +8,8 @@ * } */ export interface DetachTagFromContactRequest { - /** - * The unique identifier for the contact which is given by Intercom - */ + /** The unique identifier for the contact which is given by Intercom */ contact_id: string; - /** - * The unique identifier for the tag which is given by Intercom - */ + /** The unique identifier for the tag which is given by Intercom */ id: string; } diff --git a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromConversationRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromConversationRequest.ts index b41584c0..9cc3452f 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromConversationRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,13 +23,9 @@ * } */ export interface DetachTagFromConversationRequest { - /** - * conversation_id - */ + /** conversation_id */ conversation_id: string; - /** - * id - */ + /** id */ id: string; /** The unique identifier for the admin which is given by Intercom. */ admin_id: string; diff --git a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromTicketRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromTicketRequest.ts index ed321a9a..9c6e58ac 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromTicketRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/DetachTagFromTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -25,13 +23,9 @@ * } */ export interface DetachTagFromTicketRequest { - /** - * ticket_id - */ + /** ticket_id */ ticket_id: string; - /** - * The unique identifier for the tag which is given by Intercom - */ + /** The unique identifier for the tag which is given by Intercom */ id: string; /** The unique identifier for the admin which is given by Intercom. */ admin_id: string; diff --git a/src/api/resources/unstable/resources/tags/client/requests/FindTagRequest.ts b/src/api/resources/unstable/resources/tags/client/requests/FindTagRequest.ts index 7f23eca2..f3f35724 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/FindTagRequest.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/FindTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindTagRequest { - /** - * The unique identifier of a given tag - */ + /** The unique identifier of a given tag */ id: string; } diff --git a/src/api/resources/unstable/resources/tags/client/requests/index.ts b/src/api/resources/unstable/resources/tags/client/requests/index.ts index f529317a..5e52c0b2 100644 --- a/src/api/resources/unstable/resources/tags/client/requests/index.ts +++ b/src/api/resources/unstable/resources/tags/client/requests/index.ts @@ -1,8 +1,8 @@ -export { type AttachTagToContactRequest } from "./AttachTagToContactRequest"; -export { type DetachTagFromContactRequest } from "./DetachTagFromContactRequest"; -export { type AttachTagToConversationRequest } from "./AttachTagToConversationRequest"; -export { type DetachTagFromConversationRequest } from "./DetachTagFromConversationRequest"; -export { type FindTagRequest } from "./FindTagRequest"; -export { type DeleteTagRequest } from "./DeleteTagRequest"; -export { type AttachTagToTicketRequest } from "./AttachTagToTicketRequest"; -export { type DetachTagFromTicketRequest } from "./DetachTagFromTicketRequest"; +export type { AttachTagToContactRequest } from "./AttachTagToContactRequest.js"; +export type { AttachTagToConversationRequest } from "./AttachTagToConversationRequest.js"; +export type { AttachTagToTicketRequest } from "./AttachTagToTicketRequest.js"; +export type { DeleteTagRequest } from "./DeleteTagRequest.js"; +export type { DetachTagFromContactRequest } from "./DetachTagFromContactRequest.js"; +export type { DetachTagFromConversationRequest } from "./DetachTagFromConversationRequest.js"; +export type { DetachTagFromTicketRequest } from "./DetachTagFromTicketRequest.js"; +export type { FindTagRequest } from "./FindTagRequest.js"; diff --git a/src/api/resources/unstable/resources/tags/index.ts b/src/api/resources/unstable/resources/tags/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/tags/index.ts +++ b/src/api/resources/unstable/resources/tags/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/tags/types/CreateTagRequestBody.ts b/src/api/resources/unstable/resources/tags/types/CreateTagRequestBody.ts index cd52e610..9f3ab1dc 100644 --- a/src/api/resources/unstable/resources/tags/types/CreateTagRequestBody.ts +++ b/src/api/resources/unstable/resources/tags/types/CreateTagRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export type CreateTagRequestBody = | Intercom.unstable.CreateOrUpdateTagRequest diff --git a/src/api/resources/unstable/resources/tags/types/Tag.ts b/src/api/resources/unstable/resources/tags/types/Tag.ts index 869f2171..f62cbefb 100644 --- a/src/api/resources/unstable/resources/tags/types/Tag.ts +++ b/src/api/resources/unstable/resources/tags/types/Tag.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A tag allows you to label your contacts, companies, and conversations and list them using that tag. diff --git a/src/api/resources/unstable/resources/tags/types/TagBasic.ts b/src/api/resources/unstable/resources/tags/types/TagBasic.ts index 7067f78b..8e8b815d 100644 --- a/src/api/resources/unstable/resources/tags/types/TagBasic.ts +++ b/src/api/resources/unstable/resources/tags/types/TagBasic.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A tag allows you to label your contacts, companies, and conversations and list them using that tag. diff --git a/src/api/resources/unstable/resources/tags/types/index.ts b/src/api/resources/unstable/resources/tags/types/index.ts index 0188807b..f1b106ee 100644 --- a/src/api/resources/unstable/resources/tags/types/index.ts +++ b/src/api/resources/unstable/resources/tags/types/index.ts @@ -1,3 +1,3 @@ -export * from "./CreateTagRequestBody"; -export * from "./Tag"; -export * from "./TagBasic"; +export * from "./CreateTagRequestBody.js"; +export * from "./Tag.js"; +export * from "./TagBasic.js"; diff --git a/src/api/resources/unstable/resources/teams/client/Client.ts b/src/api/resources/unstable/resources/teams/client/Client.ts index 1a849930..c83adaf9 100644 --- a/src/api/resources/unstable/resources/teams/client/Client.ts +++ b/src/api/resources/unstable/resources/teams/client/Client.ts @@ -1,121 +1,71 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Teams { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TeamsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Teams */ -export class Teams { - constructor(protected readonly _options: Teams.Options = {}) {} +export class TeamsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TeamsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * This will return a list of team objects for the App. * - * @param {Teams.RequestOptions} requestOptions - Request-specific configuration. + * @param {TeamsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * * @example * await client.unstable.teams.listTeams() */ - public listTeams(requestOptions?: Teams.RequestOptions): core.HttpResponsePromise { + public listTeams( + requestOptions?: TeamsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listTeams(requestOptions)); } private async __listTeams( - requestOptions?: Teams.RequestOptions, + requestOptions?: TeamsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "teams", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TeamList, rawResponse: _response.rawResponse }; @@ -137,28 +87,14 @@ export class Teams { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /teams."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/teams"); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. * * @param {Intercom.unstable.RetrieveTeamRequest} request - * @param {Teams.RequestOptions} requestOptions - Request-specific configuration. + * @param {TeamsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -170,40 +106,38 @@ export class Teams { */ public retrieveTeam( request: Intercom.unstable.RetrieveTeamRequest, - requestOptions?: Teams.RequestOptions, + requestOptions?: TeamsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveTeam(request, requestOptions)); } private async __retrieveTeam( request: Intercom.unstable.RetrieveTeamRequest, - requestOptions?: Teams.RequestOptions, + requestOptions?: TeamsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `teams/${encodeURIComponent(id)}`, + `teams/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Team, rawResponse: _response.rawResponse }; @@ -227,32 +161,6 @@ export class Teams { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /teams/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/teams/{id}"); } } diff --git a/src/api/resources/unstable/resources/teams/client/index.ts b/src/api/resources/unstable/resources/teams/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/teams/client/index.ts +++ b/src/api/resources/unstable/resources/teams/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/teams/client/requests/RetrieveTeamRequest.ts b/src/api/resources/unstable/resources/teams/client/requests/RetrieveTeamRequest.ts index 0b09296c..fd825fee 100644 --- a/src/api/resources/unstable/resources/teams/client/requests/RetrieveTeamRequest.ts +++ b/src/api/resources/unstable/resources/teams/client/requests/RetrieveTeamRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveTeamRequest { - /** - * The unique identifier of a given team. - */ + /** The unique identifier of a given team. */ id: string; } diff --git a/src/api/resources/unstable/resources/teams/client/requests/index.ts b/src/api/resources/unstable/resources/teams/client/requests/index.ts index b8dd50a7..6497a22a 100644 --- a/src/api/resources/unstable/resources/teams/client/requests/index.ts +++ b/src/api/resources/unstable/resources/teams/client/requests/index.ts @@ -1 +1 @@ -export { type RetrieveTeamRequest } from "./RetrieveTeamRequest"; +export type { RetrieveTeamRequest } from "./RetrieveTeamRequest.js"; diff --git a/src/api/resources/unstable/resources/teams/index.ts b/src/api/resources/unstable/resources/teams/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/teams/index.ts +++ b/src/api/resources/unstable/resources/teams/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/teams/types/Team.ts b/src/api/resources/unstable/resources/teams/types/Team.ts index 8ba1d68f..412cc0d0 100644 --- a/src/api/resources/unstable/resources/teams/types/Team.ts +++ b/src/api/resources/unstable/resources/teams/types/Team.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Teams are groups of admins in Intercom. diff --git a/src/api/resources/unstable/resources/teams/types/index.ts b/src/api/resources/unstable/resources/teams/types/index.ts index e3645596..bc100e99 100644 --- a/src/api/resources/unstable/resources/teams/types/index.ts +++ b/src/api/resources/unstable/resources/teams/types/index.ts @@ -1 +1 @@ -export * from "./Team"; +export * from "./Team.js"; diff --git a/src/api/resources/unstable/resources/ticketStates/client/Client.ts b/src/api/resources/unstable/resources/ticketStates/client/Client.ts index 9df86fd0..84960f00 100644 --- a/src/api/resources/unstable/resources/ticketStates/client/Client.ts +++ b/src/api/resources/unstable/resources/ticketStates/client/Client.ts @@ -1,84 +1,34 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace TicketStates { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketStatesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your ticket states */ -export class TicketStates { - constructor(protected readonly _options: TicketStates.Options = {}) {} +export class TicketStatesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketStatesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can get a list of all ticket states for a workspace. * - * @param {TicketStates.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketStatesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -86,38 +36,36 @@ export class TicketStates { * await client.unstable.ticketStates.listTicketStates() */ public listTicketStates( - requestOptions?: TicketStates.RequestOptions, + requestOptions?: TicketStatesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listTicketStates(requestOptions)); } private async __listTicketStates( - requestOptions?: TicketStates.RequestOptions, + requestOptions?: TicketStatesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ticket_states", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TicketStateList, rawResponse: _response.rawResponse }; @@ -139,32 +87,6 @@ export class TicketStates { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ticket_states."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ticket_states"); } } diff --git a/src/api/resources/unstable/resources/ticketStates/index.ts b/src/api/resources/unstable/resources/ticketStates/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/ticketStates/index.ts +++ b/src/api/resources/unstable/resources/ticketStates/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/client/Client.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/client/Client.ts index 4db689cf..fe5a1095 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/client/Client.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace TicketTypeAttributes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketTypeAttributesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your ticket type attributes */ -export class TicketTypeAttributes { - constructor(protected readonly _options: TicketTypeAttributes.Options = {}) {} +export class TicketTypeAttributesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketTypeAttributesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can create a new attribute for a ticket type. * * @param {Intercom.unstable.CreateTicketTypeAttributeRequest} request - * @param {TicketTypeAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypeAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -94,41 +44,41 @@ export class TicketTypeAttributes { */ public createTicketTypeAttribute( request: Intercom.unstable.CreateTicketTypeAttributeRequest, - requestOptions?: TicketTypeAttributes.RequestOptions, + requestOptions?: TicketTypeAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createTicketTypeAttribute(request, requestOptions)); } private async __createTicketTypeAttribute( request: Intercom.unstable.CreateTicketTypeAttributeRequest, - requestOptions?: TicketTypeAttributes.RequestOptions, + requestOptions?: TicketTypeAttributesClient.RequestOptions, ): Promise> { const { ticket_type_id: ticketTypeId, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}/attributes`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}/attributes`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -153,30 +103,19 @@ export class TicketTypeAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling POST /ticket_types/{ticket_type_id}/attributes.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "POST", + "/ticket_types/{ticket_type_id}/attributes", + ); } /** * You can update an existing attribute for a ticket type. * * @param {Intercom.unstable.UpdateTicketTypeAttributeRequest} request - * @param {TicketTypeAttributes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypeAttributesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -189,41 +128,41 @@ export class TicketTypeAttributes { */ public updateTicketTypeAttribute( request: Intercom.unstable.UpdateTicketTypeAttributeRequest, - requestOptions?: TicketTypeAttributes.RequestOptions, + requestOptions?: TicketTypeAttributesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateTicketTypeAttribute(request, requestOptions)); } private async __updateTicketTypeAttribute( request: Intercom.unstable.UpdateTicketTypeAttributeRequest, - requestOptions?: TicketTypeAttributes.RequestOptions, + requestOptions?: TicketTypeAttributesClient.RequestOptions, ): Promise> { const { ticket_type_id: ticketTypeId, id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(ticketTypeId)}/attributes/${encodeURIComponent(id)}`, + `ticket_types/${core.url.encodePathParam(ticketTypeId)}/attributes/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -248,34 +187,11 @@ export class TicketTypeAttributes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError( - "Timeout exceeded when calling PUT /ticket_types/{ticket_type_id}/attributes/{id}.", - ); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError( + _response.error, + _response.rawResponse, + "PUT", + "/ticket_types/{ticket_type_id}/attributes/{id}", + ); } } diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/client/index.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/client/index.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/CreateTicketTypeAttributeRequest.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/CreateTicketTypeAttributeRequest.ts index 0a9604c1..6dbf0ac2 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/CreateTicketTypeAttributeRequest.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/CreateTicketTypeAttributeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -13,9 +11,7 @@ * } */ export interface CreateTicketTypeAttributeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; /** The name of the ticket type attribute */ name: string; @@ -40,10 +36,7 @@ export interface CreateTicketTypeAttributeRequest { } export namespace CreateTicketTypeAttributeRequest { - /** - * The data type of the attribute - */ - export type DataType = "string" | "list" | "integer" | "decimal" | "boolean" | "datetime" | "files"; + /** The data type of the attribute */ export const DataType = { String: "string", List: "list", @@ -53,4 +46,5 @@ export namespace CreateTicketTypeAttributeRequest { Datetime: "datetime", Files: "files", } as const; + export type DataType = (typeof DataType)[keyof typeof DataType]; } diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/UpdateTicketTypeAttributeRequest.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/UpdateTicketTypeAttributeRequest.ts index 9575db2d..c56bbb7b 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/UpdateTicketTypeAttributeRequest.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/UpdateTicketTypeAttributeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -11,13 +9,9 @@ * } */ export interface UpdateTicketTypeAttributeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ ticket_type_id: string; - /** - * The unique identifier for the ticket type attribute which is given by Intercom. - */ + /** The unique identifier for the ticket type attribute which is given by Intercom. */ id: string; /** The name of the ticket type attribute */ name?: string; diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/index.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/index.ts index b2d37564..2a2ffb63 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/index.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type CreateTicketTypeAttributeRequest } from "./CreateTicketTypeAttributeRequest"; -export { type UpdateTicketTypeAttributeRequest } from "./UpdateTicketTypeAttributeRequest"; +export type { CreateTicketTypeAttributeRequest } from "./CreateTicketTypeAttributeRequest.js"; +export type { UpdateTicketTypeAttributeRequest } from "./UpdateTicketTypeAttributeRequest.js"; diff --git a/src/api/resources/unstable/resources/ticketTypeAttributes/index.ts b/src/api/resources/unstable/resources/ticketTypeAttributes/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/ticketTypeAttributes/index.ts +++ b/src/api/resources/unstable/resources/ticketTypeAttributes/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/ticketTypes/client/Client.ts b/src/api/resources/unstable/resources/ticketTypes/client/Client.ts index 857fd1f7..1d1adfed 100644 --- a/src/api/resources/unstable/resources/ticketTypes/client/Client.ts +++ b/src/api/resources/unstable/resources/ticketTypes/client/Client.ts @@ -1,84 +1,34 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace TicketTypes { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketTypesClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your ticket types */ -export class TicketTypes { - constructor(protected readonly _options: TicketTypes.Options = {}) {} +export class TicketTypesClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketTypesClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can get a list of all ticket types for a workspace. * - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -86,38 +36,36 @@ export class TicketTypes { * await client.unstable.ticketTypes.listTicketTypes() */ public listTicketTypes( - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__listTicketTypes(requestOptions)); } private async __listTicketTypes( - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ticket_types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TicketTypeList, rawResponse: _response.rawResponse }; @@ -139,21 +87,7 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ticket_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ticket_types"); } /** @@ -164,7 +98,7 @@ export class TicketTypes { * > For the `icon` propery, use an emoji from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) * * @param {unknown} request - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -175,40 +109,40 @@ export class TicketTypes { */ public createTicketType( request?: unknown, - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__createTicketType(request, requestOptions)); } private async __createTicketType( request?: unknown, - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "ticket_types", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -233,28 +167,14 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /ticket_types."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/ticket_types"); } /** * You can fetch the details of a single ticket type. * * @param {Intercom.unstable.GetTicketTypeRequest} request - * @param {TicketTypes.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketTypesClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -265,40 +185,38 @@ export class TicketTypes { */ public getTicketType( request: Intercom.unstable.GetTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getTicketType(request, requestOptions)); } private async __getTicketType( request: Intercom.unstable.GetTicketTypeRequest, - requestOptions?: TicketTypes.RequestOptions, + requestOptions?: TicketTypesClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `ticket_types/${encodeURIComponent(id)}`, + `ticket_types/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -323,32 +241,6 @@ export class TicketTypes { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /ticket_types/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/ticket_types/{id}"); } } diff --git a/src/api/resources/unstable/resources/ticketTypes/client/index.ts b/src/api/resources/unstable/resources/ticketTypes/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/ticketTypes/client/index.ts +++ b/src/api/resources/unstable/resources/ticketTypes/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/ticketTypes/client/requests/GetTicketTypeRequest.ts b/src/api/resources/unstable/resources/ticketTypes/client/requests/GetTicketTypeRequest.ts index b9868adc..542c28d9 100644 --- a/src/api/resources/unstable/resources/ticketTypes/client/requests/GetTicketTypeRequest.ts +++ b/src/api/resources/unstable/resources/ticketTypes/client/requests/GetTicketTypeRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface GetTicketTypeRequest { - /** - * The unique identifier for the ticket type which is given by Intercom. - */ + /** The unique identifier for the ticket type which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/ticketTypes/client/requests/index.ts b/src/api/resources/unstable/resources/ticketTypes/client/requests/index.ts index c25063a7..0ece78d7 100644 --- a/src/api/resources/unstable/resources/ticketTypes/client/requests/index.ts +++ b/src/api/resources/unstable/resources/ticketTypes/client/requests/index.ts @@ -1 +1 @@ -export { type GetTicketTypeRequest } from "./GetTicketTypeRequest"; +export type { GetTicketTypeRequest } from "./GetTicketTypeRequest.js"; diff --git a/src/api/resources/unstable/resources/ticketTypes/index.ts b/src/api/resources/unstable/resources/ticketTypes/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/ticketTypes/index.ts +++ b/src/api/resources/unstable/resources/ticketTypes/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/resources/tickets/client/Client.ts b/src/api/resources/unstable/resources/tickets/client/Client.ts index 116eed02..4c28d71b 100644 --- a/src/api/resources/unstable/resources/tickets/client/Client.ts +++ b/src/api/resources/unstable/resources/tickets/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Tickets { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace TicketsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your tickets */ -export class Tickets { - constructor(protected readonly _options: Tickets.Options = {}) {} +export class TicketsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: TicketsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. * * @param {Intercom.unstable.ReplyTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -137,41 +87,41 @@ export class Tickets { */ public replyTicket( request: Intercom.unstable.ReplyTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__replyTicket(request, requestOptions)); } private async __replyTicket( request: Intercom.unstable.ReplyTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { const { id, body: _body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(id)}/reply`, + `tickets/${core.url.encodePathParam(id)}/reply`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TicketReply, rawResponse: _response.rawResponse }; @@ -197,28 +147,14 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/{id}/reply."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/{id}/reply"); } /** * Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job. * * @param {Intercom.unstable.EnqueueCreateTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -233,40 +169,40 @@ export class Tickets { */ public enqueueCreateTicket( request: Intercom.unstable.EnqueueCreateTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__enqueueCreateTicket(request, requestOptions)); } private async __enqueueCreateTicket( request: Intercom.unstable.EnqueueCreateTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tickets/enqueue", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Jobs, rawResponse: _response.rawResponse }; @@ -290,28 +226,14 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/enqueue."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/enqueue"); } /** * You can fetch the details of a single ticket. * * @param {Intercom.unstable.GetTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -322,40 +244,38 @@ export class Tickets { */ public getTicket( request: Intercom.unstable.GetTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__getTicket(request, requestOptions)); } private async __getTicket( request: Intercom.unstable.GetTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(id)}`, + `tickets/${core.url.encodePathParam(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Ticket | undefined, rawResponse: _response.rawResponse }; @@ -377,28 +297,14 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /tickets/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/tickets/{id}"); } /** * You can update a ticket. * * @param {Intercom.unstable.UpdateTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.BadRequestError} * @throws {@link Intercom.unstable.UnauthorizedError} @@ -438,41 +344,41 @@ export class Tickets { */ public updateTicket( request: Intercom.unstable.UpdateTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateTicket(request, requestOptions)); } private async __updateTicket( request: Intercom.unstable.UpdateTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { const { id, ..._body } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(id)}`, + `tickets/${core.url.encodePathParam(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: _body, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Ticket | undefined, rawResponse: _response.rawResponse }; @@ -498,28 +404,14 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /tickets/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/tickets/{id}"); } /** * You can delete a ticket using the Intercom provided ID. * * @param {Intercom.unstable.DeleteTicketRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -531,40 +423,38 @@ export class Tickets { */ public deleteTicket( request: Intercom.unstable.DeleteTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__deleteTicket(request, requestOptions)); } private async __deleteTicket( request: Intercom.unstable.DeleteTicketRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { const { id } = request; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, - `tickets/${encodeURIComponent(id)}`, + `tickets/${core.url.encodePathParam(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: requestOptions?.queryParams, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -591,21 +481,7 @@ export class Tickets { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling DELETE /tickets/{id}."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/tickets/{id}"); } /** @@ -638,8 +514,8 @@ export class Tickets { * | id | String | * | created_at | Date (UNIX timestamp) | * | updated_at | Date (UNIX timestamp) | - * | _default_title_ | String | - * | _default_description_ | String | + * | title | String | + * | description | String | * | category | String | * | ticket_type_id | String | * | contact_ids | String | @@ -651,6 +527,13 @@ export class Tickets { * | snoozed_until | Date (UNIX timestamp) | * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer | * + * {% admonition type="info" name="Searching by Category" %} + * When searching for tickets by the **`category`** field, specific terms must be used instead of the category names: + * * For **Customer** category tickets, use the term `request`. + * * For **Back-office** category tickets, use the term `task`. + * * For **Tracker** category tickets, use the term `tracker`. + * {% /admonition %} + * * ### Accepted Operators * * {% admonition type="info" name="Searching based on `created_at`" %} @@ -673,7 +556,7 @@ export class Tickets { * | $ | String | Ends With | * * @param {Intercom.unstable.SearchRequest} request - * @param {Tickets.RequestOptions} requestOptions - Request-specific configuration. + * @param {TicketsClient.RequestOptions} requestOptions - Request-specific configuration. * * @example * await client.unstable.tickets.searchTickets({ @@ -692,40 +575,40 @@ export class Tickets { */ public searchTickets( request: Intercom.unstable.SearchRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__searchTickets(request, requestOptions)); } private async __searchTickets( request: Intercom.unstable.SearchRequest, - requestOptions?: Tickets.RequestOptions, + requestOptions?: TicketsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "tickets/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.TicketList, rawResponse: _response.rawResponse }; @@ -739,32 +622,6 @@ export class Tickets { }); } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /tickets/search."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/tickets/search"); } } diff --git a/src/api/resources/unstable/resources/tickets/client/index.ts b/src/api/resources/unstable/resources/tickets/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/tickets/client/index.ts +++ b/src/api/resources/unstable/resources/tickets/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/tickets/client/requests/DeleteTicketRequest.ts b/src/api/resources/unstable/resources/tickets/client/requests/DeleteTicketRequest.ts index 3a9f96f8..8ea2c5e7 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/DeleteTicketRequest.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/DeleteTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface DeleteTicketRequest { - /** - * The unique identifier for the ticket which is given by Intercom. - */ + /** The unique identifier for the ticket which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts b/src/api/resources/unstable/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts index d1d3b5ee..74d72736 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/EnqueueCreateTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/tickets/client/requests/GetTicketRequest.ts b/src/api/resources/unstable/resources/tickets/client/requests/GetTicketRequest.ts index ea0795f8..c48305e2 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/GetTicketRequest.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/GetTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface GetTicketRequest { - /** - * The unique identifier for the ticket which is given by Intercom. - */ + /** The unique identifier for the ticket which is given by Intercom. */ id: string; } diff --git a/src/api/resources/unstable/resources/tickets/client/requests/ReplyTicketRequest.ts b/src/api/resources/unstable/resources/tickets/client/requests/ReplyTicketRequest.ts index ae8e6378..1e53f5d6 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/ReplyTicketRequest.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/ReplyTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../../index"; +import type * as Intercom from "../../../../../../index.js"; /** * @example diff --git a/src/api/resources/unstable/resources/tickets/client/requests/UpdateTicketRequest.ts b/src/api/resources/unstable/resources/tickets/client/requests/UpdateTicketRequest.ts index 28c7e40f..63d68d08 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/UpdateTicketRequest.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/UpdateTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -48,9 +46,7 @@ * } */ export interface UpdateTicketRequest { - /** - * The unique identifier for the ticket which is given by Intercom - */ + /** The unique identifier for the ticket which is given by Intercom */ id: string; /** The attributes set on the ticket. */ ticket_attributes?: Record; diff --git a/src/api/resources/unstable/resources/tickets/client/requests/index.ts b/src/api/resources/unstable/resources/tickets/client/requests/index.ts index b6a892f9..8f0e8032 100644 --- a/src/api/resources/unstable/resources/tickets/client/requests/index.ts +++ b/src/api/resources/unstable/resources/tickets/client/requests/index.ts @@ -1,5 +1,5 @@ -export { type ReplyTicketRequest } from "./ReplyTicketRequest"; -export { type EnqueueCreateTicketRequest } from "./EnqueueCreateTicketRequest"; -export { type GetTicketRequest } from "./GetTicketRequest"; -export { type UpdateTicketRequest } from "./UpdateTicketRequest"; -export { type DeleteTicketRequest } from "./DeleteTicketRequest"; +export type { DeleteTicketRequest } from "./DeleteTicketRequest.js"; +export type { EnqueueCreateTicketRequest } from "./EnqueueCreateTicketRequest.js"; +export type { GetTicketRequest } from "./GetTicketRequest.js"; +export type { ReplyTicketRequest } from "./ReplyTicketRequest.js"; +export type { UpdateTicketRequest } from "./UpdateTicketRequest.js"; diff --git a/src/api/resources/unstable/resources/tickets/index.ts b/src/api/resources/unstable/resources/tickets/index.ts index c9240f83..d9adb1af 100644 --- a/src/api/resources/unstable/resources/tickets/index.ts +++ b/src/api/resources/unstable/resources/tickets/index.ts @@ -1,2 +1,2 @@ -export * from "./types"; -export * from "./client"; +export * from "./client/index.js"; +export * from "./types/index.js"; diff --git a/src/api/resources/unstable/resources/tickets/types/DeleteTicketResponse.ts b/src/api/resources/unstable/resources/tickets/types/DeleteTicketResponse.ts index 579725c6..cdad7f2d 100644 --- a/src/api/resources/unstable/resources/tickets/types/DeleteTicketResponse.ts +++ b/src/api/resources/unstable/resources/tickets/types/DeleteTicketResponse.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response when a ticket is deleted. diff --git a/src/api/resources/unstable/resources/tickets/types/ReplyTicketRequestBody.ts b/src/api/resources/unstable/resources/tickets/types/ReplyTicketRequestBody.ts index 3f2ede0c..cc0d3384 100644 --- a/src/api/resources/unstable/resources/tickets/types/ReplyTicketRequestBody.ts +++ b/src/api/resources/unstable/resources/tickets/types/ReplyTicketRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; export type ReplyTicketRequestBody = | Intercom.unstable.ContactReplyTicketRequest diff --git a/src/api/resources/unstable/resources/tickets/types/Ticket.ts b/src/api/resources/unstable/resources/tickets/types/Ticket.ts index 45defe9b..1da56448 100644 --- a/src/api/resources/unstable/resources/tickets/types/Ticket.ts +++ b/src/api/resources/unstable/resources/tickets/types/Ticket.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * Tickets are how you track requests from your users. @@ -39,13 +37,11 @@ export interface Ticket { } export namespace Ticket { - /** - * Category of the Ticket. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/unstable/resources/tickets/types/TicketContacts.ts b/src/api/resources/unstable/resources/tickets/types/TicketContacts.ts index e025dd66..f85afa9f 100644 --- a/src/api/resources/unstable/resources/tickets/types/TicketContacts.ts +++ b/src/api/resources/unstable/resources/tickets/types/TicketContacts.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * The list of contacts affected by a ticket. diff --git a/src/api/resources/unstable/resources/tickets/types/TicketPart.ts b/src/api/resources/unstable/resources/tickets/types/TicketPart.ts index 9153bf31..6ab9ce04 100644 --- a/src/api/resources/unstable/resources/tickets/types/TicketPart.ts +++ b/src/api/resources/unstable/resources/tickets/types/TicketPart.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A Ticket Part represents a message in the ticket. @@ -40,26 +38,22 @@ export interface TicketPart { } export namespace TicketPart { - /** - * The previous state of the ticket. - */ - export type PreviousTicketState = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + /** The previous state of the ticket. */ export const PreviousTicketState = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; - /** - * The state of the ticket. - */ - export type TicketState = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + export type PreviousTicketState = (typeof PreviousTicketState)[keyof typeof PreviousTicketState]; + /** The state of the ticket. */ export const TicketState = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; + export type TicketState = (typeof TicketState)[keyof typeof TicketState]; /** * The updated attribute data of the ticket part. Only present for attribute update parts. diff --git a/src/api/resources/unstable/resources/tickets/types/TicketState.ts b/src/api/resources/unstable/resources/tickets/types/TicketState.ts index 70427191..beef89c7 100644 --- a/src/api/resources/unstable/resources/tickets/types/TicketState.ts +++ b/src/api/resources/unstable/resources/tickets/types/TicketState.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A ticket state, used to define the state of a ticket. @@ -19,14 +17,12 @@ export interface TicketState { } export namespace TicketState { - /** - * The category of the ticket state - */ - export type Category = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + /** The category of the ticket state */ export const Category = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/unstable/resources/tickets/types/TicketStateDetailed.ts b/src/api/resources/unstable/resources/tickets/types/TicketStateDetailed.ts index 2502a84b..1281034c 100644 --- a/src/api/resources/unstable/resources/tickets/types/TicketStateDetailed.ts +++ b/src/api/resources/unstable/resources/tickets/types/TicketStateDetailed.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A ticket state, used to define the state of a ticket. @@ -25,16 +23,14 @@ export interface TicketStateDetailed { } export namespace TicketStateDetailed { - /** - * The category of the ticket state - */ - export type Category = "submitted" | "in_progress" | "waiting_on_customer" | "resolved"; + /** The category of the ticket state */ export const Category = { Submitted: "submitted", InProgress: "in_progress", WaitingOnCustomer: "waiting_on_customer", Resolved: "resolved", } as const; + export type Category = (typeof Category)[keyof typeof Category]; /** * A list of ticket types associated with a given ticket state. diff --git a/src/api/resources/unstable/resources/tickets/types/TicketType.ts b/src/api/resources/unstable/resources/tickets/types/TicketType.ts index 3af90517..bdb7bae4 100644 --- a/src/api/resources/unstable/resources/tickets/types/TicketType.ts +++ b/src/api/resources/unstable/resources/tickets/types/TicketType.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../../index"; +import type * as Intercom from "../../../../../index.js"; /** * A ticket type, used to define the data fields to be captured in a ticket. @@ -34,15 +32,13 @@ export interface TicketType { } export namespace TicketType { - /** - * Category of the Ticket Type. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket Type. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; + export type Category = (typeof Category)[keyof typeof Category]; /** * A list of ticket states associated with a given ticket type. diff --git a/src/api/resources/unstable/resources/tickets/types/index.ts b/src/api/resources/unstable/resources/tickets/types/index.ts index 5c6f7a46..5cad94df 100644 --- a/src/api/resources/unstable/resources/tickets/types/index.ts +++ b/src/api/resources/unstable/resources/tickets/types/index.ts @@ -1,8 +1,8 @@ -export * from "./ReplyTicketRequestBody"; -export * from "./DeleteTicketResponse"; -export * from "./Ticket"; -export * from "./TicketContacts"; -export * from "./TicketPart"; -export * from "./TicketState"; -export * from "./TicketStateDetailed"; -export * from "./TicketType"; +export * from "./DeleteTicketResponse.js"; +export * from "./ReplyTicketRequestBody.js"; +export * from "./Ticket.js"; +export * from "./TicketContacts.js"; +export * from "./TicketPart.js"; +export * from "./TicketState.js"; +export * from "./TicketStateDetailed.js"; +export * from "./TicketType.js"; diff --git a/src/api/resources/unstable/resources/visitors/client/Client.ts b/src/api/resources/unstable/resources/visitors/client/Client.ts index ef6e2e8a..600ffecf 100644 --- a/src/api/resources/unstable/resources/visitors/client/Client.ts +++ b/src/api/resources/unstable/resources/visitors/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../../../environments"; -import * as core from "../../../../../../core"; -import * as Intercom from "../../../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers.js"; +import * as core from "../../../../../../core/index.js"; +import * as environments from "../../../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../../../errors/index.js"; +import * as Intercom from "../../../../../index.js"; -export declare namespace Visitors { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace VisitorsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Visitors */ -export class Visitors { - constructor(protected readonly _options: Visitors.Options = {}) {} +export class VisitorsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: VisitorsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch the details of a single visitor. * * @param {Intercom.unstable.RetrieveVisitorWithUserIdRequest} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -91,43 +41,40 @@ export class Visitors { */ public retrieveVisitorWithUserId( request: Intercom.unstable.RetrieveVisitorWithUserIdRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__retrieveVisitorWithUserId(request, requestOptions)); } private async __retrieveVisitorWithUserId( request: Intercom.unstable.RetrieveVisitorWithUserIdRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): Promise> { const { user_id: userId } = request; const _queryParams: Record = {}; - _queryParams["user_id"] = userId; + _queryParams.user_id = userId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -154,21 +101,7 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /visitors."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/visitors"); } /** @@ -179,7 +112,7 @@ export class Visitors { * **Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body. * * @param {Intercom.UpdateVisitorRequestOne} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @throws {@link Intercom.unstable.NotFoundError} @@ -198,40 +131,40 @@ export class Visitors { */ public updateVisitor( request?: Intercom.UpdateVisitorRequestOne, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__updateVisitor(request, requestOptions)); } private async __updateVisitor( request?: Intercom.UpdateVisitorRequestOne, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { @@ -258,21 +191,7 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /visitors."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/visitors"); } /** @@ -283,7 +202,7 @@ export class Visitors { * > If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers. * * @param {Intercom.unstable.ConvertVisitorRequest} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.unstable.UnauthorizedError} * @@ -300,40 +219,40 @@ export class Visitors { */ public convertVisitor( request: Intercom.unstable.ConvertVisitorRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__convertVisitor(request, requestOptions)); } private async __convertVisitor( request: Intercom.unstable.ConvertVisitorRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors/convert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.unstable.Contact, rawResponse: _response.rawResponse }; @@ -355,32 +274,6 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /visitors/convert."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/visitors/convert"); } } diff --git a/src/api/resources/unstable/resources/visitors/client/index.ts b/src/api/resources/unstable/resources/visitors/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/unstable/resources/visitors/client/index.ts +++ b/src/api/resources/unstable/resources/visitors/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/unstable/resources/visitors/client/requests/ConvertVisitorRequest.ts b/src/api/resources/unstable/resources/visitors/client/requests/ConvertVisitorRequest.ts index 275e76e7..0dceb82c 100644 --- a/src/api/resources/unstable/resources/visitors/client/requests/ConvertVisitorRequest.ts +++ b/src/api/resources/unstable/resources/visitors/client/requests/ConvertVisitorRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/unstable/resources/visitors/client/requests/RetrieveVisitorWithUserIdRequest.ts b/src/api/resources/unstable/resources/visitors/client/requests/RetrieveVisitorWithUserIdRequest.ts index 27554599..cd10d234 100644 --- a/src/api/resources/unstable/resources/visitors/client/requests/RetrieveVisitorWithUserIdRequest.ts +++ b/src/api/resources/unstable/resources/visitors/client/requests/RetrieveVisitorWithUserIdRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface RetrieveVisitorWithUserIdRequest { - /** - * The user_id of the Visitor you want to retrieve. - */ + /** The user_id of the Visitor you want to retrieve. */ user_id: string; } diff --git a/src/api/resources/unstable/resources/visitors/client/requests/index.ts b/src/api/resources/unstable/resources/visitors/client/requests/index.ts index 8878667c..a1b1278e 100644 --- a/src/api/resources/unstable/resources/visitors/client/requests/index.ts +++ b/src/api/resources/unstable/resources/visitors/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type RetrieveVisitorWithUserIdRequest } from "./RetrieveVisitorWithUserIdRequest"; -export { type ConvertVisitorRequest } from "./ConvertVisitorRequest"; +export type { ConvertVisitorRequest } from "./ConvertVisitorRequest.js"; +export type { RetrieveVisitorWithUserIdRequest } from "./RetrieveVisitorWithUserIdRequest.js"; diff --git a/src/api/resources/unstable/resources/visitors/index.ts b/src/api/resources/unstable/resources/visitors/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/unstable/resources/visitors/index.ts +++ b/src/api/resources/unstable/resources/visitors/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/resources/unstable/types/ActivityLog.ts b/src/api/resources/unstable/types/ActivityLog.ts index 1815ce24..e510cac9 100644 --- a/src/api/resources/unstable/types/ActivityLog.ts +++ b/src/api/resources/unstable/types/ActivityLog.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Activities performed by Admins. @@ -35,76 +33,9 @@ export namespace ActivityLog { ip?: string; } - export type ActivityType = - | "admin_assignment_limit_change" - | "admin_away_mode_change" - | "admin_deletion" - | "admin_deprovisioned" - | "admin_impersonation_end" - | "admin_impersonation_start" - | "admin_invite_change" - | "admin_invite_creation" - | "admin_invite_deletion" - | "admin_login_failure" - | "admin_login_success" - | "admin_logout" - | "admin_password_reset_request" - | "admin_password_reset_success" - | "admin_permission_change" - | "admin_provisioned" - | "admin_two_factor_auth_change" - | "admin_unauthorized_sign_in_method" - | "app_admin_join" - | "app_authentication_method_change" - | "app_data_deletion" - | "app_data_export" - | "app_google_sso_domain_change" - | "app_identity_verification_change" - | "app_name_change" - | "app_outbound_address_change" - | "app_package_installation" - | "app_package_token_regeneration" - | "app_package_uninstallation" - | "app_team_creation" - | "app_team_deletion" - | "app_team_membership_modification" - | "app_timezone_change" - | "app_webhook_creation" - | "app_webhook_deletion" - | "articles_in_messenger_enabled_change" - | "bulk_delete" - | "bulk_export" - | "campaign_deletion" - | "campaign_state_change" - | "conversation_part_deletion" - | "conversation_topic_change" - | "conversation_topic_creation" - | "conversation_topic_deletion" - | "help_center_settings_change" - | "inbound_conversations_change" - | "inbox_access_change" - | "message_deletion" - | "message_state_change" - | "messenger_look_and_feel_change" - | "messenger_search_required_change" - | "messenger_spaces_change" - | "office_hours_change" - | "role_change" - | "role_creation" - | "role_deletion" - | "ruleset_activation_title_preview" - | "ruleset_creation" - | "ruleset_deletion" - | "search_browse_enabled_change" - | "search_browse_required_change" - | "seat_change" - | "seat_revoke" - | "security_settings_change" - | "temporary_expectation_change" - | "upfront_email_collection_change" - | "welcome_message_change"; export const ActivityType = { - AdminAssignmentLimitChange: "admin_assignment_limit_change", + AdminConversationAssignmentLimitChange: "admin_conversation_assignment_limit_change", + AdminTicketAssignmentLimitChange: "admin_ticket_assignment_limit_change", AdminAwayModeChange: "admin_away_mode_change", AdminDeletion: "admin_deletion", AdminDeprovisioned: "admin_deprovisioned", @@ -172,4 +103,5 @@ export namespace ActivityLog { UpfrontEmailCollectionChange: "upfront_email_collection_change", WelcomeMessageChange: "welcome_message_change", } as const; + export type ActivityType = (typeof ActivityType)[keyof typeof ActivityType]; } diff --git a/src/api/resources/unstable/types/ActivityLogList.ts b/src/api/resources/unstable/types/ActivityLogList.ts index 7c9d4e57..f570390b 100644 --- a/src/api/resources/unstable/types/ActivityLogList.ts +++ b/src/api/resources/unstable/types/ActivityLogList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A paginated list of activity logs. diff --git a/src/api/resources/unstable/types/ActivityLogMetadata.ts b/src/api/resources/unstable/types/ActivityLogMetadata.ts index 4814d8e5..cbd7324e 100644 --- a/src/api/resources/unstable/types/ActivityLogMetadata.ts +++ b/src/api/resources/unstable/types/ActivityLogMetadata.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Additional data provided about Admin activity. @@ -24,4 +22,8 @@ export interface ActivityLogMetadata { update_by?: number; /** The name of the Admin who initiated the activity. */ update_by_name?: string; + /** The conversation assignment limit value for an admin. */ + conversation_assignment_limit?: number; + /** The ticket assignment limit value for an admin. */ + ticket_assignment_limit?: number; } diff --git a/src/api/resources/unstable/types/AddressableList.ts b/src/api/resources/unstable/types/AddressableList.ts index 787be0f6..cbda5a63 100644 --- a/src/api/resources/unstable/types/AddressableList.ts +++ b/src/api/resources/unstable/types/AddressableList.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A list used to access other resources from a parent model. diff --git a/src/api/resources/unstable/types/AdminList.ts b/src/api/resources/unstable/types/AdminList.ts index b5fc73d2..01507d8d 100644 --- a/src/api/resources/unstable/types/AdminList.ts +++ b/src/api/resources/unstable/types/AdminList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of admins associated with a given workspace. diff --git a/src/api/resources/unstable/types/AdminPriorityLevel.ts b/src/api/resources/unstable/types/AdminPriorityLevel.ts index 659f95f2..1127dadf 100644 --- a/src/api/resources/unstable/types/AdminPriorityLevel.ts +++ b/src/api/resources/unstable/types/AdminPriorityLevel.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Admin priority levels for the team diff --git a/src/api/resources/unstable/types/AdminReplyConversationRequest.ts b/src/api/resources/unstable/types/AdminReplyConversationRequest.ts index b0bcb16c..cf90c85b 100644 --- a/src/api/resources/unstable/types/AdminReplyConversationRequest.ts +++ b/src/api/resources/unstable/types/AdminReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of an admin @@ -25,10 +23,10 @@ export interface AdminReplyConversationRequest { } export namespace AdminReplyConversationRequest { - export type MessageType = "comment" | "note" | "quick_reply"; export const MessageType = { Comment: "comment", Note: "note", QuickReply: "quick_reply", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; } diff --git a/src/api/resources/unstable/types/AdminReplyTicketRequest.ts b/src/api/resources/unstable/types/AdminReplyTicketRequest.ts index dfc2ae57..3e2ac1ed 100644 --- a/src/api/resources/unstable/types/AdminReplyTicketRequest.ts +++ b/src/api/resources/unstable/types/AdminReplyTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to reply on behalf of an admin @@ -21,12 +19,12 @@ export interface AdminReplyTicketRequest { } export namespace AdminReplyTicketRequest { - export type MessageType = "comment" | "note" | "quick_reply"; export const MessageType = { Comment: "comment", Note: "note", QuickReply: "quick_reply", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; export type ReplyOptions = ReplyOptions.Item[]; export namespace ReplyOptions { diff --git a/src/api/resources/unstable/types/AdminWithApp.ts b/src/api/resources/unstable/types/AdminWithApp.ts index 4d7f69ed..37c0c32c 100644 --- a/src/api/resources/unstable/types/AdminWithApp.ts +++ b/src/api/resources/unstable/types/AdminWithApp.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Admins are the teammate accounts that have access to a workspace diff --git a/src/api/resources/unstable/types/AiCallResponse.ts b/src/api/resources/unstable/types/AiCallResponse.ts new file mode 100644 index 00000000..6f90c177 --- /dev/null +++ b/src/api/resources/unstable/types/AiCallResponse.ts @@ -0,0 +1,27 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Response containing information about a Fin Voice call + */ +export interface AiCallResponse { + /** The unique identifier for the external reference */ + id?: number; + /** The workspace identifier */ + app_id?: number; + /** Phone number in E.164 format for the call */ + user_phone_number?: string; + /** Status of the call. Can be "registered", "in-progress", or a resolution state */ + status?: string; + /** The Intercom call identifier, if the call has been matched */ + intercom_call_id?: string; + /** The external call identifier from the call provider */ + external_call_id?: string; + /** The Intercom conversation identifier, if a conversation has been created */ + intercom_conversation_id?: string; + /** Array of transcript entries for the call */ + call_transcript?: Record[]; + /** Summary of the call conversation, truncated to 256 characters. Empty string if no summary available. */ + call_summary?: string; + /** Array of intent classifications for the call */ + intent?: Record[]; +} diff --git a/src/api/resources/unstable/types/App.ts b/src/api/resources/unstable/types/App.ts index fd2d8319..67ce2d3c 100644 --- a/src/api/resources/unstable/types/App.ts +++ b/src/api/resources/unstable/types/App.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * App is a workspace on Intercom diff --git a/src/api/resources/unstable/types/ArticleContent.ts b/src/api/resources/unstable/types/ArticleContent.ts index 31652500..bccb5af5 100644 --- a/src/api/resources/unstable/types/ArticleContent.ts +++ b/src/api/resources/unstable/types/ArticleContent.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The Content of an Article. */ export interface ArticleContent { /** The type of object - `article_content` . */ - type?: string; + type?: "article_content"; /** The title of the article. */ title?: string; /** The description of the article. */ @@ -27,12 +25,10 @@ export interface ArticleContent { } export namespace ArticleContent { - /** - * Whether the article is `published` or is a `draft` . - */ - export type State = "published" | "draft"; + /** Whether the article is `published` or is a `draft` . */ export const State = { Published: "published", Draft: "draft", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/types/ArticleList.ts b/src/api/resources/unstable/types/ArticleList.ts index 5dbc0a01..67d409ef 100644 --- a/src/api/resources/unstable/types/ArticleList.ts +++ b/src/api/resources/unstable/types/ArticleList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of articles for the App. diff --git a/src/api/resources/unstable/types/ArticleStatistics.ts b/src/api/resources/unstable/types/ArticleStatistics.ts index 2e12b7b3..16f14f48 100644 --- a/src/api/resources/unstable/types/ArticleStatistics.ts +++ b/src/api/resources/unstable/types/ArticleStatistics.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The statistics of an article. diff --git a/src/api/resources/unstable/types/ArticleTranslatedContent.ts b/src/api/resources/unstable/types/ArticleTranslatedContent.ts index 5e4e52bd..2e625936 100644 --- a/src/api/resources/unstable/types/ArticleTranslatedContent.ts +++ b/src/api/resources/unstable/types/ArticleTranslatedContent.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The Translated Content of an Article. The keys are the locale codes and the values are the translated content of the article. */ export interface ArticleTranslatedContent { /** The type of object - article_translated_content. */ - type?: string; + type?: "article_translated_content"; /** The content of the article in Arabic */ ar?: Intercom.unstable.ArticleContent; /** The content of the article in Bulgarian */ diff --git a/src/api/resources/unstable/types/AssignConversationRequest.ts b/src/api/resources/unstable/types/AssignConversationRequest.ts index e3eef208..0e2e8ba8 100644 --- a/src/api/resources/unstable/types/AssignConversationRequest.ts +++ b/src/api/resources/unstable/types/AssignConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to assign a conversation @@ -16,9 +14,9 @@ export interface AssignConversationRequest { } export namespace AssignConversationRequest { - export type Type = "admin" | "team"; export const Type = { Admin: "admin", Team: "team", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/AwayStatusReason.ts b/src/api/resources/unstable/types/AwayStatusReason.ts index 02f9e7a8..01eaf720 100644 --- a/src/api/resources/unstable/types/AwayStatusReason.ts +++ b/src/api/resources/unstable/types/AwayStatusReason.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface AwayStatusReason { type?: string; diff --git a/src/api/resources/unstable/types/CallList.ts b/src/api/resources/unstable/types/CallList.ts new file mode 100644 index 00000000..bd332337 --- /dev/null +++ b/src/api/resources/unstable/types/CallList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * A paginated list of calls. + */ +export interface CallList { + /** String representing the object's type. Always has the value `list`. */ + type?: string; + /** A list of calls. */ + data?: Intercom.unstable.Call[]; + /** Total number of items available. */ + total_count?: number; + pages?: Intercom.unstable.CursorPages; +} diff --git a/src/api/resources/unstable/types/CloseConversationRequest.ts b/src/api/resources/unstable/types/CloseConversationRequest.ts index 56f0755e..0c75f0c3 100644 --- a/src/api/resources/unstable/types/CloseConversationRequest.ts +++ b/src/api/resources/unstable/types/CloseConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to close a conversation diff --git a/src/api/resources/unstable/types/CollectionList.ts b/src/api/resources/unstable/types/CollectionList.ts index ee2bbe53..455ae28a 100644 --- a/src/api/resources/unstable/types/CollectionList.ts +++ b/src/api/resources/unstable/types/CollectionList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of Collections for the App. diff --git a/src/api/resources/unstable/types/CompanyAttachedContacts.ts b/src/api/resources/unstable/types/CompanyAttachedContacts.ts index c4490d96..d23643b4 100644 --- a/src/api/resources/unstable/types/CompanyAttachedContacts.ts +++ b/src/api/resources/unstable/types/CompanyAttachedContacts.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Contact Objects diff --git a/src/api/resources/unstable/types/CompanyAttachedSegments.ts b/src/api/resources/unstable/types/CompanyAttachedSegments.ts index b7c72a13..73ace745 100644 --- a/src/api/resources/unstable/types/CompanyAttachedSegments.ts +++ b/src/api/resources/unstable/types/CompanyAttachedSegments.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Segment Objects diff --git a/src/api/resources/unstable/types/CompanyData.ts b/src/api/resources/unstable/types/CompanyData.ts index de38845a..29d3a559 100644 --- a/src/api/resources/unstable/types/CompanyData.ts +++ b/src/api/resources/unstable/types/CompanyData.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing data about the companies that a contact is associated with. diff --git a/src/api/resources/unstable/types/CompanyList.ts b/src/api/resources/unstable/types/CompanyList.ts index af078812..670df0a5 100644 --- a/src/api/resources/unstable/types/CompanyList.ts +++ b/src/api/resources/unstable/types/CompanyList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of companies for the App. diff --git a/src/api/resources/unstable/types/CompanyScroll.ts b/src/api/resources/unstable/types/CompanyScroll.ts index 95030bb2..4f876c99 100644 --- a/src/api/resources/unstable/types/CompanyScroll.ts +++ b/src/api/resources/unstable/types/CompanyScroll.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Companies allow you to represent organizations using your product. Each company will have its own description and be associated with contacts. You can fetch, create, update and list companies. diff --git a/src/api/resources/unstable/types/ContactArchived.ts b/src/api/resources/unstable/types/ContactArchived.ts index 9a5527f7..b99dc919 100644 --- a/src/api/resources/unstable/types/ContactArchived.ts +++ b/src/api/resources/unstable/types/ContactArchived.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * archived contact object diff --git a/src/api/resources/unstable/types/ContactAttachedCompanies.ts b/src/api/resources/unstable/types/ContactAttachedCompanies.ts index d4a80f8f..c9afae62 100644 --- a/src/api/resources/unstable/types/ContactAttachedCompanies.ts +++ b/src/api/resources/unstable/types/ContactAttachedCompanies.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Company Objects diff --git a/src/api/resources/unstable/types/ContactBlocked.ts b/src/api/resources/unstable/types/ContactBlocked.ts index 203b8792..0d31658f 100644 --- a/src/api/resources/unstable/types/ContactBlocked.ts +++ b/src/api/resources/unstable/types/ContactBlocked.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * blocked contact object diff --git a/src/api/resources/unstable/types/ContactCompanies.ts b/src/api/resources/unstable/types/ContactCompanies.ts index a827865a..c78c8889 100644 --- a/src/api/resources/unstable/types/ContactCompanies.ts +++ b/src/api/resources/unstable/types/ContactCompanies.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object with metadata about companies attached to a contact . Up to 10 will be displayed here. Use the url to get more. diff --git a/src/api/resources/unstable/types/ContactDeleted.ts b/src/api/resources/unstable/types/ContactDeleted.ts index 38fc4950..c5a47283 100644 --- a/src/api/resources/unstable/types/ContactDeleted.ts +++ b/src/api/resources/unstable/types/ContactDeleted.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * deleted contact object diff --git a/src/api/resources/unstable/types/ContactList.ts b/src/api/resources/unstable/types/ContactList.ts index 51a0df3c..5ef1b342 100644 --- a/src/api/resources/unstable/types/ContactList.ts +++ b/src/api/resources/unstable/types/ContactList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Contacts are your users in Intercom. diff --git a/src/api/resources/unstable/types/ContactLocation.ts b/src/api/resources/unstable/types/ContactLocation.ts index 6f3ca2ec..73f32530 100644 --- a/src/api/resources/unstable/types/ContactLocation.ts +++ b/src/api/resources/unstable/types/ContactLocation.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing location meta data about a Intercom contact. diff --git a/src/api/resources/unstable/types/ContactNotes.ts b/src/api/resources/unstable/types/ContactNotes.ts index fe835d12..88338f22 100644 --- a/src/api/resources/unstable/types/ContactNotes.ts +++ b/src/api/resources/unstable/types/ContactNotes.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing notes meta data about the notes that a contact has. Up to 10 will be displayed here. Use the url to get more. diff --git a/src/api/resources/unstable/types/ContactReference.ts b/src/api/resources/unstable/types/ContactReference.ts index d202aadc..6ff6080e 100644 --- a/src/api/resources/unstable/types/ContactReference.ts +++ b/src/api/resources/unstable/types/ContactReference.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * reference to contact object diff --git a/src/api/resources/unstable/types/ContactReplyBaseRequest.ts b/src/api/resources/unstable/types/ContactReplyBaseRequest.ts index 0559f83e..e6ebd102 100644 --- a/src/api/resources/unstable/types/ContactReplyBaseRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyBaseRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface ContactReplyBaseRequest { message_type: "comment"; diff --git a/src/api/resources/unstable/types/ContactReplyConversationRequest.ts b/src/api/resources/unstable/types/ContactReplyConversationRequest.ts index 74fe2c40..eb27b919 100644 --- a/src/api/resources/unstable/types/ContactReplyConversationRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type ContactReplyConversationRequest = | Intercom.unstable.ContactReplyIntercomUserIdRequest diff --git a/src/api/resources/unstable/types/ContactReplyEmailRequest.ts b/src/api/resources/unstable/types/ContactReplyEmailRequest.ts index f00aaaec..31f73734 100644 --- a/src/api/resources/unstable/types/ContactReplyEmailRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyEmailRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `email` diff --git a/src/api/resources/unstable/types/ContactReplyIntercomUserIdRequest.ts b/src/api/resources/unstable/types/ContactReplyIntercomUserIdRequest.ts index 0b6e3424..edd5a8fd 100644 --- a/src/api/resources/unstable/types/ContactReplyIntercomUserIdRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyIntercomUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `intercom_user_id` diff --git a/src/api/resources/unstable/types/ContactReplyTicketEmailRequest.ts b/src/api/resources/unstable/types/ContactReplyTicketEmailRequest.ts index b66e60dd..bad5a71c 100644 --- a/src/api/resources/unstable/types/ContactReplyTicketEmailRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyTicketEmailRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `email` diff --git a/src/api/resources/unstable/types/ContactReplyTicketIntercomUserIdRequest.ts b/src/api/resources/unstable/types/ContactReplyTicketIntercomUserIdRequest.ts index fd94eb7f..70a2d6e2 100644 --- a/src/api/resources/unstable/types/ContactReplyTicketIntercomUserIdRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyTicketIntercomUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `intercom_user_id` diff --git a/src/api/resources/unstable/types/ContactReplyTicketRequest.ts b/src/api/resources/unstable/types/ContactReplyTicketRequest.ts index c83977cc..523c59ef 100644 --- a/src/api/resources/unstable/types/ContactReplyTicketRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type ContactReplyTicketRequest = | Intercom.unstable.ContactReplyTicketIntercomUserIdRequest diff --git a/src/api/resources/unstable/types/ContactReplyTicketUserIdRequest.ts b/src/api/resources/unstable/types/ContactReplyTicketUserIdRequest.ts index 5a6d2796..51ec38dc 100644 --- a/src/api/resources/unstable/types/ContactReplyTicketUserIdRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyTicketUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `user_id` diff --git a/src/api/resources/unstable/types/ContactReplyUserIdRequest.ts b/src/api/resources/unstable/types/ContactReplyUserIdRequest.ts index b7e32da0..6870f212 100644 --- a/src/api/resources/unstable/types/ContactReplyUserIdRequest.ts +++ b/src/api/resources/unstable/types/ContactReplyUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Payload of the request to reply on behalf of a contact using their `user_id` diff --git a/src/api/resources/unstable/types/ContactSegments.ts b/src/api/resources/unstable/types/ContactSegments.ts index 21a83fec..370cfde9 100644 --- a/src/api/resources/unstable/types/ContactSegments.ts +++ b/src/api/resources/unstable/types/ContactSegments.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of segments objects attached to a specific contact. diff --git a/src/api/resources/unstable/types/ContactSocialProfiles.ts b/src/api/resources/unstable/types/ContactSocialProfiles.ts index 32b4dfde..dd46662b 100644 --- a/src/api/resources/unstable/types/ContactSocialProfiles.ts +++ b/src/api/resources/unstable/types/ContactSocialProfiles.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing social profiles that a contact has. diff --git a/src/api/resources/unstable/types/ContactSubscriptionTypes.ts b/src/api/resources/unstable/types/ContactSubscriptionTypes.ts index fc133189..b478bc44 100644 --- a/src/api/resources/unstable/types/ContactSubscriptionTypes.ts +++ b/src/api/resources/unstable/types/ContactSubscriptionTypes.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing Subscription Types meta data about the SubscriptionTypes that a contact has. diff --git a/src/api/resources/unstable/types/ContactTags.ts b/src/api/resources/unstable/types/ContactTags.ts index c7bc0e62..2ed6d4e7 100644 --- a/src/api/resources/unstable/types/ContactTags.ts +++ b/src/api/resources/unstable/types/ContactTags.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing tags meta data about the tags that a contact has. Up to 10 will be displayed here. Use the url to get more. diff --git a/src/api/resources/unstable/types/ContactUnarchived.ts b/src/api/resources/unstable/types/ContactUnarchived.ts index 38322437..e5b151a1 100644 --- a/src/api/resources/unstable/types/ContactUnarchived.ts +++ b/src/api/resources/unstable/types/ContactUnarchived.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * unarchived contact object diff --git a/src/api/resources/unstable/types/ContentSourcesList.ts b/src/api/resources/unstable/types/ContentSourcesList.ts index 9250df9d..aee5ab31 100644 --- a/src/api/resources/unstable/types/ContentSourcesList.ts +++ b/src/api/resources/unstable/types/ContentSourcesList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export interface ContentSourcesList { type?: "content_source.list"; diff --git a/src/api/resources/unstable/types/ConversationAttachmentFiles.ts b/src/api/resources/unstable/types/ConversationAttachmentFiles.ts index 98d751b4..f1a0b3e5 100644 --- a/src/api/resources/unstable/types/ConversationAttachmentFiles.ts +++ b/src/api/resources/unstable/types/ConversationAttachmentFiles.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Properties of the attachment files in a conversation part diff --git a/src/api/resources/unstable/types/ConversationAttributeUpdatedByAdmin.ts b/src/api/resources/unstable/types/ConversationAttributeUpdatedByAdmin.ts index 1c49cecf..b44c2202 100644 --- a/src/api/resources/unstable/types/ConversationAttributeUpdatedByAdmin.ts +++ b/src/api/resources/unstable/types/ConversationAttributeUpdatedByAdmin.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains details about Custom Data Attributes (CDAs) that were modified by an admin (operator) for conversation part type conversation_attribute_updated_by_admin. diff --git a/src/api/resources/unstable/types/ConversationAttributeUpdatedByWorkflow.ts b/src/api/resources/unstable/types/ConversationAttributeUpdatedByWorkflow.ts index 65572650..e9e75f32 100644 --- a/src/api/resources/unstable/types/ConversationAttributeUpdatedByWorkflow.ts +++ b/src/api/resources/unstable/types/ConversationAttributeUpdatedByWorkflow.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains details about the workflow that was triggered and any Custom Data Attributes (CDAs) that were modified during the workflow execution for conversation part type conversation_attribute_updated_by_workflow. diff --git a/src/api/resources/unstable/types/ConversationContacts.ts b/src/api/resources/unstable/types/ConversationContacts.ts index c9818ad5..eb49d28f 100644 --- a/src/api/resources/unstable/types/ConversationContacts.ts +++ b/src/api/resources/unstable/types/ConversationContacts.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The list of contacts (users or leads) involved in this conversation. This will only contain one customer unless more were added via the group conversation feature. diff --git a/src/api/resources/unstable/types/ConversationDeleted.ts b/src/api/resources/unstable/types/ConversationDeleted.ts index c45bc58f..e61823b9 100644 --- a/src/api/resources/unstable/types/ConversationDeleted.ts +++ b/src/api/resources/unstable/types/ConversationDeleted.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * deleted conversation object diff --git a/src/api/resources/unstable/types/ConversationFirstContactReply.ts b/src/api/resources/unstable/types/ConversationFirstContactReply.ts index 7d859b74..2085bd1e 100644 --- a/src/api/resources/unstable/types/ConversationFirstContactReply.ts +++ b/src/api/resources/unstable/types/ConversationFirstContactReply.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing information on the first users message. For a contact initiated message this will represent the users original message. diff --git a/src/api/resources/unstable/types/ConversationList.ts b/src/api/resources/unstable/types/ConversationList.ts index 402dae67..9a0a768e 100644 --- a/src/api/resources/unstable/types/ConversationList.ts +++ b/src/api/resources/unstable/types/ConversationList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Conversations are how you can communicate with users in Intercom. They are created when a contact replies to an outbound message, or when one admin directly sends a message to a single contact. diff --git a/src/api/resources/unstable/types/ConversationPart.ts b/src/api/resources/unstable/types/ConversationPart.ts index e724eb88..0d55a965 100644 --- a/src/api/resources/unstable/types/ConversationPart.ts +++ b/src/api/resources/unstable/types/ConversationPart.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A Conversation Part represents a message in the conversation. @@ -43,13 +41,11 @@ export interface ConversationPart { } export namespace ConversationPart { - /** - * Indicates the current state of conversation when the conversation part was created. - */ - export type State = "open" | "closed" | "snoozed"; + /** Indicates the current state of conversation when the conversation part was created. */ export const State = { Open: "open", Closed: "closed", Snoozed: "snoozed", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/types/ConversationPartAuthor.ts b/src/api/resources/unstable/types/ConversationPartAuthor.ts index 01a62b9f..3a17d751 100644 --- a/src/api/resources/unstable/types/ConversationPartAuthor.ts +++ b/src/api/resources/unstable/types/ConversationPartAuthor.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The object who initiated the conversation, which can be a Contact, Admin or Team. Bots and campaigns send messages on behalf of Admins or Teams. For Twitter, this will be blank. diff --git a/src/api/resources/unstable/types/ConversationPartMetadata.ts b/src/api/resources/unstable/types/ConversationPartMetadata.ts index 1a71c4a2..73de6365 100644 --- a/src/api/resources/unstable/types/ConversationPartMetadata.ts +++ b/src/api/resources/unstable/types/ConversationPartMetadata.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Metadata for a conversation part diff --git a/src/api/resources/unstable/types/ConversationParts.ts b/src/api/resources/unstable/types/ConversationParts.ts index 2c21bccd..a1e3f943 100644 --- a/src/api/resources/unstable/types/ConversationParts.ts +++ b/src/api/resources/unstable/types/ConversationParts.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Conversation Part objects for each part message in the conversation. This is only returned when Retrieving a Conversation, and ignored when Listing all Conversations. There is a limit of 500 parts. diff --git a/src/api/resources/unstable/types/ConversationRating.ts b/src/api/resources/unstable/types/ConversationRating.ts index 5b5a7899..1edf63c5 100644 --- a/src/api/resources/unstable/types/ConversationRating.ts +++ b/src/api/resources/unstable/types/ConversationRating.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The Conversation Rating object which contains information on the rating and/or remark added by a Contact and the Admin assigned to the conversation. @@ -14,6 +12,8 @@ export interface ConversationRating { remark?: string; /** The time the rating was requested in the conversation being rated. */ created_at?: number; + /** The time the rating was last updated. */ + updated_at?: number; contact?: Intercom.unstable.ContactReference; teammate?: Intercom.unstable.Reference; } diff --git a/src/api/resources/unstable/types/ConversationResponseTime.ts b/src/api/resources/unstable/types/ConversationResponseTime.ts index 56d2b0ae..8c503679 100644 --- a/src/api/resources/unstable/types/ConversationResponseTime.ts +++ b/src/api/resources/unstable/types/ConversationResponseTime.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Details of first response time of assigned team in seconds. diff --git a/src/api/resources/unstable/types/ConversationSource.ts b/src/api/resources/unstable/types/ConversationSource.ts index e9ade720..3987bf3f 100644 --- a/src/api/resources/unstable/types/ConversationSource.ts +++ b/src/api/resources/unstable/types/ConversationSource.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The type of the conversation part that started this conversation. Can be Contact, Admin, Campaign, Automated or Operator initiated. @@ -28,20 +26,7 @@ export interface ConversationSource { } export namespace ConversationSource { - /** - * This includes conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. - */ - export type Type = - | "conversation" - | "email" - | "facebook" - | "instagram" - | "phone_call" - | "phone_switch" - | "push" - | "sms" - | "twitter" - | "whatsapp"; + /** This includes conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. */ export const Type = { Conversation: "conversation", Email: "email", @@ -54,4 +39,5 @@ export namespace ConversationSource { Twitter: "twitter", Whatsapp: "whatsapp", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/ConversationStatistics.ts b/src/api/resources/unstable/types/ConversationStatistics.ts index 03dc8b5c..8491c58f 100644 --- a/src/api/resources/unstable/types/ConversationStatistics.ts +++ b/src/api/resources/unstable/types/ConversationStatistics.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A Statistics object containing all information required for reporting, with timestamps and calculated metrics. @@ -52,4 +50,6 @@ export interface ConversationStatistics { assigned_team_first_response_time_in_office_hours?: Intercom.unstable.ConversationResponseTime[]; /** Time from conversation assignment to conversation close in seconds. */ handling_time?: number; + /** Adjusted handling time for conversation in seconds. This is the active handling time excluding idle periods when teammates are not actively working on the conversation. */ + adjusted_handling_time?: number; } diff --git a/src/api/resources/unstable/types/ConversationTeammates.ts b/src/api/resources/unstable/types/ConversationTeammates.ts index b72a5928..3932494d 100644 --- a/src/api/resources/unstable/types/ConversationTeammates.ts +++ b/src/api/resources/unstable/types/ConversationTeammates.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The list of teammates who participated in the conversation (wrote at least one conversation part). diff --git a/src/api/resources/unstable/types/UpdateArticleRequestBody.ts b/src/api/resources/unstable/types/CreateArticleRequest.ts similarity index 67% rename from src/api/resources/unstable/types/UpdateArticleRequestBody.ts rename to src/api/resources/unstable/types/CreateArticleRequest.ts index 09be43a9..fae9a9e6 100644 --- a/src/api/resources/unstable/types/UpdateArticleRequestBody.ts +++ b/src/api/resources/unstable/types/CreateArticleRequest.ts @@ -1,37 +1,33 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** - * You can Update an Article + * You can create an Article */ -export interface UpdateArticleRequestBody { +export interface CreateArticleRequest { /** The title of the article.For multilingual articles, this will be the title of the default language's content. */ - title?: string; + title: string; /** The description of the article. For multilingual articles, this will be the description of the default language's content. */ description?: string; /** The content of the article. For multilingual articles, this will be the body of the default language's content. */ body?: string; /** The id of the author of the article. For multilingual articles, this will be the id of the author of the default language's content. Must be a teammate on the help center's workspace. */ - author_id?: number; + author_id: number; /** Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. */ - state?: UpdateArticleRequestBody.State; + state?: CreateArticleRequest.State; /** The id of the article's parent collection or section. An article without this field stands alone. */ - parent_id?: string; + parent_id?: number; /** The type of parent, which can either be a `collection` or `section`. */ parent_type?: string; translated_content?: Intercom.unstable.ArticleTranslatedContent; } -export namespace UpdateArticleRequestBody { - /** - * Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. - */ - export type State = "published" | "draft"; +export namespace CreateArticleRequest { + /** Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. */ export const State = { Published: "published", Draft: "draft", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/types/CreateDataAttributeRequest.ts b/src/api/resources/unstable/types/CreateDataAttributeRequest.ts new file mode 100644 index 00000000..e2abd5d2 --- /dev/null +++ b/src/api/resources/unstable/types/CreateDataAttributeRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * + */ +export type CreateDataAttributeRequest = + | { + data_type?: "options" | undefined; + options: { + value?: string | undefined; + }[]; + } + | { + data_type?: ("string" | "integer" | "float" | "boolean" | "datetime" | "date") | undefined; + }; diff --git a/src/api/resources/unstable/types/CreateInternalArticleRequest.ts b/src/api/resources/unstable/types/CreateInternalArticleRequest.ts new file mode 100644 index 00000000..f971e918 --- /dev/null +++ b/src/api/resources/unstable/types/CreateInternalArticleRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can create an Internal Article + */ +export interface CreateInternalArticleRequest { + /** The title of the article. */ + title: string; + /** The content of the article. */ + body?: string; + /** The id of the author of the article. */ + author_id: number; + /** The id of the owner of the article. */ + owner_id: number; +} diff --git a/src/api/resources/unstable/types/CreateMessageRequest.ts b/src/api/resources/unstable/types/CreateMessageRequest.ts new file mode 100644 index 00000000..b9bc1f58 --- /dev/null +++ b/src/api/resources/unstable/types/CreateMessageRequest.ts @@ -0,0 +1,6 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can create a message + */ +export type CreateMessageRequest = unknown | undefined; diff --git a/src/api/resources/unstable/types/CreateOrUpdateCompanyRequest.ts b/src/api/resources/unstable/types/CreateOrUpdateCompanyRequest.ts new file mode 100644 index 00000000..9a465e5c --- /dev/null +++ b/src/api/resources/unstable/types/CreateOrUpdateCompanyRequest.ts @@ -0,0 +1,25 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can create or update a Company + */ +export interface CreateOrUpdateCompanyRequest { + /** The name of the Company */ + name?: string; + /** The company id you have defined for the company. Can't be updated */ + company_id?: string; + /** The name of the plan you have associated with the company. */ + plan?: string; + /** The number of employees in this company. */ + size?: number; + /** The URL for this company's website. Please note that the value specified here is not validated. Accepts any string. */ + website?: string; + /** The industry that this company operates in. */ + industry?: string; + /** A hash of key/value pairs containing any other data about the company you want Intercom to store. */ + custom_attributes?: Record; + /** The time the company was created by you. */ + remote_created_at?: number; + /** How much revenue the company generates for your business. Note that this will truncate floats. i.e. it only allow for whole integers, 155.98 will be truncated to 155. Note that this has an upper limit of 2**31-1 or 2147483647.. */ + monthly_spend?: number; +} diff --git a/src/api/resources/unstable/types/CreateOrUpdateTagRequest.ts b/src/api/resources/unstable/types/CreateOrUpdateTagRequest.ts index a79ff2e0..7dfd1b3f 100644 --- a/src/api/resources/unstable/types/CreateOrUpdateTagRequest.ts +++ b/src/api/resources/unstable/types/CreateOrUpdateTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can create or update an existing tag. diff --git a/src/api/resources/unstable/types/CreatePhoneSwitchRequest.ts b/src/api/resources/unstable/types/CreatePhoneSwitchRequest.ts new file mode 100644 index 00000000..825757f8 --- /dev/null +++ b/src/api/resources/unstable/types/CreatePhoneSwitchRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * You can create an phone switch + */ +export interface CreatePhoneSwitchRequest { + /** Phone number in E.164 format, that will receive the SMS to continue the conversation in the Messenger. */ + phone: string; + custom_attributes?: Intercom.unstable.CustomAttributes; +} diff --git a/src/api/resources/unstable/types/CreateTicketReplyWithCommentRequest.ts b/src/api/resources/unstable/types/CreateTicketReplyWithCommentRequest.ts index cbca0524..31c13aad 100644 --- a/src/api/resources/unstable/types/CreateTicketReplyWithCommentRequest.ts +++ b/src/api/resources/unstable/types/CreateTicketReplyWithCommentRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type CreateTicketReplyWithCommentRequest = | Intercom.unstable.ContactReplyTicketRequest diff --git a/src/api/resources/unstable/types/CreateTicketRequestBody.ts b/src/api/resources/unstable/types/CreateTicketRequestBody.ts index b5af5ba1..9ec9fb5c 100644 --- a/src/api/resources/unstable/types/CreateTicketRequestBody.ts +++ b/src/api/resources/unstable/types/CreateTicketRequestBody.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can create a Ticket diff --git a/src/api/resources/ticketTypes/client/requests/CreateTicketTypeRequest.ts b/src/api/resources/unstable/types/CreateTicketTypeRequest.ts similarity index 65% rename from src/api/resources/ticketTypes/client/requests/CreateTicketTypeRequest.ts rename to src/api/resources/unstable/types/CreateTicketTypeRequest.ts index 0282e169..eebc72da 100644 --- a/src/api/resources/ticketTypes/client/requests/CreateTicketTypeRequest.ts +++ b/src/api/resources/unstable/types/CreateTicketTypeRequest.ts @@ -1,15 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** - * @example - * { - * name: "Customer Issue", - * description: "Customer Report Template", - * category: "Customer", - * icon: "\uD83C\uDF9F\uFE0F" - * } + * The request payload for creating a ticket type. + * You can copy the `icon` property for your ticket type from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) */ export interface CreateTicketTypeRequest { /** The name of the ticket type. */ @@ -25,13 +18,11 @@ export interface CreateTicketTypeRequest { } export namespace CreateTicketTypeRequest { - /** - * Category of the Ticket Type. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; + /** Category of the Ticket Type. */ export const Category = { Customer: "Customer", BackOffice: "Back-office", Tracker: "Tracker", } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/unstable/types/CursorPages.ts b/src/api/resources/unstable/types/CursorPages.ts index b289ca72..28a01ed3 100644 --- a/src/api/resources/unstable/types/CursorPages.ts +++ b/src/api/resources/unstable/types/CursorPages.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Cursor-based pagination is a technique used in the Intercom API to navigate through large amounts of data. diff --git a/src/api/resources/unstable/types/CustomActionFinished.ts b/src/api/resources/unstable/types/CustomActionFinished.ts index 95484be5..54471392 100644 --- a/src/api/resources/unstable/types/CustomActionFinished.ts +++ b/src/api/resources/unstable/types/CustomActionFinished.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains details about final status of the completed action for conversation part type custom_action_finished. @@ -18,13 +16,11 @@ export namespace CustomActionFinished { } export namespace Action { - /** - * Status of the action - */ - export type Result = "success" | "failed"; + /** Status of the action */ export const Result = { Success: "success", Failed: "failed", } as const; + export type Result = (typeof Result)[keyof typeof Result]; } } diff --git a/src/api/resources/unstable/types/CustomActionStarted.ts b/src/api/resources/unstable/types/CustomActionStarted.ts index eb089da6..18114f6c 100644 --- a/src/api/resources/unstable/types/CustomActionStarted.ts +++ b/src/api/resources/unstable/types/CustomActionStarted.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains details about name of the action that was initiated for conversation part type custom_action_started. diff --git a/src/api/resources/unstable/types/CustomAttributes.ts b/src/api/resources/unstable/types/CustomAttributes.ts index 1a8f52e6..c2086e14 100644 --- a/src/api/resources/unstable/types/CustomAttributes.ts +++ b/src/api/resources/unstable/types/CustomAttributes.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing the different custom attributes associated to the conversation as key-value pairs. For relationship attributes the value will be a list of custom object instance models. diff --git a/src/api/resources/unstable/types/CustomChannelAttribute.ts b/src/api/resources/unstable/types/CustomChannelAttribute.ts index 1f5ffeb6..9afa1dd6 100644 --- a/src/api/resources/unstable/types/CustomChannelAttribute.ts +++ b/src/api/resources/unstable/types/CustomChannelAttribute.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface CustomChannelAttribute { /** Identifier for the attribute being collected. */ diff --git a/src/api/resources/unstable/types/CustomChannelBaseEvent.ts b/src/api/resources/unstable/types/CustomChannelBaseEvent.ts index 16b7996e..6a638105 100644 --- a/src/api/resources/unstable/types/CustomChannelBaseEvent.ts +++ b/src/api/resources/unstable/types/CustomChannelBaseEvent.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export interface CustomChannelBaseEvent { /** Unique identifier for the event. */ diff --git a/src/api/resources/unstable/types/CustomChannelContact.ts b/src/api/resources/unstable/types/CustomChannelContact.ts index e1e7eabc..7d11a83c 100644 --- a/src/api/resources/unstable/types/CustomChannelContact.ts +++ b/src/api/resources/unstable/types/CustomChannelContact.ts @@ -1,25 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface CustomChannelContact { /** Type of contact, must be "user" or "lead". */ type: CustomChannelContact.Type; /** External identifier for the contact. Intercom will take care of the mapping of your external_id with our internal ones so you don't have to worry about it. */ external_id: string; - /** Name of the contact. */ - name: string; - /** Email address of the contact. */ - email: string; + /** Name of the contact. Required for user type. */ + name?: string; + /** Email address of the contact. Required for user type. */ + email?: string; } export namespace CustomChannelContact { - /** - * Type of contact, must be "user" or "lead". - */ - export type Type = "user" | "lead"; + /** Type of contact, must be "user" or "lead". */ export const Type = { User: "user", Lead: "lead", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/CustomChannelNotificationResponse.ts b/src/api/resources/unstable/types/CustomChannelNotificationResponse.ts index ae5a5611..238b883d 100644 --- a/src/api/resources/unstable/types/CustomChannelNotificationResponse.ts +++ b/src/api/resources/unstable/types/CustomChannelNotificationResponse.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface CustomChannelNotificationResponse { /** The external conversation ID provided in the notification request */ diff --git a/src/api/resources/unstable/types/CustomObjectInstanceDeleted.ts b/src/api/resources/unstable/types/CustomObjectInstanceDeleted.ts index 091e1ec4..4c14eba9 100644 --- a/src/api/resources/unstable/types/CustomObjectInstanceDeleted.ts +++ b/src/api/resources/unstable/types/CustomObjectInstanceDeleted.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * deleted custom object instance object diff --git a/src/api/resources/unstable/types/CustomObjectInstanceList.ts b/src/api/resources/unstable/types/CustomObjectInstanceList.ts index 8bfd0ef2..98e68588 100644 --- a/src/api/resources/unstable/types/CustomObjectInstanceList.ts +++ b/src/api/resources/unstable/types/CustomObjectInstanceList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The list of associated custom object instances for a given reference attribute on the parent object. diff --git a/src/api/resources/unstable/types/CustomerRequest.ts b/src/api/resources/unstable/types/CustomerRequest.ts index 6ede7a3d..d86d11c7 100644 --- a/src/api/resources/unstable/types/CustomerRequest.ts +++ b/src/api/resources/unstable/types/CustomerRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type CustomerRequest = | { diff --git a/src/api/resources/unstable/types/DataAttributeList.ts b/src/api/resources/unstable/types/DataAttributeList.ts index 5242a0bf..f8b6055b 100644 --- a/src/api/resources/unstable/types/DataAttributeList.ts +++ b/src/api/resources/unstable/types/DataAttributeList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of all data attributes belonging to a workspace for contacts, companies or conversations. diff --git a/src/api/resources/unstable/types/DataEventList.ts b/src/api/resources/unstable/types/DataEventList.ts index 09ed47e2..1fa73fc8 100644 --- a/src/api/resources/unstable/types/DataEventList.ts +++ b/src/api/resources/unstable/types/DataEventList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of data events for the App. diff --git a/src/api/resources/unstable/types/DataEventSummary.ts b/src/api/resources/unstable/types/DataEventSummary.ts index 87791da0..0badccff 100644 --- a/src/api/resources/unstable/types/DataEventSummary.ts +++ b/src/api/resources/unstable/types/DataEventSummary.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a summary of data events for the App. diff --git a/src/api/resources/unstable/types/DataEventSummaryItem.ts b/src/api/resources/unstable/types/DataEventSummaryItem.ts index 26f9e3a5..9f0d9192 100644 --- a/src/api/resources/unstable/types/DataEventSummaryItem.ts +++ b/src/api/resources/unstable/types/DataEventSummaryItem.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * This will return a summary of a data event for the App. diff --git a/src/api/resources/unstable/types/DataExportCsv.ts b/src/api/resources/unstable/types/DataExportCsv.ts index 5cc3bea0..8c268f7e 100644 --- a/src/api/resources/unstable/types/DataExportCsv.ts +++ b/src/api/resources/unstable/types/DataExportCsv.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A CSV output file diff --git a/src/api/resources/unstable/types/Datetime.ts b/src/api/resources/unstable/types/Datetime.ts index c291e607..63964732 100644 --- a/src/api/resources/unstable/types/Datetime.ts +++ b/src/api/resources/unstable/types/Datetime.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type Datetime = /** diff --git a/src/api/resources/unstable/types/DeletedArticleObject.ts b/src/api/resources/unstable/types/DeletedArticleObject.ts index 2fb626a8..5667114c 100644 --- a/src/api/resources/unstable/types/DeletedArticleObject.ts +++ b/src/api/resources/unstable/types/DeletedArticleObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted diff --git a/src/api/resources/unstable/types/DeletedCollectionObject.ts b/src/api/resources/unstable/types/DeletedCollectionObject.ts index 9f09babd..4d03d936 100644 --- a/src/api/resources/unstable/types/DeletedCollectionObject.ts +++ b/src/api/resources/unstable/types/DeletedCollectionObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted diff --git a/src/api/resources/unstable/types/DeletedCompanyObject.ts b/src/api/resources/unstable/types/DeletedCompanyObject.ts index f93f0699..b5ee6cf6 100644 --- a/src/api/resources/unstable/types/DeletedCompanyObject.ts +++ b/src/api/resources/unstable/types/DeletedCompanyObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted diff --git a/src/api/resources/unstable/types/DeletedInternalArticleObject.ts b/src/api/resources/unstable/types/DeletedInternalArticleObject.ts new file mode 100644 index 00000000..47d5060b --- /dev/null +++ b/src/api/resources/unstable/types/DeletedInternalArticleObject.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Response returned when an object is deleted + */ +export interface DeletedInternalArticleObject { + /** The unique identifier for the internal article which you provided in the URL. */ + id?: string; + /** The type of object which was deleted. - internal_article */ + object?: "internal_article"; + /** Whether the internal article was deleted successfully or not. */ + deleted?: boolean; +} diff --git a/src/api/resources/unstable/types/DeletedObject.ts b/src/api/resources/unstable/types/DeletedObject.ts index 613a0f83..a22b393b 100644 --- a/src/api/resources/unstable/types/DeletedObject.ts +++ b/src/api/resources/unstable/types/DeletedObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted diff --git a/src/api/resources/unstable/types/EmailAddressHeader.ts b/src/api/resources/unstable/types/EmailAddressHeader.ts index 81f30d02..7e8d234d 100644 --- a/src/api/resources/unstable/types/EmailAddressHeader.ts +++ b/src/api/resources/unstable/types/EmailAddressHeader.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains data for an email address header for a conversation part that was sent as an email. diff --git a/src/api/resources/unstable/types/EmailMessageMetadata.ts b/src/api/resources/unstable/types/EmailMessageMetadata.ts index 6a407392..022108cf 100644 --- a/src/api/resources/unstable/types/EmailMessageMetadata.ts +++ b/src/api/resources/unstable/types/EmailMessageMetadata.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Contains metadata if the message was sent as an email @@ -12,4 +10,6 @@ export interface EmailMessageMetadata { subject?: string; /** A list of an email address headers. */ email_address_headers?: Intercom.unstable.EmailAddressHeader[]; + /** The unique identifier for the email message as specified in the Message-ID header */ + message_id?: string; } diff --git a/src/api/resources/unstable/types/Error_.ts b/src/api/resources/unstable/types/Error_.ts index 1526174a..91e726ed 100644 --- a/src/api/resources/unstable/types/Error_.ts +++ b/src/api/resources/unstable/types/Error_.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The API will return an Error List for a failed request, which will contain one or more Error objects. diff --git a/src/api/resources/unstable/types/EventDetails.ts b/src/api/resources/unstable/types/EventDetails.ts index a5bddd05..b257b71e 100644 --- a/src/api/resources/unstable/types/EventDetails.ts +++ b/src/api/resources/unstable/types/EventDetails.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type EventDetails = | Intercom.unstable.ConversationAttributeUpdatedByWorkflow diff --git a/src/api/resources/unstable/types/FileAttribute.ts b/src/api/resources/unstable/types/FileAttribute.ts index e0c5f023..b8fab036 100644 --- a/src/api/resources/unstable/types/FileAttribute.ts +++ b/src/api/resources/unstable/types/FileAttribute.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The value describing a file upload set for a custom attribute diff --git a/src/api/resources/unstable/types/GroupContent.ts b/src/api/resources/unstable/types/GroupContent.ts index a7fb4506..68c5b320 100644 --- a/src/api/resources/unstable/types/GroupContent.ts +++ b/src/api/resources/unstable/types/GroupContent.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The Content of a Group. */ export interface GroupContent { /** The type of object - `group_content` . */ - type?: string; + type?: "group_content"; /** The name of the collection or section. */ name?: string; /** The description of the collection. Only available for collections. */ diff --git a/src/api/resources/unstable/types/GroupTranslatedContent.ts b/src/api/resources/unstable/types/GroupTranslatedContent.ts index 5df6fde7..c7b9933b 100644 --- a/src/api/resources/unstable/types/GroupTranslatedContent.ts +++ b/src/api/resources/unstable/types/GroupTranslatedContent.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * The Translated Content of an Group. The keys are the locale codes and the values are the translated content of the Group. */ export interface GroupTranslatedContent { /** The type of object - group_translated_content. */ - type?: string; + type?: "group_translated_content"; /** The content of the group in Arabic */ ar?: Intercom.unstable.GroupContent; /** The content of the group in Bulgarian */ diff --git a/src/api/resources/unstable/types/IntercomVersion.ts b/src/api/resources/unstable/types/IntercomVersion.ts deleted file mode 100644 index 921f8ae6..00000000 --- a/src/api/resources/unstable/types/IntercomVersion.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * Intercom API version.
By default, it's equal to the version set in the app package. - */ -export type IntercomVersion = - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; -export const IntercomVersion = { - One0: "1.0", - One1: "1.1", - One2: "1.2", - One3: "1.3", - One4: "1.4", - Two0: "2.0", - Two1: "2.1", - Two2: "2.2", - Two3: "2.3", - Two4: "2.4", - Two5: "2.5", - Two6: "2.6", - Two7: "2.7", - Two8: "2.8", - Two9: "2.9", - Two10: "2.10", - Two11: "2.11", - Unstable: "Unstable", -} as const; diff --git a/src/api/resources/unstable/types/IntercomVersionUnstable.ts b/src/api/resources/unstable/types/IntercomVersionUnstable.ts deleted file mode 100644 index 1bbcf600..00000000 --- a/src/api/resources/unstable/types/IntercomVersionUnstable.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * Unstable Intercom API version. Used for closed beta endpoints. - */ -export type IntercomVersionUnstable = "unstable"; diff --git a/src/api/resources/unstable/types/InternalArticleList.ts b/src/api/resources/unstable/types/InternalArticleList.ts new file mode 100644 index 00000000..5f5f6df8 --- /dev/null +++ b/src/api/resources/unstable/types/InternalArticleList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../../../index.js"; + +/** + * This will return a list of internal articles for the App. + */ +export interface InternalArticleList { + /** The type of the object - `list`. */ + type?: "list"; + pages?: Intercom.unstable.CursorPages; + /** A count of the total number of internal articles. */ + total_count?: number; + /** An array of Internal Article objects */ + data?: Intercom.unstable.InternalArticleListItem[]; +} diff --git a/src/api/resources/unstable/types/LinkedObject.ts b/src/api/resources/unstable/types/LinkedObject.ts index d7eaf21d..27fe77b5 100644 --- a/src/api/resources/unstable/types/LinkedObject.ts +++ b/src/api/resources/unstable/types/LinkedObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A linked conversation or ticket. @@ -11,16 +9,21 @@ export interface LinkedObject { /** The ID of the linked object */ id?: string; /** Category of the Linked Ticket Object. */ - category?: string; + category?: LinkedObject.Category; } export namespace LinkedObject { - /** - * ticket or conversation - */ - export type Type = "ticket" | "conversation"; + /** ticket or conversation */ export const Type = { Ticket: "ticket", Conversation: "conversation", } as const; + export type Type = (typeof Type)[keyof typeof Type]; + /** Category of the Linked Ticket Object. */ + export const Category = { + Customer: "Customer", + BackOffice: "Back-office", + Tracker: "Tracker", + } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/resources/unstable/types/LinkedObjectList.ts b/src/api/resources/unstable/types/LinkedObjectList.ts index 8a95b96a..b17171e1 100644 --- a/src/api/resources/unstable/types/LinkedObjectList.ts +++ b/src/api/resources/unstable/types/LinkedObjectList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing metadata about linked conversations and linked tickets. Up to 1000 can be returned. diff --git a/src/api/resources/unstable/types/MultipleFilterSearchRequest.ts b/src/api/resources/unstable/types/MultipleFilterSearchRequest.ts index 9f184175..4d834701 100644 --- a/src/api/resources/unstable/types/MultipleFilterSearchRequest.ts +++ b/src/api/resources/unstable/types/MultipleFilterSearchRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Search using Intercoms Search APIs with more than one filter. @@ -14,14 +12,12 @@ export interface MultipleFilterSearchRequest { } export namespace MultipleFilterSearchRequest { - /** - * An operator to allow boolean inspection between multiple fields. - */ - export type Operator = "AND" | "OR"; + /** An operator to allow boolean inspection between multiple fields. */ export const Operator = { And: "AND", Or: "OR", } as const; + export type Operator = (typeof Operator)[keyof typeof Operator]; export type Value = /** * Add mutiple filters. */ diff --git a/src/api/resources/unstable/types/NewsItemRequest.ts b/src/api/resources/unstable/types/NewsItemRequest.ts index 3e3791a2..9735b4fc 100644 --- a/src/api/resources/unstable/types/NewsItemRequest.ts +++ b/src/api/resources/unstable/types/NewsItemRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A News Item is a content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers. @@ -27,12 +25,10 @@ export interface NewsItemRequest { } export namespace NewsItemRequest { - /** - * News items will not be visible to your users in the assigned newsfeeds until they are set live. - */ - export type State = "draft" | "live"; + /** News items will not be visible to your users in the assigned newsfeeds until they are set live. */ export const State = { Draft: "draft", Live: "live", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/resources/unstable/types/NotFoundErrorBody.ts b/src/api/resources/unstable/types/NotFoundErrorBody.ts index 0893b81e..de9109f3 100644 --- a/src/api/resources/unstable/types/NotFoundErrorBody.ts +++ b/src/api/resources/unstable/types/NotFoundErrorBody.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface NotFoundErrorBody { /** The type is error.list */ diff --git a/src/api/resources/unstable/types/NoteList.ts b/src/api/resources/unstable/types/NoteList.ts index 162d648f..0f1e8fe4 100644 --- a/src/api/resources/unstable/types/NoteList.ts +++ b/src/api/resources/unstable/types/NoteList.ts @@ -1,11 +1,9 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** - * A paginated list of notes associated with a contact. + * A paginated list of notes associated with a contact or a company. */ export interface NoteList { /** String representing the object's type. Always has the value `list`. */ diff --git a/src/api/resources/unstable/types/OpenConversationRequest.ts b/src/api/resources/unstable/types/OpenConversationRequest.ts index 682699e3..b3e63714 100644 --- a/src/api/resources/unstable/types/OpenConversationRequest.ts +++ b/src/api/resources/unstable/types/OpenConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to open a conversation diff --git a/src/api/resources/unstable/types/OperatorWorkflowEvent.ts b/src/api/resources/unstable/types/OperatorWorkflowEvent.ts index 336b4885..df8629d3 100644 --- a/src/api/resources/unstable/types/OperatorWorkflowEvent.ts +++ b/src/api/resources/unstable/types/OperatorWorkflowEvent.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Contains details about name of the workflow for conversation part type operator_workflow_event. diff --git a/src/api/resources/unstable/types/PagesLink.ts b/src/api/resources/unstable/types/PagesLink.ts index 4dd36d75..59d698ff 100644 --- a/src/api/resources/unstable/types/PagesLink.ts +++ b/src/api/resources/unstable/types/PagesLink.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The majority of list resources in the API are paginated to allow clients to traverse data over multiple requests. diff --git a/src/api/resources/unstable/types/PaginatedResponse.ts b/src/api/resources/unstable/types/PaginatedResponse.ts index af97a516..64972bf9 100644 --- a/src/api/resources/unstable/types/PaginatedResponse.ts +++ b/src/api/resources/unstable/types/PaginatedResponse.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Paginated Response @@ -18,12 +16,10 @@ export interface PaginatedResponse { } export namespace PaginatedResponse { - /** - * The type of object - */ - export type Type = "list" | "conversation.list"; + /** The type of object */ export const Type = { List: "list", ConversationList: "conversation.list", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/PaginatedResponseDataItem.ts b/src/api/resources/unstable/types/PaginatedResponseDataItem.ts index fc09f5f8..65655304 100644 --- a/src/api/resources/unstable/types/PaginatedResponseDataItem.ts +++ b/src/api/resources/unstable/types/PaginatedResponseDataItem.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type PaginatedResponseDataItem = | Intercom.unstable.PaginatedResponseDataItem.NewsItem diff --git a/src/api/resources/unstable/types/PartAttachment.ts b/src/api/resources/unstable/types/PartAttachment.ts index 690152f9..3c01b778 100644 --- a/src/api/resources/unstable/types/PartAttachment.ts +++ b/src/api/resources/unstable/types/PartAttachment.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The file attached to a part diff --git a/src/api/resources/unstable/types/PhoneSwitch.ts b/src/api/resources/unstable/types/PhoneSwitch.ts index 3e6aad44..5fbeb892 100644 --- a/src/api/resources/unstable/types/PhoneSwitch.ts +++ b/src/api/resources/unstable/types/PhoneSwitch.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Phone Switch Response diff --git a/src/api/resources/unstable/types/QuickReplyOption.ts b/src/api/resources/unstable/types/QuickReplyOption.ts index 379777e5..8de2d400 100644 --- a/src/api/resources/unstable/types/QuickReplyOption.ts +++ b/src/api/resources/unstable/types/QuickReplyOption.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface QuickReplyOption { /** The text to display in this quick reply option. */ diff --git a/src/api/resources/unstable/types/Recipient.ts b/src/api/resources/unstable/types/Recipient.ts index 25e28bb9..194d11d0 100644 --- a/src/api/resources/unstable/types/Recipient.ts +++ b/src/api/resources/unstable/types/Recipient.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A recipient of a message @@ -13,12 +11,10 @@ export interface Recipient { } export namespace Recipient { - /** - * The role associated to the contact - `user` or `lead`. - */ - export type Type = "user" | "lead"; + /** The role associated to the contact - `user` or `lead`. */ export const Type = { User: "user", Lead: "lead", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/RedactConversationRequest.ts b/src/api/resources/unstable/types/RedactConversationRequest.ts index 968bb6af..f4845e8e 100644 --- a/src/api/resources/unstable/types/RedactConversationRequest.ts +++ b/src/api/resources/unstable/types/RedactConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type RedactConversationRequest = /** diff --git a/src/api/resources/unstable/types/Reference.ts b/src/api/resources/unstable/types/Reference.ts index b14f584f..7c9c82a3 100644 --- a/src/api/resources/unstable/types/Reference.ts +++ b/src/api/resources/unstable/types/Reference.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * reference to another object diff --git a/src/api/resources/unstable/types/RegisterFinVoiceCallRequest.ts b/src/api/resources/unstable/types/RegisterFinVoiceCallRequest.ts new file mode 100644 index 00000000..2fd07f21 --- /dev/null +++ b/src/api/resources/unstable/types/RegisterFinVoiceCallRequest.ts @@ -0,0 +1,25 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Register a Fin Voice call with Intercom + */ +export interface RegisterFinVoiceCallRequest { + /** Phone number in E.164 format for the call */ + phone_number: string; + /** External call identifier from the call provider */ + call_id: string; + /** Source of the call. Can be "five9", "zoom_phone", or defaults to "aws_connect" */ + source?: RegisterFinVoiceCallRequest.Source; + /** Additional metadata about the call */ + data?: Record; +} + +export namespace RegisterFinVoiceCallRequest { + /** Source of the call. Can be "five9", "zoom_phone", or defaults to "aws_connect" */ + export const Source = { + Five9: "five9", + ZoomPhone: "zoom_phone", + AwsConnect: "aws_connect", + } as const; + export type Source = (typeof Source)[keyof typeof Source]; +} diff --git a/src/api/resources/unstable/types/ReplyConversationRequestBody.ts b/src/api/resources/unstable/types/ReplyConversationRequestBody.ts index 261d4f73..3f05df15 100644 --- a/src/api/resources/unstable/types/ReplyConversationRequestBody.ts +++ b/src/api/resources/unstable/types/ReplyConversationRequestBody.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; export type ReplyConversationRequestBody = | Intercom.unstable.ContactReplyConversationRequest diff --git a/src/api/resources/unstable/types/SearchRequest.ts b/src/api/resources/unstable/types/SearchRequest.ts index 7dc82a61..796d8fc5 100644 --- a/src/api/resources/unstable/types/SearchRequest.ts +++ b/src/api/resources/unstable/types/SearchRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Search using Intercoms Search APIs. diff --git a/src/api/resources/unstable/types/SegmentList.ts b/src/api/resources/unstable/types/SegmentList.ts index 22f29cc3..7a3ae83b 100644 --- a/src/api/resources/unstable/types/SegmentList.ts +++ b/src/api/resources/unstable/types/SegmentList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of Segment Objects. The result may also have a pages object if the response is paginated. diff --git a/src/api/resources/unstable/types/SingleFilterSearchRequest.ts b/src/api/resources/unstable/types/SingleFilterSearchRequest.ts index 1d1e1613..58808cb4 100644 --- a/src/api/resources/unstable/types/SingleFilterSearchRequest.ts +++ b/src/api/resources/unstable/types/SingleFilterSearchRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Search using Intercoms Search APIs with a single filter. @@ -15,10 +13,7 @@ export interface SingleFilterSearchRequest { } export namespace SingleFilterSearchRequest { - /** - * The accepted operators you can use to define how you want to search for the value. - */ - export type Operator = "=" | "!=" | "IN" | "NIN" | "<" | ">"; + /** The accepted operators you can use to define how you want to search for the value. */ export const Operator = { EqualTo: "=", NotEquals: "!=", @@ -27,6 +22,7 @@ export namespace SingleFilterSearchRequest { LessThan: "<", GreaterThan: ">", } as const; + export type Operator = (typeof Operator)[keyof typeof Operator]; /** * The value that you want to search on. */ diff --git a/src/api/resources/unstable/types/SlaApplied.ts b/src/api/resources/unstable/types/SlaApplied.ts index 1a7049bb..3ea77f62 100644 --- a/src/api/resources/unstable/types/SlaApplied.ts +++ b/src/api/resources/unstable/types/SlaApplied.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The SLA Applied object contains the details for which SLA has been applied to this conversation. @@ -27,11 +25,11 @@ export namespace SlaApplied { * - `missed`: If there are any missed sla_events for the conversation and no canceled events. If there’s even a single missed sla event, the status will always be missed. A missed status is not applied when the SLA expires, only the next time a teammate replies. * - `active`: An SLA has been applied to a conversation, but has not yet been fulfilled. SLA status is active only if there are no “hit, “missed”, or “canceled” events. */ - export type SlaStatus = "hit" | "missed" | "cancelled" | "active"; export const SlaStatus = { Hit: "hit", Missed: "missed", Cancelled: "cancelled", Active: "active", } as const; + export type SlaStatus = (typeof SlaStatus)[keyof typeof SlaStatus]; } diff --git a/src/api/resources/unstable/types/SnoozeConversationRequest.ts b/src/api/resources/unstable/types/SnoozeConversationRequest.ts index 25429753..7e3e7061 100644 --- a/src/api/resources/unstable/types/SnoozeConversationRequest.ts +++ b/src/api/resources/unstable/types/SnoozeConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to snooze a conversation diff --git a/src/api/resources/unstable/types/SocialProfile.ts b/src/api/resources/unstable/types/SocialProfile.ts index 3598c433..5beba459 100644 --- a/src/api/resources/unstable/types/SocialProfile.ts +++ b/src/api/resources/unstable/types/SocialProfile.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A Social Profile allows you to label your contacts, companies, and conversations and list them using that Social Profile. diff --git a/src/api/resources/unstable/types/StartingAfterPaging.ts b/src/api/resources/unstable/types/StartingAfterPaging.ts index e2d31e3f..6fc82b73 100644 --- a/src/api/resources/unstable/types/StartingAfterPaging.ts +++ b/src/api/resources/unstable/types/StartingAfterPaging.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface StartingAfterPaging { /** The number of results to fetch per page. */ diff --git a/src/api/resources/unstable/types/SubscriptionTypeList.ts b/src/api/resources/unstable/types/SubscriptionTypeList.ts index 3aa55e5c..977b74d8 100644 --- a/src/api/resources/unstable/types/SubscriptionTypeList.ts +++ b/src/api/resources/unstable/types/SubscriptionTypeList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of subscription type objects. diff --git a/src/api/resources/unstable/types/TagCompanyRequest.ts b/src/api/resources/unstable/types/TagCompanyRequest.ts index 23231949..4f4affb5 100644 --- a/src/api/resources/unstable/types/TagCompanyRequest.ts +++ b/src/api/resources/unstable/types/TagCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a single company or a list of companies. diff --git a/src/api/resources/unstable/types/TagList.ts b/src/api/resources/unstable/types/TagList.ts index f42df4b4..5aba89c4 100644 --- a/src/api/resources/unstable/types/TagList.ts +++ b/src/api/resources/unstable/types/TagList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of tags objects in the workspace. diff --git a/src/api/resources/unstable/types/TagMultipleUsersRequest.ts b/src/api/resources/unstable/types/TagMultipleUsersRequest.ts index df2f72b2..fc697987 100644 --- a/src/api/resources/unstable/types/TagMultipleUsersRequest.ts +++ b/src/api/resources/unstable/types/TagMultipleUsersRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a list of users. diff --git a/src/api/resources/unstable/types/Tags.ts b/src/api/resources/unstable/types/Tags.ts index 980aba63..e968cf71 100644 --- a/src/api/resources/unstable/types/Tags.ts +++ b/src/api/resources/unstable/types/Tags.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of tags objects associated with a conversation diff --git a/src/api/resources/unstable/types/TeamList.ts b/src/api/resources/unstable/types/TeamList.ts index 6728f16f..c711e412 100644 --- a/src/api/resources/unstable/types/TeamList.ts +++ b/src/api/resources/unstable/types/TeamList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * This will return a list of team objects for the App. diff --git a/src/api/resources/unstable/types/TeamPriorityLevel.ts b/src/api/resources/unstable/types/TeamPriorityLevel.ts index b979fa1d..07d6bae5 100644 --- a/src/api/resources/unstable/types/TeamPriorityLevel.ts +++ b/src/api/resources/unstable/types/TeamPriorityLevel.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Admin priority levels for teams diff --git a/src/api/resources/unstable/types/TicketCustomAttributes.ts b/src/api/resources/unstable/types/TicketCustomAttributes.ts index 50eb281d..c3cb349e 100644 --- a/src/api/resources/unstable/types/TicketCustomAttributes.ts +++ b/src/api/resources/unstable/types/TicketCustomAttributes.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * An object containing the different attributes associated to the ticket as key-value pairs. For the default title and description attributes, the keys are `_default_title_` and `_default_description_`. diff --git a/src/api/resources/unstable/types/TicketList.ts b/src/api/resources/unstable/types/TicketList.ts index 0457d26e..b1545342 100644 --- a/src/api/resources/unstable/types/TicketList.ts +++ b/src/api/resources/unstable/types/TicketList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Tickets are how you track requests from your users. diff --git a/src/api/resources/unstable/types/TicketPartAuthor.ts b/src/api/resources/unstable/types/TicketPartAuthor.ts index 6dc2eb3b..e0ea7ff3 100644 --- a/src/api/resources/unstable/types/TicketPartAuthor.ts +++ b/src/api/resources/unstable/types/TicketPartAuthor.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The author that wrote or triggered the part. Can be a bot, admin, team or user. @@ -17,14 +15,12 @@ export interface TicketPartAuthor { } export namespace TicketPartAuthor { - /** - * The type of the author - */ - export type Type = "admin" | "bot" | "team" | "user"; + /** The type of the author */ export const Type = { Admin: "admin", Bot: "bot", Team: "team", User: "user", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/resources/unstable/types/TicketParts.ts b/src/api/resources/unstable/types/TicketParts.ts index f4847b22..95c99271 100644 --- a/src/api/resources/unstable/types/TicketParts.ts +++ b/src/api/resources/unstable/types/TicketParts.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of Ticket Part objects for each note and event in the ticket. There is a limit of 500 parts. diff --git a/src/api/resources/unstable/types/TicketReply.ts b/src/api/resources/unstable/types/TicketReply.ts index d1e66754..1a648076 100644 --- a/src/api/resources/unstable/types/TicketReply.ts +++ b/src/api/resources/unstable/types/TicketReply.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A Ticket Part representing a note, comment, or quick_reply on a ticket @@ -28,13 +26,11 @@ export interface TicketReply { } export namespace TicketReply { - /** - * Type of the part - */ - export type PartType = "note" | "comment" | "quick_reply"; + /** Type of the part */ export const PartType = { Note: "note", Comment: "comment", QuickReply: "quick_reply", } as const; + export type PartType = (typeof PartType)[keyof typeof PartType]; } diff --git a/src/api/resources/unstable/types/TicketRequestCustomAttributes.ts b/src/api/resources/unstable/types/TicketRequestCustomAttributes.ts index 6a3af042..6f54ade8 100644 --- a/src/api/resources/unstable/types/TicketRequestCustomAttributes.ts +++ b/src/api/resources/unstable/types/TicketRequestCustomAttributes.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The attributes set on the ticket. When setting the default title and description attributes, the attribute keys that should be used are `_default_title_` and `_default_description_`. When setting ticket type attributes of the list attribute type, the key should be the attribute name and the value of the attribute should be the list item id, obtainable by [listing the ticket type](ref:get_ticket-types). For example, if the ticket type has an attribute called `priority` of type `list`, the key should be `priority` and the value of the attribute should be the guid of the list item (e.g. `de1825a0-0164-4070-8ca6-13e22462fa7e`). diff --git a/src/api/resources/unstable/types/TicketStateList.ts b/src/api/resources/unstable/types/TicketStateList.ts index 7e3bfbe6..51e43516 100644 --- a/src/api/resources/unstable/types/TicketStateList.ts +++ b/src/api/resources/unstable/types/TicketStateList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of ticket states associated with a given ticket type. diff --git a/src/api/resources/unstable/types/TicketTypeAttribute.ts b/src/api/resources/unstable/types/TicketTypeAttribute.ts index 269e5f99..f634dd96 100644 --- a/src/api/resources/unstable/types/TicketTypeAttribute.ts +++ b/src/api/resources/unstable/types/TicketTypeAttribute.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Ticket type attribute, used to define each data field to be captured in a ticket. diff --git a/src/api/resources/unstable/types/TicketTypeAttributeList.ts b/src/api/resources/unstable/types/TicketTypeAttributeList.ts index ed242103..1466cda0 100644 --- a/src/api/resources/unstable/types/TicketTypeAttributeList.ts +++ b/src/api/resources/unstable/types/TicketTypeAttributeList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of attributes associated with a given ticket type. diff --git a/src/api/resources/unstable/types/TicketTypeList.ts b/src/api/resources/unstable/types/TicketTypeList.ts index 572085e6..7b839c67 100644 --- a/src/api/resources/unstable/types/TicketTypeList.ts +++ b/src/api/resources/unstable/types/TicketTypeList.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * A list of ticket types associated with a given workspace. diff --git a/src/api/resources/unstable/types/Translation.ts b/src/api/resources/unstable/types/Translation.ts index 9807efeb..3d656a16 100644 --- a/src/api/resources/unstable/types/Translation.ts +++ b/src/api/resources/unstable/types/Translation.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A translation object contains the localised details of a subscription type. diff --git a/src/api/resources/unstable/types/UntagCompanyRequest.ts b/src/api/resources/unstable/types/UntagCompanyRequest.ts index b970ebc4..09886bd1 100644 --- a/src/api/resources/unstable/types/UntagCompanyRequest.ts +++ b/src/api/resources/unstable/types/UntagCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a single company or a list of companies. diff --git a/src/api/resources/unstable/types/UpdateDataAttributeRequestBody.ts b/src/api/resources/unstable/types/UpdateDataAttributeRequestBody.ts new file mode 100644 index 00000000..6524ae99 --- /dev/null +++ b/src/api/resources/unstable/types/UpdateDataAttributeRequestBody.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * + */ +export type UpdateDataAttributeRequestBody = + | { + options: { + value?: string | undefined; + }[]; + } + | unknown; diff --git a/src/api/resources/unstable/types/UpdateTicketTypeRequestBody.ts b/src/api/resources/unstable/types/UpdateTicketTypeRequestBody.ts deleted file mode 100644 index 2eca441d..00000000 --- a/src/api/resources/unstable/types/UpdateTicketTypeRequestBody.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * The request payload for updating a ticket type. - * You can copy the `icon` property for your ticket type from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) - */ -export interface UpdateTicketTypeRequestBody { - /** The name of the ticket type. */ - name?: string; - /** The description of the ticket type. */ - description?: string; - /** Category of the Ticket Type. */ - category?: UpdateTicketTypeRequestBody.Category; - /** The icon of the ticket type. */ - icon?: string; - /** The archived status of the ticket type. */ - archived?: boolean; - /** Whether the tickets associated with this ticket type are intended for internal use only or will be shared with customers. This is currently a limited attribute. */ - is_internal?: boolean; -} - -export namespace UpdateTicketTypeRequestBody { - /** - * Category of the Ticket Type. - */ - export type Category = "Customer" | "Back-office" | "Tracker"; - export const Category = { - Customer: "Customer", - BackOffice: "Back-office", - Tracker: "Tracker", - } as const; -} diff --git a/src/api/resources/unstable/types/Visitor.ts b/src/api/resources/unstable/types/Visitor.ts index 272de16a..32dcf169 100644 --- a/src/api/resources/unstable/types/Visitor.ts +++ b/src/api/resources/unstable/types/Visitor.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../index"; +import type * as Intercom from "../../../index.js"; /** * Visitors are useful for representing anonymous people that have not yet been identified. They usually represent website visitors. Visitors are not visible in Intercom platform. The Visitors resource provides methods to fetch, update, convert and delete. diff --git a/src/api/resources/unstable/types/VisitorDeletedObject.ts b/src/api/resources/unstable/types/VisitorDeletedObject.ts index 6d2dcfd3..6a3cc196 100644 --- a/src/api/resources/unstable/types/VisitorDeletedObject.ts +++ b/src/api/resources/unstable/types/VisitorDeletedObject.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted diff --git a/src/api/resources/unstable/types/WhatsappMessageStatusList.ts b/src/api/resources/unstable/types/WhatsappMessageStatusList.ts index 71377c21..b1d0e8d8 100644 --- a/src/api/resources/unstable/types/WhatsappMessageStatusList.ts +++ b/src/api/resources/unstable/types/WhatsappMessageStatusList.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface WhatsappMessageStatusList { type: "list"; @@ -56,16 +54,14 @@ export namespace WhatsappMessageStatusList { } export namespace Item { - /** - * Current status of the message - */ - export type Status = "sent" | "delivered" | "read" | "failed"; + /** Current status of the message */ export const Status = { Sent: "sent", Delivered: "delivered", Read: "read", Failed: "failed", } as const; + export type Status = (typeof Status)[keyof typeof Status]; } } } diff --git a/src/api/resources/unstable/types/index.ts b/src/api/resources/unstable/types/index.ts index 129ed3c6..ff1cd877 100644 --- a/src/api/resources/unstable/types/index.ts +++ b/src/api/resources/unstable/types/index.ts @@ -1,145 +1,154 @@ -export * from "./NotFoundErrorBody"; -export * from "./Datetime"; -export * from "./ActivityLog"; -export * from "./ActivityLogList"; -export * from "./ActivityLogMetadata"; -export * from "./AddressableList"; -export * from "./AdminList"; -export * from "./AdminPriorityLevel"; -export * from "./AdminReplyConversationRequest"; -export * from "./AdminReplyTicketRequest"; -export * from "./AdminWithApp"; -export * from "./App"; -export * from "./ArticleContent"; -export * from "./ArticleList"; -export * from "./ArticleStatistics"; -export * from "./ArticleTranslatedContent"; -export * from "./AssignConversationRequest"; -export * from "./AwayStatusReason"; -export * from "./CloseConversationRequest"; -export * from "./CollectionList"; -export * from "./CompanyAttachedContacts"; -export * from "./CompanyAttachedSegments"; -export * from "./CompanyList"; -export * from "./CompanyScroll"; -export * from "./ContactAttachedCompanies"; -export * from "./ContactCompanies"; -export * from "./CompanyData"; -export * from "./ContactDeleted"; -export * from "./ContactList"; -export * from "./ContactLocation"; -export * from "./ContactNotes"; -export * from "./ContactReference"; -export * from "./ContactReplyBaseRequest"; -export * from "./ContactReplyConversationRequest"; -export * from "./ContactReplyEmailRequest"; -export * from "./ContactReplyIntercomUserIdRequest"; -export * from "./ContactReplyTicketEmailRequest"; -export * from "./ContactReplyTicketIntercomUserIdRequest"; -export * from "./ContactReplyTicketRequest"; -export * from "./ContactReplyTicketUserIdRequest"; -export * from "./ContactReplyUserIdRequest"; -export * from "./ContactSegments"; -export * from "./ContactSocialProfiles"; -export * from "./ContactSubscriptionTypes"; -export * from "./ContactTags"; -export * from "./ContactArchived"; -export * from "./ContactUnarchived"; -export * from "./ContactBlocked"; -export * from "./ContentSourcesList"; -export * from "./ConversationAttachmentFiles"; -export * from "./ConversationContacts"; -export * from "./ConversationDeleted"; -export * from "./ConversationFirstContactReply"; -export * from "./ConversationList"; -export * from "./ConversationPart"; -export * from "./ConversationPartAuthor"; -export * from "./ConversationParts"; -export * from "./ConversationPartMetadata"; -export * from "./ConversationRating"; -export * from "./ConversationResponseTime"; -export * from "./ConversationSource"; -export * from "./ConversationStatistics"; -export * from "./ConversationTeammates"; -export * from "./Recipient"; -export * from "./CreateOrUpdateTagRequest"; -export * from "./CreateTicketReplyWithCommentRequest"; -export * from "./CreateTicketRequestBody"; -export * from "./CursorPages"; -export * from "./CustomAttributes"; -export * from "./CustomObjectInstanceDeleted"; -export * from "./CustomObjectInstanceList"; -export * from "./CustomerRequest"; -export * from "./DataAttributeList"; -export * from "./DataEventList"; -export * from "./DataEventSummary"; -export * from "./DataEventSummaryItem"; -export * from "./DataExportCsv"; -export * from "./DeletedArticleObject"; -export * from "./DeletedCollectionObject"; -export * from "./DeletedCompanyObject"; -export * from "./DeletedObject"; -export * from "./EmailAddressHeader"; -export * from "./EmailMessageMetadata"; -export * from "./ConversationAttributeUpdatedByWorkflow"; -export * from "./ConversationAttributeUpdatedByAdmin"; -export * from "./CustomActionStarted"; -export * from "./CustomChannelAttribute"; -export * from "./CustomChannelBaseEvent"; -export * from "./CustomChannelContact"; -export * from "./CustomChannelNotificationResponse"; -export * from "./CustomActionFinished"; -export * from "./OperatorWorkflowEvent"; -export * from "./EventDetails"; -export * from "./Error_"; -export * from "./FileAttribute"; -export * from "./GroupContent"; -export * from "./GroupTranslatedContent"; -export * from "./IntercomVersion"; -export * from "./LinkedObject"; -export * from "./IntercomVersionUnstable"; -export * from "./LinkedObjectList"; -export * from "./WhatsappMessageStatusList"; -export * from "./MultipleFilterSearchRequest"; -export * from "./NewsItemRequest"; -export * from "./NoteList"; -export * from "./OpenConversationRequest"; -export * from "./PagesLink"; -export * from "./PaginatedResponseDataItem"; -export * from "./PaginatedResponse"; -export * from "./PartAttachment"; -export * from "./PhoneSwitch"; -export * from "./QuickReplyOption"; -export * from "./RedactConversationRequest"; -export * from "./Reference"; -export * from "./ReplyConversationRequestBody"; -export * from "./SearchRequest"; -export * from "./SegmentList"; -export * from "./SingleFilterSearchRequest"; -export * from "./SlaApplied"; -export * from "./SnoozeConversationRequest"; -export * from "./SocialProfile"; -export * from "./StartingAfterPaging"; -export * from "./SubscriptionTypeList"; -export * from "./TagCompanyRequest"; -export * from "./TagList"; -export * from "./TagMultipleUsersRequest"; -export * from "./Tags"; -export * from "./TeamList"; -export * from "./TeamPriorityLevel"; -export * from "./TicketCustomAttributes"; -export * from "./TicketList"; -export * from "./TicketPartAuthor"; -export * from "./TicketParts"; -export * from "./TicketReply"; -export * from "./TicketRequestCustomAttributes"; -export * from "./TicketStateList"; -export * from "./TicketTypeAttribute"; -export * from "./TicketTypeAttributeList"; -export * from "./TicketTypeList"; -export * from "./Translation"; -export * from "./UntagCompanyRequest"; -export * from "./UpdateArticleRequestBody"; -export * from "./UpdateTicketTypeRequestBody"; -export * from "./Visitor"; -export * from "./VisitorDeletedObject"; +export * from "./ActivityLog.js"; +export * from "./ActivityLogList.js"; +export * from "./ActivityLogMetadata.js"; +export * from "./AddressableList.js"; +export * from "./AdminList.js"; +export * from "./AdminPriorityLevel.js"; +export * from "./AdminReplyConversationRequest.js"; +export * from "./AdminReplyTicketRequest.js"; +export * from "./AdminWithApp.js"; +export * from "./AiCallResponse.js"; +export * from "./App.js"; +export * from "./ArticleContent.js"; +export * from "./ArticleList.js"; +export * from "./ArticleStatistics.js"; +export * from "./ArticleTranslatedContent.js"; +export * from "./AssignConversationRequest.js"; +export * from "./AwayStatusReason.js"; +export * from "./CallList.js"; +export * from "./CloseConversationRequest.js"; +export * from "./CollectionList.js"; +export * from "./CompanyAttachedContacts.js"; +export * from "./CompanyAttachedSegments.js"; +export * from "./CompanyData.js"; +export * from "./CompanyList.js"; +export * from "./CompanyScroll.js"; +export * from "./ContactArchived.js"; +export * from "./ContactAttachedCompanies.js"; +export * from "./ContactBlocked.js"; +export * from "./ContactCompanies.js"; +export * from "./ContactDeleted.js"; +export * from "./ContactList.js"; +export * from "./ContactLocation.js"; +export * from "./ContactNotes.js"; +export * from "./ContactReference.js"; +export * from "./ContactReplyBaseRequest.js"; +export * from "./ContactReplyConversationRequest.js"; +export * from "./ContactReplyEmailRequest.js"; +export * from "./ContactReplyIntercomUserIdRequest.js"; +export * from "./ContactReplyTicketEmailRequest.js"; +export * from "./ContactReplyTicketIntercomUserIdRequest.js"; +export * from "./ContactReplyTicketRequest.js"; +export * from "./ContactReplyTicketUserIdRequest.js"; +export * from "./ContactReplyUserIdRequest.js"; +export * from "./ContactSegments.js"; +export * from "./ContactSocialProfiles.js"; +export * from "./ContactSubscriptionTypes.js"; +export * from "./ContactTags.js"; +export * from "./ContactUnarchived.js"; +export * from "./ContentSourcesList.js"; +export * from "./ConversationAttachmentFiles.js"; +export * from "./ConversationAttributeUpdatedByAdmin.js"; +export * from "./ConversationAttributeUpdatedByWorkflow.js"; +export * from "./ConversationContacts.js"; +export * from "./ConversationDeleted.js"; +export * from "./ConversationFirstContactReply.js"; +export * from "./ConversationList.js"; +export * from "./ConversationPart.js"; +export * from "./ConversationPartAuthor.js"; +export * from "./ConversationPartMetadata.js"; +export * from "./ConversationParts.js"; +export * from "./ConversationRating.js"; +export * from "./ConversationResponseTime.js"; +export * from "./ConversationSource.js"; +export * from "./ConversationStatistics.js"; +export * from "./ConversationTeammates.js"; +export * from "./CreateArticleRequest.js"; +export * from "./CreateDataAttributeRequest.js"; +export * from "./CreateInternalArticleRequest.js"; +export * from "./CreateMessageRequest.js"; +export * from "./CreateOrUpdateCompanyRequest.js"; +export * from "./CreateOrUpdateTagRequest.js"; +export * from "./CreatePhoneSwitchRequest.js"; +export * from "./CreateTicketReplyWithCommentRequest.js"; +export * from "./CreateTicketRequestBody.js"; +export * from "./CreateTicketTypeRequest.js"; +export * from "./CursorPages.js"; +export * from "./CustomActionFinished.js"; +export * from "./CustomActionStarted.js"; +export * from "./CustomAttributes.js"; +export * from "./CustomChannelAttribute.js"; +export * from "./CustomChannelBaseEvent.js"; +export * from "./CustomChannelContact.js"; +export * from "./CustomChannelNotificationResponse.js"; +export * from "./CustomerRequest.js"; +export * from "./CustomObjectInstanceDeleted.js"; +export * from "./CustomObjectInstanceList.js"; +export * from "./DataAttributeList.js"; +export * from "./DataEventList.js"; +export * from "./DataEventSummary.js"; +export * from "./DataEventSummaryItem.js"; +export * from "./DataExportCsv.js"; +export * from "./Datetime.js"; +export * from "./DeletedArticleObject.js"; +export * from "./DeletedCollectionObject.js"; +export * from "./DeletedCompanyObject.js"; +export * from "./DeletedInternalArticleObject.js"; +export * from "./DeletedObject.js"; +export * from "./EmailAddressHeader.js"; +export * from "./EmailMessageMetadata.js"; +export * from "./Error_.js"; +export * from "./EventDetails.js"; +export * from "./FileAttribute.js"; +export * from "./GroupContent.js"; +export * from "./GroupTranslatedContent.js"; +export * from "./InternalArticleList.js"; +export * from "./LinkedObject.js"; +export * from "./LinkedObjectList.js"; +export * from "./MultipleFilterSearchRequest.js"; +export * from "./NewsItemRequest.js"; +export * from "./NoteList.js"; +export * from "./NotFoundErrorBody.js"; +export * from "./OpenConversationRequest.js"; +export * from "./OperatorWorkflowEvent.js"; +export * from "./PagesLink.js"; +export * from "./PaginatedResponse.js"; +export * from "./PaginatedResponseDataItem.js"; +export * from "./PartAttachment.js"; +export * from "./PhoneSwitch.js"; +export * from "./QuickReplyOption.js"; +export * from "./Recipient.js"; +export * from "./RedactConversationRequest.js"; +export * from "./Reference.js"; +export * from "./RegisterFinVoiceCallRequest.js"; +export * from "./ReplyConversationRequestBody.js"; +export * from "./SearchRequest.js"; +export * from "./SegmentList.js"; +export * from "./SingleFilterSearchRequest.js"; +export * from "./SlaApplied.js"; +export * from "./SnoozeConversationRequest.js"; +export * from "./SocialProfile.js"; +export * from "./StartingAfterPaging.js"; +export * from "./SubscriptionTypeList.js"; +export * from "./TagCompanyRequest.js"; +export * from "./TagList.js"; +export * from "./TagMultipleUsersRequest.js"; +export * from "./Tags.js"; +export * from "./TeamList.js"; +export * from "./TeamPriorityLevel.js"; +export * from "./TicketCustomAttributes.js"; +export * from "./TicketList.js"; +export * from "./TicketPartAuthor.js"; +export * from "./TicketParts.js"; +export * from "./TicketReply.js"; +export * from "./TicketRequestCustomAttributes.js"; +export * from "./TicketStateList.js"; +export * from "./TicketTypeAttribute.js"; +export * from "./TicketTypeAttributeList.js"; +export * from "./TicketTypeList.js"; +export * from "./Translation.js"; +export * from "./UntagCompanyRequest.js"; +export * from "./UpdateDataAttributeRequestBody.js"; +export * from "./Visitor.js"; +export * from "./VisitorDeletedObject.js"; +export * from "./WhatsappMessageStatusList.js"; diff --git a/src/api/resources/visitors/client/Client.ts b/src/api/resources/visitors/client/Client.ts index e18896e6..097e5ada 100644 --- a/src/api/resources/visitors/client/Client.ts +++ b/src/api/resources/visitors/client/Client.ts @@ -1,85 +1,35 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as environments from "../../../../environments"; -import * as core from "../../../../core"; -import * as Intercom from "../../../index"; -import urlJoin from "url-join"; -import * as errors from "../../../../errors/index"; +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import * as environments from "../../../../environments.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as Intercom from "../../../index.js"; -export declare namespace Visitors { - export interface Options { - environment?: core.Supplier; - /** Specify a custom URL to connect the client to. */ - baseUrl?: core.Supplier; - token?: core.Supplier; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - fetcher?: core.FetchFunction; - } +export declare namespace VisitorsClient { + export interface Options extends BaseClientOptions {} - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Additional headers to include in the request. */ - headers?: Record; - /** Override the Intercom-Version header */ - version?: - | "1.0" - | "1.1" - | "1.2" - | "1.3" - | "1.4" - | "2.0" - | "2.1" - | "2.2" - | "2.3" - | "2.4" - | "2.5" - | "2.6" - | "2.7" - | "2.8" - | "2.9" - | "2.10" - | "2.11" - | "Unstable"; - } + export interface RequestOptions extends BaseRequestOptions {} } /** * Everything about your Visitors */ -export class Visitors { - constructor(protected readonly _options: Visitors.Options = {}) {} +export class VisitorsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: VisitorsClient.Options = {}) { + this._options = normalizeClientOptionsWithAuth(options); + } /** * You can fetch the details of a single visitor. * * @param {Intercom.FindVisitorRequest} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} @@ -91,46 +41,43 @@ export class Visitors { */ public find( request: Intercom.FindVisitorRequest, - requestOptions?: Visitors.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: VisitorsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__find(request, requestOptions)); } private async __find( request: Intercom.FindVisitorRequest, - requestOptions?: Visitors.RequestOptions, - ): Promise> { + requestOptions?: VisitorsClient.RequestOptions, + ): Promise> { const { user_id: userId } = request; const _queryParams: Record = {}; - _queryParams["user_id"] = userId; + _queryParams.user_id = userId; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + headers: _headers, + queryParameters: { ..._queryParams, ...requestOptions?.queryParams }, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Visitor, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Visitor | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -151,21 +98,7 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling GET /visitors."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/visitors"); } /** @@ -176,14 +109,14 @@ export class Visitors { * **Option 2.** You can update a visitor by passing in the `id` of the visitor in the Request body. * * @param {Intercom.UpdateVisitorRequest} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @throws {@link Intercom.NotFoundError} * * @example * await client.visitors.update({ - * id: "667d61cc8a68186f43bafe95", + * id: "6762f30c1bb69f9f2193bc5e", * name: "Gareth Bale" * }) * @@ -195,43 +128,43 @@ export class Visitors { */ public update( request: Intercom.UpdateVisitorRequest, - requestOptions?: Visitors.RequestOptions, - ): core.HttpResponsePromise { + requestOptions?: VisitorsClient.RequestOptions, + ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); } private async __update( request: Intercom.UpdateVisitorRequest, - requestOptions?: Visitors.RequestOptions, - ): Promise> { + requestOptions?: VisitorsClient.RequestOptions, + ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { - return { data: _response.body as Intercom.Visitor, rawResponse: _response.rawResponse }; + return { data: _response.body as Intercom.Visitor | undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { @@ -252,21 +185,7 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling PUT /visitors."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/visitors"); } /** @@ -277,7 +196,7 @@ export class Visitors { * > If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers. * * @param {Intercom.MergeVisitorToContactRequest} request - * @param {Visitors.RequestOptions} requestOptions - Request-specific configuration. + * @param {VisitorsClient.RequestOptions} requestOptions - Request-specific configuration. * * @throws {@link Intercom.UnauthorizedError} * @@ -295,40 +214,40 @@ export class Visitors { */ public mergeToContact( request: Intercom.MergeVisitorToContactRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): core.HttpResponsePromise { return core.HttpResponsePromise.fromPromise(this.__mergeToContact(request, requestOptions)); } private async __mergeToContact( request: Intercom.MergeVisitorToContactRequest, - requestOptions?: Visitors.RequestOptions, + requestOptions?: VisitorsClient.RequestOptions, ): Promise> { + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + mergeOnlyDefinedHeaders({ "Intercom-Version": requestOptions?.version }), + requestOptions?.headers, + ); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.IntercomEnvironment.UsProduction, "visitors/convert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "intercom-client", - "X-Fern-SDK-Version": "6.4.0", - "User-Agent": "intercom-client/6.4.0", - "Intercom-Version": requestOptions?.version ?? this._options?.version ?? "2.11", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: _headers, contentType: "application/json", + queryParameters: requestOptions?.queryParams, requestType: "json", body: request, - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 20000, - maxRetries: requestOptions?.maxRetries, + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 20) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, }); if (_response.ok) { return { data: _response.body as Intercom.Contact, rawResponse: _response.rawResponse }; @@ -350,32 +269,6 @@ export class Visitors { } } - switch (_response.error.reason) { - case "non-json": - throw new errors.IntercomError({ - statusCode: _response.error.statusCode, - body: _response.error.rawBody, - rawResponse: _response.rawResponse, - }); - case "timeout": - throw new errors.IntercomTimeoutError("Timeout exceeded when calling POST /visitors/convert."); - case "unknown": - throw new errors.IntercomError({ - message: _response.error.errorMessage, - rawResponse: _response.rawResponse, - }); - } - } - - protected async _getAuthorizationHeader(): Promise { - const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["INTERCOM_API_KEY"]; - if (bearer == null) { - throw new errors.IntercomError({ - message: - "Please specify a bearer by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", - }); - } - - return `Bearer ${bearer}`; + return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/visitors/convert"); } } diff --git a/src/api/resources/visitors/client/index.ts b/src/api/resources/visitors/client/index.ts index 415726b7..195f9aa8 100644 --- a/src/api/resources/visitors/client/index.ts +++ b/src/api/resources/visitors/client/index.ts @@ -1 +1 @@ -export * from "./requests"; +export * from "./requests/index.js"; diff --git a/src/api/resources/visitors/client/requests/FindVisitorRequest.ts b/src/api/resources/visitors/client/requests/FindVisitorRequest.ts index 24bdf1b9..45db1e2d 100644 --- a/src/api/resources/visitors/client/requests/FindVisitorRequest.ts +++ b/src/api/resources/visitors/client/requests/FindVisitorRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example @@ -9,8 +7,6 @@ * } */ export interface FindVisitorRequest { - /** - * The user_id of the Visitor you want to retrieve. - */ + /** The user_id of the Visitor you want to retrieve. */ user_id: string; } diff --git a/src/api/resources/visitors/client/requests/MergeVisitorToContactRequest.ts b/src/api/resources/visitors/client/requests/MergeVisitorToContactRequest.ts index 85a59941..d469c38a 100644 --- a/src/api/resources/visitors/client/requests/MergeVisitorToContactRequest.ts +++ b/src/api/resources/visitors/client/requests/MergeVisitorToContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * @example diff --git a/src/api/resources/visitors/client/requests/index.ts b/src/api/resources/visitors/client/requests/index.ts index c03d0f15..f956dfd4 100644 --- a/src/api/resources/visitors/client/requests/index.ts +++ b/src/api/resources/visitors/client/requests/index.ts @@ -1,2 +1,2 @@ -export { type FindVisitorRequest } from "./FindVisitorRequest"; -export { type MergeVisitorToContactRequest } from "./MergeVisitorToContactRequest"; +export type { FindVisitorRequest } from "./FindVisitorRequest.js"; +export type { MergeVisitorToContactRequest } from "./MergeVisitorToContactRequest.js"; diff --git a/src/api/resources/visitors/index.ts b/src/api/resources/visitors/index.ts index 5ec76921..914b8c3c 100644 --- a/src/api/resources/visitors/index.ts +++ b/src/api/resources/visitors/index.ts @@ -1 +1 @@ -export * from "./client"; +export * from "./client/index.js"; diff --git a/src/api/types/ActionComponent.ts b/src/api/types/ActionComponent.ts deleted file mode 100644 index c97feba7..00000000 --- a/src/api/types/ActionComponent.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -export type ActionComponent = - | Intercom.ActionComponent.Sheet - | Intercom.ActionComponent.Url - | Intercom.ActionComponent.Submit; - -export namespace ActionComponent { - export interface Sheet extends Intercom.SheetActionComponent { - type: "sheet"; - } - - export interface Url extends Intercom.UrlActionComponent { - type: "url"; - } - - export interface Submit extends Intercom.SubmitActionComponent { - type: "submit"; - } -} diff --git a/src/api/types/ActivityLog.ts b/src/api/types/ActivityLog.ts index 80328f6f..ddf4451d 100644 --- a/src/api/types/ActivityLog.ts +++ b/src/api/types/ActivityLog.ts @@ -1,21 +1,19 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Activities performed by Admins. */ export interface ActivityLog { /** The id representing the activity. */ - id: string; + id?: string; /** Details about the Admin involved in the activity. */ - performed_by: ActivityLog.PerformedBy; + performed_by?: ActivityLog.PerformedBy; metadata?: Intercom.ActivityLogMetadata; /** The time the activity was created. */ created_at?: number; - activity_type: ActivityLog.ActivityType; + activity_type?: ActivityLog.ActivityType; /** A sentence or two describing the activity. */ activity_description?: string; } @@ -26,7 +24,7 @@ export namespace ActivityLog { */ export interface PerformedBy { /** String representing the object's type. Always has the value `admin`. */ - type?: "admin"; + type?: string; /** The id representing the admin. */ id?: string; /** The email of the admin. */ @@ -35,81 +33,16 @@ export namespace ActivityLog { ip?: string; } - export type ActivityType = - | "admin_assignment_limit_change" - | "admin_away_mode_change" - | "admin_deletion" - | "admin_deprovisioned" - | "admin_impersonation_end" - | "admin_impersonation_start" - | "admin_invite_change" - | "admin_invite_creation" - | "admin_invite_deletion" - | "admin_login_failure" - | "admin_login_success" - | "admin_logout" - | "admin_password_reset_request" - | "admin_password_reset_success" - | "admin_permission_change" - | "admin_provisioned" - | "admin_two_factor_auth_change" - | "admin_unauthorized_sign_in_method" - | "app_admin_join" - | "app_authentication_method_change" - | "app_data_deletion" - | "app_data_export" - | "app_google_sso_domain_change" - | "app_identity_verification_change" - | "app_name_change" - | "app_outbound_address_change" - | "app_package_installation" - | "app_package_token_regeneration" - | "app_package_uninstallation" - | "app_team_creation" - | "app_team_deletion" - | "app_team_membership_modification" - | "app_timezone_change" - | "app_webhook_creation" - | "app_webhook_deletion" - | "articles_in_messenger_enabled_change" - | "bulk_delete" - | "bulk_export" - | "campaign_deletion" - | "campaign_state_change" - | "conversation_part_deletion" - | "conversation_topic_change" - | "conversation_topic_creation" - | "conversation_topic_deletion" - | "help_center_settings_change" - | "inbound_conversations_change" - | "inbox_access_change" - | "message_deletion" - | "message_state_change" - | "messenger_look_and_feel_change" - | "messenger_search_required_change" - | "messenger_spaces_change" - | "office_hours_change" - | "role_change" - | "role_creation" - | "role_deletion" - | "ruleset_activation_title_preview" - | "ruleset_creation" - | "ruleset_deletion" - | "search_browse_enabled_change" - | "search_browse_required_change" - | "seat_change" - | "seat_revoke" - | "security_settings_change" - | "temporary_expectation_change" - | "upfront_email_collection_change" - | "welcome_message_change"; export const ActivityType = { - AdminAssignmentLimitChange: "admin_assignment_limit_change", + AdminConversationAssignmentLimitChange: "admin_conversation_assignment_limit_change", + AdminTicketAssignmentLimitChange: "admin_ticket_assignment_limit_change", AdminAwayModeChange: "admin_away_mode_change", AdminDeletion: "admin_deletion", AdminDeprovisioned: "admin_deprovisioned", AdminImpersonationEnd: "admin_impersonation_end", AdminImpersonationStart: "admin_impersonation_start", + AdminImpersonationConsentApproved: "admin_impersonation_consent_approved", + AdminImpersonationConsentRevoked: "admin_impersonation_consent_revoked", AdminInviteChange: "admin_invite_change", AdminInviteCreation: "admin_invite_creation", AdminInviteDeletion: "admin_invite_deletion", @@ -140,6 +73,7 @@ export namespace ActivityLog { AppWebhookCreation: "app_webhook_creation", AppWebhookDeletion: "app_webhook_deletion", ArticlesInMessengerEnabledChange: "articles_in_messenger_enabled_change", + AutomaticAwayModeSettingChange: "automatic_away_mode_setting_change", BulkDelete: "bulk_delete", BulkExport: "bulk_export", CampaignDeletion: "campaign_deletion", @@ -148,14 +82,22 @@ export namespace ActivityLog { ConversationTopicChange: "conversation_topic_change", ConversationTopicCreation: "conversation_topic_creation", ConversationTopicDeletion: "conversation_topic_deletion", + CustomAuthenticationTokenCreation: "custom_authentication_token_creation", HelpCenterSettingsChange: "help_center_settings_change", InboundConversationsChange: "inbound_conversations_change", InboxAccessChange: "inbox_access_change", + MacroCreation: "macro_creation", + MacroDeletion: "macro_deletion", + MacroUpdated: "macro_updated", + MaliciousDomainsSettingChange: "malicious_domains_setting_change", MessageDeletion: "message_deletion", MessageStateChange: "message_state_change", + MessengerApiSecretCreation: "messenger_api_secret_creation", + MessengerApiSecretDeletion: "messenger_api_secret_deletion", MessengerLookAndFeelChange: "messenger_look_and_feel_change", MessengerSearchRequiredChange: "messenger_search_required_change", MessengerSpacesChange: "messenger_spaces_change", + OauthTokenRevocation: "oauth_token_revocation", OfficeHoursChange: "office_hours_change", RoleChange: "role_change", RoleCreation: "role_creation", @@ -168,8 +110,23 @@ export namespace ActivityLog { SeatChange: "seat_change", SeatRevoke: "seat_revoke", SecuritySettingsChange: "security_settings_change", + StripInboundEmailLinksChange: "strip_inbound_email_links_change", TemporaryExpectationChange: "temporary_expectation_change", + TeamAssignmentLimitChange: "team_assignment_limit_change", + TrustedDomainsSettingChange: "trusted_domains_setting_change", + UnassignUnsnoozedAtCapacitySettingChange: "unassign_unsnoozed_at_capacity_setting_change", UpfrontEmailCollectionChange: "upfront_email_collection_change", + AllowedAttachmentFiletypesSettingChange: "allowed_attachment_filetypes_setting_change", + AttachUploadsInlineSettingChange: "attach_uploads_inline_setting_change", + TeammateGifsSettingChange: "teammate_gifs_setting_change", + UserCameraAttachmentsSettingChange: "user_camera_attachments_setting_change", + UserConversationAttachmentsSettingChange: "user_conversation_attachments_setting_change", + UserFileAttachmentsSettingChange: "user_file_attachments_setting_change", + UserGifsSettingChange: "user_gifs_setting_change", + UserMediaAttachmentsSettingChange: "user_media_attachments_setting_change", + UserVoiceNotesSettingChange: "user_voice_notes_setting_change", WelcomeMessageChange: "welcome_message_change", + WorkspaceDeletionRequest: "workspace_deletion_request", } as const; + export type ActivityType = (typeof ActivityType)[keyof typeof ActivityType]; } diff --git a/src/api/types/ActivityLogList.ts b/src/api/types/ActivityLogList.ts index ff4d942a..6a1253cc 100644 --- a/src/api/types/ActivityLogList.ts +++ b/src/api/types/ActivityLogList.ts @@ -1,16 +1,14 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A paginated list of activity logs. */ export interface ActivityLogList { /** String representing the object's type. Always has the value `activity_log.list`. */ - type: "activity_log.list"; + type?: string; pages?: Intercom.CursorPages; /** An array of activity logs */ - activity_logs: Intercom.ActivityLog[]; + activity_logs?: (Intercom.ActivityLog | undefined)[]; } diff --git a/src/api/types/ActivityLogMetadata.ts b/src/api/types/ActivityLogMetadata.ts index 4814d8e5..ed4bfcf2 100644 --- a/src/api/types/ActivityLogMetadata.ts +++ b/src/api/types/ActivityLogMetadata.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Additional data provided about Admin activity. @@ -24,4 +22,34 @@ export interface ActivityLogMetadata { update_by?: number; /** The name of the Admin who initiated the activity. */ update_by_name?: string; + /** The conversation assignment limit value for an admin. */ + conversation_assignment_limit?: number; + /** The ticket assignment limit value for an admin. */ + ticket_assignment_limit?: number; + /** Details about the team whose assignment limit was changed. */ + team?: ActivityLogMetadata.Team; + /** The team assignment limit value (null if limit was removed). */ + team_assignment_limit?: number; + /** Indicates if the setting is enabled or disabled. */ + enabled?: boolean; + /** The ID of the impersonation consent. */ + consent_id?: number; + /** The timestamp when the impersonation consent expires. */ + expired_at?: string; + /** The state of settings or values before the change. Structure varies by activity type. */ + before?: Record; + /** The state of settings or values after the change. Structure varies by activity type. */ + after?: Record; +} + +export namespace ActivityLogMetadata { + /** + * Details about the team whose assignment limit was changed. + */ + export interface Team { + /** The ID of the team. */ + id?: number; + /** The name of the team. */ + name?: string; + } } diff --git a/src/api/types/AddressableList.ts b/src/api/types/AddressableList.ts index 9fbf43ad..cbda5a63 100644 --- a/src/api/types/AddressableList.ts +++ b/src/api/types/AddressableList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A list used to access other resources from a parent model. */ export interface AddressableList { /** The addressable object type */ - type: string; + type?: string; /** The id of the addressable object */ - id: string; + id?: string; /** Url to get more company resources for this contact */ - url: string; + url?: string; } diff --git a/src/api/types/AdminList.ts b/src/api/types/AdminList.ts index 6c802a88..c504537d 100644 --- a/src/api/types/AdminList.ts +++ b/src/api/types/AdminList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of admins associated with a given workspace. */ export interface AdminList { /** String representing the object's type. Always has the value `admin.list`. */ - type: "admin.list"; + type?: string; /** A list of admins associated with a given workspace. */ - admins: Intercom.Admin[]; + admins?: (Intercom.Admin | undefined)[]; } diff --git a/src/api/types/AdminPriorityLevel.ts b/src/api/types/AdminPriorityLevel.ts index 659f95f2..1127dadf 100644 --- a/src/api/types/AdminPriorityLevel.ts +++ b/src/api/types/AdminPriorityLevel.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Admin priority levels for the team diff --git a/src/api/types/AdminReplyConversationRequest.ts b/src/api/types/AdminReplyConversationRequest.ts index be2e3a21..36982c2d 100644 --- a/src/api/types/AdminReplyConversationRequest.ts +++ b/src/api/types/AdminReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of an admin @@ -16,6 +14,8 @@ export interface AdminReplyConversationRequest { admin_id: string; /** The time the reply was created. If not provided, the current time will be used. */ created_at?: number; + /** The quick reply options to display to the end user. Must be present for quick_reply message types. */ + reply_options?: Intercom.QuickReplyOption[]; /** A list of image URLs that will be added as attachments. You can include up to 10 URLs. */ attachment_urls?: string[]; /** A list of files that will be added as attachments. You can include up to 10 files */ @@ -23,9 +23,10 @@ export interface AdminReplyConversationRequest { } export namespace AdminReplyConversationRequest { - export type MessageType = "comment" | "note"; export const MessageType = { Comment: "comment", Note: "note", + QuickReply: "quick_reply", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; } diff --git a/src/api/types/AdminReplyTicketRequest.ts b/src/api/types/AdminReplyTicketRequest.ts index dfc2ae57..3e2ac1ed 100644 --- a/src/api/types/AdminReplyTicketRequest.ts +++ b/src/api/types/AdminReplyTicketRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to reply on behalf of an admin @@ -21,12 +19,12 @@ export interface AdminReplyTicketRequest { } export namespace AdminReplyTicketRequest { - export type MessageType = "comment" | "note" | "quick_reply"; export const MessageType = { Comment: "comment", Note: "note", QuickReply: "quick_reply", } as const; + export type MessageType = (typeof MessageType)[keyof typeof MessageType]; export type ReplyOptions = ReplyOptions.Item[]; export namespace ReplyOptions { diff --git a/src/api/types/AdminWithApp.ts b/src/api/types/AdminWithApp.ts index 5f262869..8675a421 100644 --- a/src/api/types/AdminWithApp.ts +++ b/src/api/types/AdminWithApp.ts @@ -1,31 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Admins are the teammate accounts that have access to a workspace */ export interface AdminWithApp { /** String representing the object's type. Always has the value `admin`. */ - type: "admin"; + type?: string; /** The id representing the admin. */ - id: string; + id?: string; /** The name of the admin. */ - name: string; + name?: string; /** The email of the admin. */ - email: string; + email?: string; /** The job title of the admin. */ - job_title: string; + job_title?: string; /** Identifies if this admin is currently set in away mode. */ - away_mode_enabled: boolean; + away_mode_enabled?: boolean; /** Identifies if this admin is set to automatically reassign new conversations to the apps default inbox. */ - away_mode_reassign: boolean; + away_mode_reassign?: boolean; /** Identifies if this admin has a paid inbox seat to restrict/allow features that require them. */ - has_inbox_seat: boolean; + has_inbox_seat?: boolean; /** This is a list of ids of the teams that this admin is part of. */ - team_ids: number[]; + team_ids?: number[]; /** This object represents the avatar associated with the admin. */ avatar?: AdminWithApp.Avatar; /** Identifies if this admin's email is verified. */ @@ -40,7 +38,7 @@ export namespace AdminWithApp { */ export interface Avatar { /** This is a string that identifies the type of the object. It will always have the value `avatar`. */ - type?: "avatar"; + type?: string; /** This object represents the avatar associated with the admin. */ image_url?: string; } diff --git a/src/api/types/App.ts b/src/api/types/App.ts index 6506491c..67ce2d3c 100644 --- a/src/api/types/App.ts +++ b/src/api/types/App.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * App is a workspace on Intercom */ export interface App { /** */ - type: string; + type?: string; /** The id of the app. */ - id_code: string; + id_code?: string; /** The name of the app. */ - name: string; + name?: string; /** The Intercom region the app is located in. */ - region: string; + region?: string; /** The timezone of the region where the app is located. */ - timezone: string; + timezone?: string; /** When the app was created. */ - created_at: number; + created_at?: number; /** Whether or not the app uses identity verification. */ - identity_verification: boolean; + identity_verification?: boolean; } diff --git a/src/api/types/ArticleContent.ts b/src/api/types/ArticleContent.ts index dd73e27e..bccb5af5 100644 --- a/src/api/types/ArticleContent.ts +++ b/src/api/types/ArticleContent.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The Content of an Article. */ export interface ArticleContent { /** The type of object - `article_content` . */ - type: "article_content"; + type?: "article_content"; /** The title of the article. */ - title: string; + title?: string; /** The description of the article. */ - description: string; + description?: string; /** The body of the article. */ - body: string; + body?: string; /** The ID of the author of the article. */ - author_id: number; + author_id?: number; /** Whether the article is `published` or is a `draft` . */ - state: ArticleContent.State; + state?: ArticleContent.State; /** The time when the article was created (seconds). */ created_at?: number; /** The time when the article was last updated (seconds). */ @@ -27,12 +25,10 @@ export interface ArticleContent { } export namespace ArticleContent { - /** - * Whether the article is `published` or is a `draft` . - */ - export type State = "published" | "draft"; + /** Whether the article is `published` or is a `draft` . */ export const State = { Published: "published", Draft: "draft", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/types/ArticleList.ts b/src/api/types/ArticleList.ts index faf9ef31..02eb730b 100644 --- a/src/api/types/ArticleList.ts +++ b/src/api/types/ArticleList.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of articles for the App. */ export interface ArticleList { /** The type of the object - `list`. */ - type: "list"; + type?: "list"; pages?: unknown; /** A count of the total number of articles. */ - total_count: number; + total_count?: number; /** An array of Article objects */ - data: Intercom.ArticleListItem[]; + data?: Intercom.ArticleListItem[]; } diff --git a/src/api/types/ArticleStatistics.ts b/src/api/types/ArticleStatistics.ts index 00301798..36ea843e 100644 --- a/src/api/types/ArticleStatistics.ts +++ b/src/api/types/ArticleStatistics.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The statistics of an article. @@ -11,7 +9,7 @@ export interface ArticleStatistics { /** The number of total views the article has received. */ views: number; /** The number of conversations started from the article. */ - conversions: number; + conversions?: number; /** The number of total reactions the article has received. */ reactions: number; /** The percentage of happy reactions the article has received against other types of reaction. */ diff --git a/src/api/types/ArticleTranslatedContent.ts b/src/api/types/ArticleTranslatedContent.ts index 48f103b3..351d8148 100644 --- a/src/api/types/ArticleTranslatedContent.ts +++ b/src/api/types/ArticleTranslatedContent.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * The Translated Content of an Article. The keys are the locale codes and the values are the translated content of the article. diff --git a/src/api/types/AssignConversationRequest.ts b/src/api/types/AssignConversationRequest.ts index e3eef208..0e2e8ba8 100644 --- a/src/api/types/AssignConversationRequest.ts +++ b/src/api/types/AssignConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to assign a conversation @@ -16,9 +14,9 @@ export interface AssignConversationRequest { } export namespace AssignConversationRequest { - export type Type = "admin" | "team"; export const Type = { Admin: "admin", Team: "team", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/types/AwayStatusReason.ts b/src/api/types/AwayStatusReason.ts new file mode 100644 index 00000000..01eaf720 --- /dev/null +++ b/src/api/types/AwayStatusReason.ts @@ -0,0 +1,19 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface AwayStatusReason { + type?: string; + /** The unique identifier for the away status reason */ + id?: string; + /** The display text for the away status reason */ + label?: string; + /** The emoji associated with the status reason */ + emoji?: string; + /** The display order of the status reason */ + order?: number; + /** Whether the status reason has been soft deleted */ + deleted?: boolean; + /** The Unix timestamp when the status reason was created */ + created_at?: number; + /** The Unix timestamp when the status reason was last updated */ + updated_at?: number; +} diff --git a/src/api/types/ButtonComponent.ts b/src/api/types/ButtonComponent.ts deleted file mode 100644 index fa419ed8..00000000 --- a/src/api/types/ButtonComponent.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A button component is used to take an action by clicking a button. This can either: - * - [Trigger a submit request to be sent](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/submit-action) Inbox Messenger - * - [Open a link in a new page](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/url-action) Inbox Messenger - * - [Open a sheet](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/sheets-action) Messenger - */ -export interface ButtonComponent { - /** A unique identifier for the component. */ - id: string; - /** The text that will be rendered inside the button. */ - label: string; - /** This can be a Submit Action, URL Action, or Sheets Action. */ - action: Intercom.ActionComponent; - /** Styles the button. Default is 'primary'. */ - style?: ButtonComponent.Style; - /** Styles the button and prevents the action. Default is false. */ - disabled?: boolean; -} - -export namespace ButtonComponent { - /** - * Styles the button. Default is 'primary'. - */ - export type Style = "primary" | "secondary" | "link"; - export const Style = { - Primary: "primary", - Secondary: "secondary", - Link: "link", - } as const; -} diff --git a/src/api/types/CallList.ts b/src/api/types/CallList.ts new file mode 100644 index 00000000..ab4b49a4 --- /dev/null +++ b/src/api/types/CallList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * A paginated list of calls. + */ +export interface CallList { + /** String representing the object's type. Always has the value `list`. */ + type?: string; + /** A list of calls. */ + data?: Intercom.Call[]; + /** Total number of items available. */ + total_count?: number; + pages?: Intercom.CursorPages; +} diff --git a/src/api/types/CanvasObject.ts b/src/api/types/CanvasObject.ts deleted file mode 100644 index bb6161d3..00000000 --- a/src/api/types/CanvasObject.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * You have to respond to the majority of requests with a canvas object. This will tell us what UI to show for your app. - * - * A canvas can either be static (meaning we send you the next request only when an action takes place) or live (meaning we send you the next request when someone views the app). - * - * - A static canvas needs a ContentObject which will contain the components to show. - * - A live canvas needs a `content_url` which we we will make the Live Canvas requests to when the app is viewed. This is only possible for apps viewed or used in the Messenger. - */ -export interface CanvasObject { - /** The content object that will be shown as the UI of the app. Max Size is 64KB. */ - content: Intercom.ContentObject; - /** The URL which we make Live Canvas requests to. You must respond to these with a content object. Max size is 64KB. */ - content_url?: string; - /** Optional Stored Data that you want to be returned in the next sent request. Max Size is 64KB. */ - stored_data?: Record; -} diff --git a/src/api/types/CheckboxComponent.ts b/src/api/types/CheckboxComponent.ts deleted file mode 100644 index ddd79298..00000000 --- a/src/api/types/CheckboxComponent.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A checkbox component is used to capture multiple choices from as many options as you want to provide. You can submit the options by: - * - * - Using a ButtonComponent (which will submit all interactive components in the canvas) - * - * When a submit action takes place, the results are given in a hash with the `id` from the checkbox component used as the key and an array containing the `id` of each chosen option as the value. - */ -export interface CheckboxComponent { - /** A unique identifier for the component. */ - id: string; - /** The list of options. Minimum of 1. */ - option: Intercom.CheckboxOption[]; - /** The text shown above the options. */ - label: string; - /** The option's that are selected by default. */ - value?: string[]; - /** Styles the input. Default is `unsaved`. Prevent action with `saved`. */ - save_state?: CheckboxComponent.SaveState; - /** Styles all options and prevents the action. Default is false. Will be overridden if save_state is saved. */ - disabled?: boolean; -} - -export namespace CheckboxComponent { - /** - * Styles the input. Default is `unsaved`. Prevent action with `saved`. - */ - export type SaveState = "unsaved" | "saved" | "failed"; - export const SaveState = { - Unsaved: "unsaved", - Saved: "saved", - Failed: "failed", - } as const; -} diff --git a/src/api/types/CheckboxOption.ts b/src/api/types/CheckboxOption.ts deleted file mode 100644 index d33bb8fe..00000000 --- a/src/api/types/CheckboxOption.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A checkbox option component that can be selected. - */ -export interface CheckboxOption { - /** The type of component you are rendering. */ - type: "option"; - /** A unique identifier for the option. */ - id: string; - /** The text shown next to the checkbox. */ - text: string; - /** Styles the option and prevents the action. Default is false. */ - disabled?: boolean; -} diff --git a/src/api/types/CloseConversationRequest.ts b/src/api/types/CloseConversationRequest.ts index 56f0755e..0c75f0c3 100644 --- a/src/api/types/CloseConversationRequest.ts +++ b/src/api/types/CloseConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to close a conversation diff --git a/src/api/types/CollectionList.ts b/src/api/types/CollectionList.ts index 3260e2c6..d2c02975 100644 --- a/src/api/types/CollectionList.ts +++ b/src/api/types/CollectionList.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of Collections for the App. */ export interface CollectionList { /** The type of the object - `list`. */ - type: "list"; + type?: "list"; pages?: Intercom.OffsetPages; /** A count of the total number of collections. */ - total_count: number; + total_count?: number; /** An array of collection objects */ - data: Intercom.Collection[]; + data?: Intercom.Collection[]; } diff --git a/src/api/types/CompanyAttachedContacts.ts b/src/api/types/CompanyAttachedContacts.ts index a07697e9..8725ffd9 100644 --- a/src/api/types/CompanyAttachedContacts.ts +++ b/src/api/types/CompanyAttachedContacts.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of Contact Objects */ export interface CompanyAttachedContacts { /** The type of object - `list` */ - type: "list"; + type?: "list"; /** An array containing Contact Objects */ - data: Intercom.Contact[]; + data?: Intercom.Contact[]; /** The total number of contacts */ - total_count: number; + total_count?: number; pages?: Intercom.CursorPages; } diff --git a/src/api/types/CompanyAttachedSegments.ts b/src/api/types/CompanyAttachedSegments.ts index 12c36438..aa6941ca 100644 --- a/src/api/types/CompanyAttachedSegments.ts +++ b/src/api/types/CompanyAttachedSegments.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of Segment Objects */ export interface CompanyAttachedSegments { /** The type of object - `list` */ - type: "list"; + type?: "list"; /** An array containing Segment Objects */ - data: Intercom.Segment[]; + data?: Intercom.Segment[]; } diff --git a/src/api/types/CompanyData.ts b/src/api/types/CompanyData.ts new file mode 100644 index 00000000..29d3a559 --- /dev/null +++ b/src/api/types/CompanyData.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * An object containing data about the companies that a contact is associated with. + */ +export interface CompanyData { + /** The unique identifier for the company which is given by Intercom. */ + id?: string; + /** The type of the object. Always company. */ + type?: "company"; + /** The relative URL of the company. */ + url?: string; +} diff --git a/src/api/types/CompanyList.ts b/src/api/types/CompanyList.ts index 8d4eb5de..34851ae1 100644 --- a/src/api/types/CompanyList.ts +++ b/src/api/types/CompanyList.ts @@ -1,16 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of companies for the App. */ export interface CompanyList { + /** The type of object - `list`. */ + type?: "list"; pages?: Intercom.OffsetPages; /** The total number of companies. */ - total_count: number; + total_count?: number; /** An array containing Company Objects. */ - data: Intercom.Company[]; + data?: Intercom.Company[]; } diff --git a/src/api/types/CompanyScroll.ts b/src/api/types/CompanyScroll.ts index dd606955..1ba47ea4 100644 --- a/src/api/types/CompanyScroll.ts +++ b/src/api/types/CompanyScroll.ts @@ -1,16 +1,14 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Companies allow you to represent organizations using your product. Each company will have its own description and be associated with contacts. You can fetch, create, update and list companies. */ export interface CompanyScroll { /** The type of object - `list` */ - type: "list"; - data: Intercom.Company[]; + type?: "list"; + data?: Intercom.Company[]; pages?: Intercom.CursorPages; /** The total number of companies */ total_count?: number; diff --git a/src/api/types/Component.ts b/src/api/types/Component.ts deleted file mode 100644 index d2de298c..00000000 --- a/src/api/types/Component.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -export type Component = - | Intercom.Component.Button - | Intercom.Component.Checkbox - | Intercom.Component.Dropdown - | Intercom.Component.Input - | Intercom.Component.List - | Intercom.Component.SingleSelect - | Intercom.Component.Textarea - | Intercom.Component.DataTable - | Intercom.Component.Divider - | Intercom.Component.Image - | Intercom.Component.Spacer - | Intercom.Component.Text; - -export namespace Component { - export interface Button extends Intercom.ButtonComponent { - type: "button"; - } - - export interface Checkbox extends Intercom.CheckboxComponent { - type: "checkbox"; - } - - export interface Dropdown extends Intercom.DropdownComponent { - type: "dropdown"; - } - - export interface Input extends Intercom.InputComponent { - type: "input"; - } - - export interface List extends Intercom.ListComponent { - type: "list"; - } - - export interface SingleSelect extends Intercom.SingleSelectComponent { - type: "single-select"; - } - - export interface Textarea extends Intercom.TextAreaComponent { - type: "textarea"; - } - - export interface DataTable extends Intercom.DataTableComponent { - type: "data-table"; - } - - export interface Divider extends Intercom.DividerComponent { - type: "divider"; - } - - export interface Image extends Intercom.ImageComponent { - type: "image"; - } - - export interface Spacer extends Intercom.SpacerComponent { - type: "spacer"; - } - - export interface Text extends Intercom.TextComponent { - type: "text"; - } -} diff --git a/src/api/types/ConfigureRequest.ts b/src/api/types/ConfigureRequest.ts deleted file mode 100644 index b565bb2b..00000000 --- a/src/api/types/ConfigureRequest.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The first request we send will allow you to know the workspace where this is happening, the admin who will be configuring the app, and additional context such as where this will be added once complete. - * - * For subsequent requests whereby an admin has interacted with a component with a submit action, the request payload will contain the same details with `current_canvas`, `input_values` and the `component_id` also present. This allows you to understand what component the request came from, see what the value of any input was, action anything in your codebase, and then respond knowing what canvas was previously shown beforehand. - */ -export type ConfigureRequest = - | { - workspace_id: string; - admin: Intercom.Admin; - context: Intercom.Context; - } - | { - workspace_id: string; - workspace_region: string; - component_id: string; - admin: Intercom.Admin; - context: Intercom.Context; - current_canvas: Intercom.CanvasObject; - input_values: Record; - }; diff --git a/src/api/types/ConfigureResponse.ts b/src/api/types/ConfigureResponse.ts deleted file mode 100644 index 08ad2508..00000000 --- a/src/api/types/ConfigureResponse.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The response object returned when configuring an app. This will either: - * - A canvas object which will replace the previous canvas that was visible until the teammate interacted with your app - * - A results object which will end the configuration and trigger the initialize request to be sent. There will be a card_creation_options object in the payload showing your key-value pairs from the results object. - */ -export type ConfigureResponse = - | Intercom.ResultsResponse - | { - canvas: Intercom.CanvasObject; - }; diff --git a/src/api/types/ContactArchived.ts b/src/api/types/ContactArchived.ts index 882c4bec..53e83824 100644 --- a/src/api/types/ContactArchived.ts +++ b/src/api/types/ContactArchived.ts @@ -1,17 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; /** * archived contact object */ -export interface ContactArchived { - /** always contact */ - type: "contact"; - /** The unique identifier for the contact which is given by Intercom. */ - id: string; - /** The unique identifier for the contact which is provided by the Client. */ - external_id?: string; +export interface ContactArchived extends Intercom.ContactReference { /** Whether the contact is archived or not. */ - archived: boolean; + archived?: boolean; } diff --git a/src/api/types/ContactAttachedCompanies.ts b/src/api/types/ContactAttachedCompanies.ts index 3c73d361..6606054e 100644 --- a/src/api/types/ContactAttachedCompanies.ts +++ b/src/api/types/ContactAttachedCompanies.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of Company Objects */ export interface ContactAttachedCompanies { /** The type of object */ - type: "list"; + type?: "list"; /** An array containing Company Objects */ - companies: Intercom.Company[]; + companies?: Intercom.Company[]; /** The total number of companies associated to this contact */ - total_count: number; + total_count?: number; pages?: Intercom.PagesLink; } diff --git a/src/api/types/ContactBlocked.ts b/src/api/types/ContactBlocked.ts new file mode 100644 index 00000000..9c85baa7 --- /dev/null +++ b/src/api/types/ContactBlocked.ts @@ -0,0 +1,11 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * blocked contact object + */ +export interface ContactBlocked extends Intercom.ContactReference { + /** Always true. */ + blocked?: boolean; +} diff --git a/src/api/types/ContactCompanies.ts b/src/api/types/ContactCompanies.ts index 88980a31..8a3a13b0 100644 --- a/src/api/types/ContactCompanies.ts +++ b/src/api/types/ContactCompanies.ts @@ -1,21 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** - * An object containing companies meta data about the companies that a contact has. Up to 10 will be displayed here. Use the url to get more. + * An object with metadata about companies attached to a contact . Up to 10 will be displayed here. Use the url to get more. */ export interface ContactCompanies { - /** The type of object */ - type?: "list"; - /** An array containing Company Objects */ - data?: Intercom.ContactCompany[]; + /** An array of company data objects attached to the contact. */ + data?: Intercom.CompanyData[]; /** Url to get more company resources for this contact */ - url: string; - /** Int representing the total number of companyies attached to this contact */ - total_count: number; + url?: string; + /** Integer representing the total number of companies attached to this contact */ + total_count?: number; /** Whether there's more Addressable Objects to be viewed. If true, use the url to view all */ - has_more: boolean; + has_more?: boolean; } diff --git a/src/api/types/ContactCompany.ts b/src/api/types/ContactCompany.ts deleted file mode 100644 index cfe15a56..00000000 --- a/src/api/types/ContactCompany.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A reference to a company associated with a contact - */ -export interface ContactCompany { - /** The unique identifier for the company */ - id: string; - /** The type of the object */ - type: "company"; - /** URL to get the full company resource */ - url: string; -} diff --git a/src/api/types/ContactDeleted.ts b/src/api/types/ContactDeleted.ts index 12d7b0c6..6b047f65 100644 --- a/src/api/types/ContactDeleted.ts +++ b/src/api/types/ContactDeleted.ts @@ -1,17 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; /** * deleted contact object */ -export interface ContactDeleted { - /** always contact */ - type: "contact"; - /** The unique identifier for the contact which is given by Intercom. */ - id: string; - /** The unique identifier for the contact which is provided by the Client. */ - external_id?: string; +export interface ContactDeleted extends Intercom.ContactReference { /** Whether the contact is deleted or not. */ - deleted: boolean; + deleted?: boolean; } diff --git a/src/api/types/ContactList.ts b/src/api/types/ContactList.ts index fd188c1a..2fc8ab69 100644 --- a/src/api/types/ContactList.ts +++ b/src/api/types/ContactList.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Contacts are your users in Intercom. */ export interface ContactList { /** Always list */ - type: "list"; + type?: "list"; /** The list of contact objects */ - data: Intercom.Contact[]; + data?: Intercom.Contact[]; /** A count of the total number of objects. */ - total_count: number; + total_count?: number; pages?: Intercom.CursorPages; } diff --git a/src/api/types/ContactLocation.ts b/src/api/types/ContactLocation.ts index 2e079a7c..73f32530 100644 --- a/src/api/types/ContactLocation.ts +++ b/src/api/types/ContactLocation.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing location meta data about a Intercom contact. */ export interface ContactLocation { /** Always location */ - type: "location"; + type?: string; /** The country that the contact is located in */ country?: string; /** The overal region that the contact is located in */ diff --git a/src/api/types/ContactNotes.ts b/src/api/types/ContactNotes.ts index 56f4b090..77a34b6f 100644 --- a/src/api/types/ContactNotes.ts +++ b/src/api/types/ContactNotes.ts @@ -1,19 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * An object containing notes meta data about the notes that a contact has. Up to 10 will be displayed here. Use the url to get more. */ export interface ContactNotes { /** This object represents the notes attached to a contact. */ - data: Intercom.AddressableList[]; + data?: Intercom.AddressableList[]; /** Url to get more company resources for this contact */ - url: string; + url?: string; /** Int representing the total number of companyies attached to this contact */ - total_count: number; + total_count?: number; /** Whether there's more Addressable Objects to be viewed. If true, use the url to view all */ - has_more: boolean; + has_more?: boolean; } diff --git a/src/api/types/ContactReference.ts b/src/api/types/ContactReference.ts index 06dcf74e..6ff6080e 100644 --- a/src/api/types/ContactReference.ts +++ b/src/api/types/ContactReference.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * reference to contact object */ export interface ContactReference { /** always contact */ - type: "contact"; + type?: "contact"; /** The unique identifier for the contact which is given by Intercom. */ - id: string; + id?: string; /** The unique identifier for the contact which is provided by the Client. */ external_id?: string; } diff --git a/src/api/types/ContactReplyBaseRequest.ts b/src/api/types/ContactReplyBaseRequest.ts index 74f679c9..e6ebd102 100644 --- a/src/api/types/ContactReplyBaseRequest.ts +++ b/src/api/types/ContactReplyBaseRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface ContactReplyBaseRequest { message_type: "comment"; @@ -11,4 +9,19 @@ export interface ContactReplyBaseRequest { created_at?: number; /** A list of image URLs that will be added as attachments. You can include up to 10 URLs. */ attachment_urls?: string[]; + /** The quick reply selection the contact wishes to respond with. These map to buttons displayed in the Messenger UI if sent by a bot, or the reply options sent by an Admin via the API. */ + reply_options?: ContactReplyBaseRequest.ReplyOptions.Item[]; +} + +export namespace ContactReplyBaseRequest { + export type ReplyOptions = ReplyOptions.Item[]; + + export namespace ReplyOptions { + export interface Item { + /** The text of the chosen reply option. */ + text: string; + /** The unique identifier for the quick reply option selected. */ + uuid: string; + } + } } diff --git a/src/api/types/ContactReplyConversationRequest.ts b/src/api/types/ContactReplyConversationRequest.ts index 90c1aa5b..c0f18e11 100644 --- a/src/api/types/ContactReplyConversationRequest.ts +++ b/src/api/types/ContactReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type ContactReplyConversationRequest = | Intercom.ContactReplyIntercomUserIdRequest diff --git a/src/api/types/ContactReplyEmailRequest.ts b/src/api/types/ContactReplyEmailRequest.ts index 3f6b266b..3af33d96 100644 --- a/src/api/types/ContactReplyEmailRequest.ts +++ b/src/api/types/ContactReplyEmailRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `email` diff --git a/src/api/types/ContactReplyIntercomUserIdRequest.ts b/src/api/types/ContactReplyIntercomUserIdRequest.ts index 7de99551..4a3b3f1b 100644 --- a/src/api/types/ContactReplyIntercomUserIdRequest.ts +++ b/src/api/types/ContactReplyIntercomUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `intercom_user_id` diff --git a/src/api/types/ContactReplyTicketEmailRequest.ts b/src/api/types/ContactReplyTicketEmailRequest.ts index f1c5da4d..8baf8758 100644 --- a/src/api/types/ContactReplyTicketEmailRequest.ts +++ b/src/api/types/ContactReplyTicketEmailRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `email` diff --git a/src/api/types/ContactReplyTicketIntercomUserIdRequest.ts b/src/api/types/ContactReplyTicketIntercomUserIdRequest.ts index fb39fc05..712a6dfc 100644 --- a/src/api/types/ContactReplyTicketIntercomUserIdRequest.ts +++ b/src/api/types/ContactReplyTicketIntercomUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `intercom_user_id` diff --git a/src/api/types/ContactReplyTicketRequest.ts b/src/api/types/ContactReplyTicketRequest.ts index a285ecec..a8deae5d 100644 --- a/src/api/types/ContactReplyTicketRequest.ts +++ b/src/api/types/ContactReplyTicketRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type ContactReplyTicketRequest = | Intercom.ContactReplyTicketIntercomUserIdRequest diff --git a/src/api/types/ContactReplyTicketUserIdRequest.ts b/src/api/types/ContactReplyTicketUserIdRequest.ts index 475a259d..d754bd17 100644 --- a/src/api/types/ContactReplyTicketUserIdRequest.ts +++ b/src/api/types/ContactReplyTicketUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `user_id` diff --git a/src/api/types/ContactReplyUserIdRequest.ts b/src/api/types/ContactReplyUserIdRequest.ts index 919a6e28..c043f3cc 100644 --- a/src/api/types/ContactReplyUserIdRequest.ts +++ b/src/api/types/ContactReplyUserIdRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Payload of the request to reply on behalf of a contact using their `user_id` diff --git a/src/api/types/ContactSegments.ts b/src/api/types/ContactSegments.ts index cb9bc850..5099c19d 100644 --- a/src/api/types/ContactSegments.ts +++ b/src/api/types/ContactSegments.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of segments objects attached to a specific contact. */ export interface ContactSegments { /** The type of the object */ - type: "list"; + type?: "list"; /** Segment objects associated with the contact. */ - data: Intercom.Segment[]; + data?: Intercom.Segment[]; } diff --git a/src/api/types/ContactSocialProfiles.ts b/src/api/types/ContactSocialProfiles.ts index baf40a04..c61e7c62 100644 --- a/src/api/types/ContactSocialProfiles.ts +++ b/src/api/types/ContactSocialProfiles.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * An object containing social profiles that a contact has. */ export interface ContactSocialProfiles { /** A list of social profiles objects associated with the contact. */ - data: Intercom.SocialProfile[]; + data?: Intercom.SocialProfile[]; } diff --git a/src/api/types/ContactSubscriptionTypes.ts b/src/api/types/ContactSubscriptionTypes.ts index ff8cd650..358f4604 100644 --- a/src/api/types/ContactSubscriptionTypes.ts +++ b/src/api/types/ContactSubscriptionTypes.ts @@ -1,19 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * An object containing Subscription Types meta data about the SubscriptionTypes that a contact has. */ export interface ContactSubscriptionTypes { /** This object represents the subscriptions attached to a contact. */ - data: Intercom.AddressableList[]; + data?: Intercom.AddressableList[]; /** Url to get more subscription type resources for this contact */ - url: string; + url?: string; /** Int representing the total number of subscription types attached to this contact */ - total_count: number; + total_count?: number; /** Whether there's more Addressable Objects to be viewed. If true, use the url to view all */ - has_more: boolean; + has_more?: boolean; } diff --git a/src/api/types/ContactTags.ts b/src/api/types/ContactTags.ts index 6ed9fd6d..90b8cc0f 100644 --- a/src/api/types/ContactTags.ts +++ b/src/api/types/ContactTags.ts @@ -1,19 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * An object containing tags meta data about the tags that a contact has. Up to 10 will be displayed here. Use the url to get more. */ export interface ContactTags { /** This object represents the tags attached to a contact. */ - data: Intercom.AddressableList[]; + data?: Intercom.AddressableList[]; /** url to get more tag resources for this contact */ - url: string; + url?: string; /** Int representing the total number of tags attached to this contact */ - total_count: number; + total_count?: number; /** Whether there's more Addressable Objects to be viewed. If true, use the url to view all */ - has_more: boolean; + has_more?: boolean; } diff --git a/src/api/types/ContactUnarchived.ts b/src/api/types/ContactUnarchived.ts index 7940f0f1..5c84ff30 100644 --- a/src/api/types/ContactUnarchived.ts +++ b/src/api/types/ContactUnarchived.ts @@ -1,17 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; /** * unarchived contact object */ -export interface ContactUnarchived { - /** always contact */ - type: "contact"; - /** The unique identifier for the contact which is given by Intercom. */ - id: string; - /** The unique identifier for the contact which is provided by the Client. */ - external_id?: string; +export interface ContactUnarchived extends Intercom.ContactReference { /** Whether the contact is archived or not. */ - archived: boolean; + archived?: boolean; } diff --git a/src/api/types/ContentObject.ts b/src/api/types/ContentObject.ts deleted file mode 100644 index 127b8d88..00000000 --- a/src/api/types/ContentObject.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The content object is where you specify the UI of your app. You provide us with a set of `components` in a components array that we then render. - * - * The content object should usually be returned within the [canvas object](https://developers.intercom.com/docs/references/canvas-kit/responseobjects/canvas). If you're responding to a Live Canvas request however, then you should only respond with the content object. - */ -export interface ContentObject { - /** The list of components to be rendered. */ - components: Intercom.Component[]; -} diff --git a/src/api/types/ContentSourcesList.ts b/src/api/types/ContentSourcesList.ts index 28044b85..4af840d0 100644 --- a/src/api/types/ContentSourcesList.ts +++ b/src/api/types/ContentSourcesList.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export interface ContentSourcesList { - type: "content_source.list"; + type?: "content_source.list"; /** The total number of content sources used by AI Agent in the conversation. */ - total_count: number; + total_count?: number; /** The content sources used by AI Agent in the conversation. */ - content_sources: Intercom.ContentSource[]; + content_sources?: Intercom.ContentSource[]; } diff --git a/src/api/types/Context.ts b/src/api/types/Context.ts deleted file mode 100644 index c86d4597..00000000 --- a/src/api/types/Context.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * The context object provides additional details on where the app has been added (or is currently being used), what page the app is being used on, and information on the Messenger settings. This is in order for you give a fully customised experience based on the customers use case. - * - * If the `location` is `conversation` then you will also be given a `conversation_id`. If you need to use details about the conversation, then you have to use the `conversation_id` to [make a call to our Conversations API and retrieve the conversation object](https://developers.intercom.com/intercom-api-reference/reference#get-a-single-conversation). - */ -export interface Context { - /** The id of the conversation where the app is added or being used. */ - conversation_id?: number; - /** Where the app is added or the action took place. Can be either 'conversation', 'home', 'message', or 'operator'. */ - location?: Context.Location; - /** The default end-user language of the Messenger. Use to localise Messenger App content. */ - locale?: string; - /** The messengers action colour. Use in Sheets and Icons to make a Messenger App experience feel part of the host Messenger. */ - messenger_action_colour?: string; - /** The messengers background colour. Use in Sheets and Icons to make a Messenger App experience feel part of the host Messenger. */ - messenger_background_colour?: string; - /** The current page URL where the app is being used. */ - referrer?: string; -} - -export namespace Context { - /** - * Where the app is added or the action took place. Can be either 'conversation', 'home', 'message', or 'operator'. - */ - export type Location = "conversation" | "home" | "message" | "operator"; - export const Location = { - Conversation: "conversation", - Home: "home", - Message: "message", - Operator: "operator", - } as const; -} diff --git a/src/api/types/ConversationAttachmentFiles.ts b/src/api/types/ConversationAttachmentFiles.ts index df8323f1..f1a0b3e5 100644 --- a/src/api/types/ConversationAttachmentFiles.ts +++ b/src/api/types/ConversationAttachmentFiles.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Properties of the attachment files in a conversation part */ export interface ConversationAttachmentFiles { /** The content type of the file */ - content_type: string; + content_type?: string; /** The base64 encoded file data. */ - data: string; + data?: string; /** The name of the file. */ - name: string; + name?: string; } diff --git a/src/api/types/ConversationAttributeUpdatedByAdmin.ts b/src/api/types/ConversationAttributeUpdatedByAdmin.ts new file mode 100644 index 00000000..b44c2202 --- /dev/null +++ b/src/api/types/ConversationAttributeUpdatedByAdmin.ts @@ -0,0 +1,21 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains details about Custom Data Attributes (CDAs) that were modified by an admin (operator) for conversation part type conversation_attribute_updated_by_admin. + */ +export interface ConversationAttributeUpdatedByAdmin { + attribute?: ConversationAttributeUpdatedByAdmin.Attribute; + value?: ConversationAttributeUpdatedByAdmin.Value; +} + +export namespace ConversationAttributeUpdatedByAdmin { + export interface Attribute { + /** Name of the CDA updated */ + name?: string; + } + + export interface Value { + /** Value of the CDA updated */ + name?: string; + } +} diff --git a/src/api/types/ConversationAttributeUpdatedByWorkflow.ts b/src/api/types/ConversationAttributeUpdatedByWorkflow.ts new file mode 100644 index 00000000..e9e75f32 --- /dev/null +++ b/src/api/types/ConversationAttributeUpdatedByWorkflow.ts @@ -0,0 +1,27 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains details about the workflow that was triggered and any Custom Data Attributes (CDAs) that were modified during the workflow execution for conversation part type conversation_attribute_updated_by_workflow. + */ +export interface ConversationAttributeUpdatedByWorkflow { + workflow?: ConversationAttributeUpdatedByWorkflow.Workflow; + attribute?: ConversationAttributeUpdatedByWorkflow.Attribute; + value?: ConversationAttributeUpdatedByWorkflow.Value; +} + +export namespace ConversationAttributeUpdatedByWorkflow { + export interface Workflow { + /** Name of the workflow */ + name?: string; + } + + export interface Attribute { + /** Name of the CDA updated */ + name?: string; + } + + export interface Value { + /** Value of the CDA updated */ + name?: string; + } +} diff --git a/src/api/types/ConversationContacts.ts b/src/api/types/ConversationContacts.ts index c76e082d..860cd318 100644 --- a/src/api/types/ConversationContacts.ts +++ b/src/api/types/ConversationContacts.ts @@ -1,14 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * The list of contacts (users or leads) involved in this conversation. This will only contain one customer unless more were added via the group conversation feature. */ export interface ConversationContacts { - type: "contact.list"; + /** */ + type?: "contact.list"; /** The list of contacts (users or leads) involved in this conversation. This will only contain one customer unless more were added via the group conversation feature. */ - contacts: Intercom.ContactReference[]; + contacts?: Intercom.ContactReference[]; } diff --git a/src/api/types/ConversationDeleted.ts b/src/api/types/ConversationDeleted.ts new file mode 100644 index 00000000..e61823b9 --- /dev/null +++ b/src/api/types/ConversationDeleted.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * deleted conversation object + */ +export interface ConversationDeleted { + /** The unique identifier for the conversation. */ + id?: string; + /** always conversation */ + object?: "conversation"; + /** Whether the conversation is deleted or not. */ + deleted?: boolean; +} diff --git a/src/api/types/ConversationFirstContactReply.ts b/src/api/types/ConversationFirstContactReply.ts index efef9c6a..2085bd1e 100644 --- a/src/api/types/ConversationFirstContactReply.ts +++ b/src/api/types/ConversationFirstContactReply.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing information on the first users message. For a contact initiated message this will represent the users original message. */ export interface ConversationFirstContactReply { /** */ - created_at: number; + created_at?: number; /** */ - type: string; + type?: string; /** */ url?: string; } diff --git a/src/api/types/PaginatedConversationResponse.ts b/src/api/types/ConversationList.ts similarity index 59% rename from src/api/types/PaginatedConversationResponse.ts rename to src/api/types/ConversationList.ts index 4a319f84..4d0c74f3 100644 --- a/src/api/types/PaginatedConversationResponse.ts +++ b/src/api/types/ConversationList.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Conversations are how you can communicate with users in Intercom. They are created when a contact replies to an outbound message, or when one admin directly sends a message to a single contact. */ -export interface PaginatedConversationResponse { +export interface ConversationList { /** Always conversation.list */ - type: "conversation.list"; + type?: "conversation.list"; /** The list of conversation objects */ - conversations: Intercom.Conversation[]; + conversations?: Intercom.Conversation[]; /** A count of the total number of objects. */ - total_count: number; + total_count?: number; pages?: Intercom.CursorPages; } diff --git a/src/api/types/ConversationPart.ts b/src/api/types/ConversationPart.ts index 51fcf06a..2182ec66 100644 --- a/src/api/types/ConversationPart.ts +++ b/src/api/types/ConversationPart.ts @@ -1,34 +1,51 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A Conversation Part represents a message in the conversation. */ export interface ConversationPart { /** Always conversation_part */ - type: "conversation_part"; + type?: string; /** The id representing the conversation part. */ - id: string; + id?: string; /** The type of conversation part. */ - part_type: string; + part_type?: string; /** The message body, which may contain HTML. For Twitter, this will show a generic message regarding why the body is obscured. */ body?: string; /** The time the conversation part was created. */ - created_at: number; + created_at?: number; /** The last time the conversation part was updated. */ updated_at?: number; /** The time the user was notified with the conversation part. */ - notified_at: number; + notified_at?: number; /** The id of the admin that was assigned the conversation by this conversation_part (null if there has been no change in assignment.) */ assigned_to?: Intercom.Reference; - author: Intercom.ConversationPartAuthor; + author?: Intercom.ConversationPartAuthor; /** A list of attachments for the part. */ attachments?: Intercom.PartAttachment[]; /** The external id of the conversation part */ external_id?: string; /** Whether or not the conversation part has been redacted. */ - redacted: boolean; + redacted?: boolean; + email_message_metadata?: Intercom.EmailMessageMetadata; + metadata?: Intercom.ConversationPartMetadata; + /** Indicates the current state of conversation when the conversation part was created. */ + state?: ConversationPart.State; + /** A list of tags objects associated with the conversation part. */ + tags?: Intercom.TagBasic[]; + event_details?: Intercom.EventDetails; + /** The app package code if this part was created via API. null if the part was not created via API. */ + app_package_code?: string; +} + +export namespace ConversationPart { + /** Indicates the current state of conversation when the conversation part was created. */ + export const State = { + Open: "open", + Closed: "closed", + Snoozed: "snoozed", + } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/types/ConversationPartAuthor.ts b/src/api/types/ConversationPartAuthor.ts index 36495f34..3a17d751 100644 --- a/src/api/types/ConversationPartAuthor.ts +++ b/src/api/types/ConversationPartAuthor.ts @@ -1,17 +1,19 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The object who initiated the conversation, which can be a Contact, Admin or Team. Bots and campaigns send messages on behalf of Admins or Teams. For Twitter, this will be blank. */ export interface ConversationPartAuthor { /** The type of the author */ - type: string; + type?: string; /** The id of the author */ - id: string; + id?: string; /** The name of the author */ - name: string; + name?: string; /** The email of the author */ - email: string; + email?: string; + /** If this conversation part was sent by the AI Agent */ + from_ai_agent?: boolean; + /** If this conversation part body was generated by the AI Agent */ + is_ai_answer?: boolean; } diff --git a/src/api/types/ConversationPartMetadata.ts b/src/api/types/ConversationPartMetadata.ts new file mode 100644 index 00000000..34c17f40 --- /dev/null +++ b/src/api/types/ConversationPartMetadata.ts @@ -0,0 +1,24 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * Metadata for a conversation part + */ +export interface ConversationPartMetadata { + /** The quick reply options sent by the Admin or bot, presented in this conversation part. */ + quick_reply_options?: ConversationPartMetadata.QuickReplyOptions.Item[]; + /** The unique identifier for the quick reply option that was clicked by the end user. */ + quick_reply_uuid?: string; +} + +export namespace ConversationPartMetadata { + export type QuickReplyOptions = QuickReplyOptions.Item[]; + + export namespace QuickReplyOptions { + export interface Item extends Intercom.QuickReplyOption { + /** The translations for the quick reply option. */ + translations?: Record; + } + } +} diff --git a/src/api/types/ConversationParts.ts b/src/api/types/ConversationParts.ts index 2d0114df..ba6730f6 100644 --- a/src/api/types/ConversationParts.ts +++ b/src/api/types/ConversationParts.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of Conversation Part objects for each part message in the conversation. This is only returned when Retrieving a Conversation, and ignored when Listing all Conversations. There is a limit of 500 parts. */ export interface ConversationParts { /** */ - type: "conversation_part.list"; + type?: "conversation_part.list"; /** A list of Conversation Part objects for each part message in the conversation. This is only returned when Retrieving a Conversation, and ignored when Listing all Conversations. There is a limit of 500 parts. */ - conversation_parts: Intercom.ConversationPart[]; + conversation_parts?: Intercom.ConversationPart[]; /** */ - total_count: number; + total_count?: number; } diff --git a/src/api/types/ConversationRating.ts b/src/api/types/ConversationRating.ts index 96209e62..1ba83dbb 100644 --- a/src/api/types/ConversationRating.ts +++ b/src/api/types/ConversationRating.ts @@ -1,19 +1,19 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * The Conversation Rating object which contains information on the rating and/or remark added by a Contact and the Admin assigned to the conversation. */ export interface ConversationRating { /** The rating, between 1 and 5, for the conversation. */ - rating: number; + rating?: number; /** An optional field to add a remark to correspond to the number rating */ - remark: string; + remark?: string; /** The time the rating was requested in the conversation being rated. */ - created_at: number; - contact: Intercom.ContactReference; - teammate: Intercom.Reference; + created_at?: number; + /** The time the rating was last updated. */ + updated_at?: number; + contact?: Intercom.ContactReference; + teammate?: Intercom.Reference; } diff --git a/src/api/types/ConversationResponseTime.ts b/src/api/types/ConversationResponseTime.ts new file mode 100644 index 00000000..8c503679 --- /dev/null +++ b/src/api/types/ConversationResponseTime.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Details of first response time of assigned team in seconds. + */ +export interface ConversationResponseTime { + /** Id of the assigned team. */ + team_id?: number; + /** Name of the assigned Team, null if team does not exist, Unassigned if no team is assigned. */ + team_name?: string; + /** First response time of assigned team in seconds. */ + response_time?: number; +} diff --git a/src/api/types/ConversationSource.ts b/src/api/types/ConversationSource.ts index 7dcaf810..960f667c 100644 --- a/src/api/types/ConversationSource.ts +++ b/src/api/types/ConversationSource.ts @@ -1,47 +1,32 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** - * The Conversation Part that originated this conversation, which can be Contact, Admin, Campaign, Automated or Operator initiated. + * The type of the conversation part that started this conversation. Can be Contact, Admin, Campaign, Automated or Operator initiated. */ export interface ConversationSource { /** This includes conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. */ - type: ConversationSource.Type; + type?: ConversationSource.Type; /** The id representing the message. */ - id: string; + id?: string; /** The conversation's initiation type. Possible values are customer_initiated, campaigns_initiated (legacy campaigns), operator_initiated (Custom bot), automated (Series and other outbounds with dynamic audience message) and admin_initiated (fixed audience message, ticket initiated by an admin, group email). */ - delivered_as: string; + delivered_as?: string; /** Optional. The message subject. For Twitter, this will show a generic message regarding why the subject is obscured. */ - subject: string; + subject?: string; /** The message body, which may contain HTML. For Twitter, this will show a generic message regarding why the body is obscured. */ body?: string; - author: Intercom.ConversationPartAuthor; + author?: Intercom.ConversationPartAuthor; /** A list of attachments for the part. */ attachments?: Intercom.PartAttachment[]; /** The URL where the conversation was started. For Twitter, Email, and Bots, this will be blank. */ url?: string; /** Whether or not the source message has been redacted. Only applicable for contact initiated messages. */ - redacted: boolean; + redacted?: boolean; } export namespace ConversationSource { - /** - * This includes conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. - */ - export type Type = - | "conversation" - | "email" - | "facebook" - | "instagram" - | "phone_call" - | "phone_switch" - | "push" - | "sms" - | "twitter" - | "whatsapp"; + /** This includes conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. */ export const Type = { Conversation: "conversation", Email: "email", @@ -54,4 +39,5 @@ export namespace ConversationSource { Twitter: "twitter", Whatsapp: "whatsapp", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/types/ConversationStatistics.ts b/src/api/types/ConversationStatistics.ts index 18444e0d..999c99f5 100644 --- a/src/api/types/ConversationStatistics.ts +++ b/src/api/types/ConversationStatistics.ts @@ -1,13 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; /** * A Statistics object containing all information required for reporting, with timestamps and calculated metrics. */ export interface ConversationStatistics { /** */ - type: "conversation_statistics"; + type?: string; /** Duration until last assignment before first admin reply. In seconds. */ time_to_assignment?: number; /** Duration until first admin reply. Subtracts out of business hours. In seconds. */ @@ -44,4 +44,12 @@ export interface ConversationStatistics { count_assignments?: number; /** Total number of conversation parts. */ count_conversation_parts?: number; + /** An array of conversation response time objects */ + assigned_team_first_response_time_by_team?: Intercom.ConversationResponseTime[]; + /** An array of conversation response time objects within office hours */ + assigned_team_first_response_time_in_office_hours?: Intercom.ConversationResponseTime[]; + /** Time from conversation assignment to conversation close in seconds. */ + handling_time?: number; + /** Adjusted handling time for conversation in seconds. This is the active handling time excluding idle periods when teammates are not actively working on the conversation. */ + adjusted_handling_time?: number; } diff --git a/src/api/types/ConversationTeammates.ts b/src/api/types/ConversationTeammates.ts index c619dcb5..4f278e45 100644 --- a/src/api/types/ConversationTeammates.ts +++ b/src/api/types/ConversationTeammates.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * The list of teammates who participated in the conversation (wrote at least one conversation part). diff --git a/src/api/resources/articles/client/requests/CreateArticleRequest.ts b/src/api/types/CreateArticleRequest.ts similarity index 52% rename from src/api/resources/articles/client/requests/CreateArticleRequest.ts rename to src/api/types/CreateArticleRequest.ts index ef3fdc01..432c43aa 100644 --- a/src/api/resources/articles/client/requests/CreateArticleRequest.ts +++ b/src/api/types/CreateArticleRequest.ts @@ -1,39 +1,9 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../../../../index"; +import type * as Intercom from "../index.js"; /** - * @example - * { - * title: "Thanks for everything", - * description: "Description of the Article", - * body: "Body of the Article", - * author_id: 991267407, - * state: "published", - * parent_id: 145, - * parent_type: "collection", - * translated_content: { - * fr: { - * type: "article_content", - * title: "Merci pour tout", - * description: "Description de l'article", - * body: "Corps de l'article", - * author_id: 991267407, - * state: "published" - * } - * } - * } - * - * @example - * { - * title: "Thanks for everything", - * description: "Description of the Article", - * body: "Body of the Article", - * author_id: 1295, - * state: "published" - * } + * You can create an Article */ export interface CreateArticleRequest { /** The title of the article.For multilingual articles, this will be the title of the default language's content. */ @@ -54,20 +24,16 @@ export interface CreateArticleRequest { } export namespace CreateArticleRequest { - /** - * Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. - */ - export type State = "published" | "draft"; + /** Whether the article will be `published` or will be a `draft`. Defaults to draft. For multilingual articles, this will be the state of the default language's content. */ export const State = { Published: "published", Draft: "draft", } as const; - /** - * The type of parent, which can either be a `collection` or `section`. - */ - export type ParentType = "collection" | "section"; + export type State = (typeof State)[keyof typeof State]; + /** The type of parent, which can either be a `collection` or `section`. */ export const ParentType = { Collection: "collection", Section: "section", } as const; + export type ParentType = (typeof ParentType)[keyof typeof ParentType]; } diff --git a/src/api/types/CreateContactRequest.ts b/src/api/types/CreateContactRequest.ts index 9af417df..4067737b 100644 --- a/src/api/types/CreateContactRequest.ts +++ b/src/api/types/CreateContactRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload to create a contact diff --git a/src/api/types/CreateContactRequestTwo.ts b/src/api/types/CreateContactRequestTwo.ts index b3041530..06133b6b 100644 --- a/src/api/types/CreateContactRequestTwo.ts +++ b/src/api/types/CreateContactRequestTwo.ts @@ -1,5 +1,3 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type CreateContactRequestTwo = unknown; diff --git a/src/api/types/CreateDataAttributeRequest.ts b/src/api/types/CreateDataAttributeRequest.ts new file mode 100644 index 00000000..e2abd5d2 --- /dev/null +++ b/src/api/types/CreateDataAttributeRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * + */ +export type CreateDataAttributeRequest = + | { + data_type?: "options" | undefined; + options: { + value?: string | undefined; + }[]; + } + | { + data_type?: ("string" | "integer" | "float" | "boolean" | "datetime" | "date") | undefined; + }; diff --git a/src/api/types/CreateDataEventRequest.ts b/src/api/types/CreateDataEventRequest.ts index 85a0c1c5..b0502eab 100644 --- a/src/api/types/CreateDataEventRequest.ts +++ b/src/api/types/CreateDataEventRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * diff --git a/src/api/types/CreateDataEventRequestTwo.ts b/src/api/types/CreateDataEventRequestTwo.ts index 5eb4bbe5..d4d0d15e 100644 --- a/src/api/types/CreateDataEventRequestTwo.ts +++ b/src/api/types/CreateDataEventRequestTwo.ts @@ -1,5 +1,3 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type CreateDataEventRequestTwo = unknown; diff --git a/src/api/types/CreateInternalArticleRequest.ts b/src/api/types/CreateInternalArticleRequest.ts new file mode 100644 index 00000000..f971e918 --- /dev/null +++ b/src/api/types/CreateInternalArticleRequest.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can create an Internal Article + */ +export interface CreateInternalArticleRequest { + /** The title of the article. */ + title: string; + /** The content of the article. */ + body?: string; + /** The id of the author of the article. */ + author_id: number; + /** The id of the owner of the article. */ + owner_id: number; +} diff --git a/src/api/types/CreateMessageRequest.ts b/src/api/types/CreateMessageRequest.ts index 9434ec98..2e3bc5fb 100644 --- a/src/api/types/CreateMessageRequest.ts +++ b/src/api/types/CreateMessageRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * You can create a message @@ -50,14 +48,12 @@ export namespace CreateMessageRequest { } export namespace To { - /** - * The role associated to the contact - `user` or `lead`. - */ - export type Type = "user" | "lead"; + /** The role associated to the contact - `user` or `lead`. */ export const Type = { User: "user", Lead: "lead", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } @@ -101,14 +97,12 @@ export namespace CreateMessageRequest { } export namespace To { - /** - * The role associated to the contact - `user` or `lead`. - */ - export type Type = "user" | "lead"; + /** The role associated to the contact - `user` or `lead`. */ export const Type = { User: "user", Lead: "lead", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } } } diff --git a/src/api/types/CreateMessageRequestTwo.ts b/src/api/types/CreateMessageRequestTwo.ts deleted file mode 100644 index 1c075b32..00000000 --- a/src/api/types/CreateMessageRequestTwo.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -export type CreateMessageRequestTwo = unknown; diff --git a/src/api/resources/companies/client/requests/CreateOrUpdateCompanyRequest.ts b/src/api/types/CreateOrUpdateCompanyRequest.ts similarity index 82% rename from src/api/resources/companies/client/requests/CreateOrUpdateCompanyRequest.ts rename to src/api/types/CreateOrUpdateCompanyRequest.ts index 7024d304..136693c2 100644 --- a/src/api/resources/companies/client/requests/CreateOrUpdateCompanyRequest.ts +++ b/src/api/types/CreateOrUpdateCompanyRequest.ts @@ -1,17 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** - * @example - * { - * name: "my company", - * company_id: "company_remote_id", - * remote_created_at: 1374138000 - * } - * - * @example - * {} + * You can create or update a Company */ export interface CreateOrUpdateCompanyRequest { /** The name of the Company */ diff --git a/src/api/types/CreateOrUpdateTagRequest.ts b/src/api/types/CreateOrUpdateTagRequest.ts index a79ff2e0..7dfd1b3f 100644 --- a/src/api/types/CreateOrUpdateTagRequest.ts +++ b/src/api/types/CreateOrUpdateTagRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can create or update an existing tag. diff --git a/src/api/types/CreatePhoneSwitchRequest.ts b/src/api/types/CreatePhoneSwitchRequest.ts new file mode 100644 index 00000000..aae47b79 --- /dev/null +++ b/src/api/types/CreatePhoneSwitchRequest.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * You can create an phone switch + */ +export interface CreatePhoneSwitchRequest { + /** Phone number in E.164 format, that will receive the SMS to continue the conversation in the Messenger. */ + phone: string; + custom_attributes?: Intercom.CustomAttributes; +} diff --git a/src/api/types/CreateTicketReplyWithCommentRequest.ts b/src/api/types/CreateTicketReplyWithCommentRequest.ts index ad63ed81..31d1cccc 100644 --- a/src/api/types/CreateTicketReplyWithCommentRequest.ts +++ b/src/api/types/CreateTicketReplyWithCommentRequest.ts @@ -1,7 +1,5 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type CreateTicketReplyWithCommentRequest = Intercom.ContactReplyTicketRequest | Intercom.AdminReplyTicketRequest; diff --git a/src/api/types/CreateTicketRequest.ts b/src/api/types/CreateTicketRequest.ts deleted file mode 100644 index 272de2b7..00000000 --- a/src/api/types/CreateTicketRequest.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * You can create a Ticket - */ -export interface CreateTicketRequest { - /** The ID of the type of ticket you want to create */ - ticket_type_id: string; - /** The list of contacts (users or leads) affected by this ticket. Currently only one is allowed */ - contacts: CreateTicketRequest.Contacts.Item[]; - /** The ID of the company that the ticket is associated with. The ID that you set upon company creation. */ - company_id?: string; - /** The time the ticket was created. If not provided, the current time will be used. */ - created_at?: number; - ticket_attributes?: Intercom.TicketRequestCustomAttributes; -} - -export namespace CreateTicketRequest { - export type Contacts = Contacts.Item[]; - - export namespace Contacts { - export type Item = - | { - id: string; - } - | { - external_id: string; - } - | { - email: string; - }; - } -} diff --git a/src/api/types/CreateTicketRequestBody.ts b/src/api/types/CreateTicketRequestBody.ts new file mode 100644 index 00000000..9ec9fb5c --- /dev/null +++ b/src/api/types/CreateTicketRequestBody.ts @@ -0,0 +1,48 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can create a Ticket + */ +export interface CreateTicketRequestBody { + /** The ID of the type of ticket you want to create */ + ticket_type_id: string; + /** The list of contacts (users or leads) affected by this ticket. Currently only one is allowed */ + contacts: CreateTicketRequestBody.Contacts.Item[]; + /** + * The ID of the conversation you want to link to the ticket. Here are the valid ways of linking two tickets: + * - conversation | back-office ticket + * - customer tickets | non-shared back-office ticket + * - conversation | tracker ticket + * - customer ticket | tracker ticket + */ + conversation_to_link_id?: string; + /** The ID of the company that the ticket is associated with. The unique identifier for the company which is given by Intercom */ + company_id?: string; + /** The time the ticket was created. If not provided, the current time will be used. */ + created_at?: number; + assignment?: CreateTicketRequestBody.Assignment; +} + +export namespace CreateTicketRequestBody { + export type Contacts = Contacts.Item[]; + + export namespace Contacts { + export type Item = + | { + id: string; + } + | { + external_id: string; + } + | { + email: string; + }; + } + + export interface Assignment { + /** The ID of the admin to which the ticket is assigned. If not provided, the ticket will be unassigned. */ + admin_assignee_id?: string; + /** The ID of the team to which the ticket is assigned. If not provided, the ticket will be unassigned. */ + team_assignee_id?: string; + } +} diff --git a/src/api/types/CreateTicketTypeRequest.ts b/src/api/types/CreateTicketTypeRequest.ts new file mode 100644 index 00000000..eebc72da --- /dev/null +++ b/src/api/types/CreateTicketTypeRequest.ts @@ -0,0 +1,28 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * The request payload for creating a ticket type. + * You can copy the `icon` property for your ticket type from [Twemoji Cheatsheet](https://twemoji-cheatsheet.vercel.app/) + */ +export interface CreateTicketTypeRequest { + /** The name of the ticket type. */ + name: string; + /** The description of the ticket type. */ + description?: string; + /** Category of the Ticket Type. */ + category?: CreateTicketTypeRequest.Category; + /** The icon of the ticket type. */ + icon?: string; + /** Whether the tickets associated with this ticket type are intended for internal use only or will be shared with customers. This is currently a limited attribute. */ + is_internal?: boolean; +} + +export namespace CreateTicketTypeRequest { + /** Category of the Ticket Type. */ + export const Category = { + Customer: "Customer", + BackOffice: "Back-office", + Tracker: "Tracker", + } as const; + export type Category = (typeof Category)[keyof typeof Category]; +} diff --git a/src/api/types/CurrentCanvas.ts b/src/api/types/CurrentCanvas.ts deleted file mode 100644 index d985ac0f..00000000 --- a/src/api/types/CurrentCanvas.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The current canvas that was most recently showing before the request was sent. This object mirrors the same format as the Canvas Object. - */ -export interface CurrentCanvas { - /** The canvas object representing the current canvas state. */ - current_canvas: Intercom.CanvasObject; -} diff --git a/src/api/types/CursorPages.ts b/src/api/types/CursorPages.ts index db27af6a..4245c670 100644 --- a/src/api/types/CursorPages.ts +++ b/src/api/types/CursorPages.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Cursor-based pagination is a technique used in the Intercom API to navigate through large amounts of data. @@ -10,7 +8,7 @@ import * as Intercom from "../index"; */ export interface CursorPages { /** the type of object `pages`. */ - type: "pages"; + type?: "pages"; /** The current page */ page?: number; next?: Intercom.StartingAfterPaging; diff --git a/src/api/types/CustomActionFinished.ts b/src/api/types/CustomActionFinished.ts new file mode 100644 index 00000000..54471392 --- /dev/null +++ b/src/api/types/CustomActionFinished.ts @@ -0,0 +1,26 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains details about final status of the completed action for conversation part type custom_action_finished. + */ +export interface CustomActionFinished { + action?: CustomActionFinished.Action; +} + +export namespace CustomActionFinished { + export interface Action { + /** Name of the action */ + name?: string; + /** Status of the action */ + result?: Action.Result; + } + + export namespace Action { + /** Status of the action */ + export const Result = { + Success: "success", + Failed: "failed", + } as const; + export type Result = (typeof Result)[keyof typeof Result]; + } +} diff --git a/src/api/types/CustomActionStarted.ts b/src/api/types/CustomActionStarted.ts new file mode 100644 index 00000000..18114f6c --- /dev/null +++ b/src/api/types/CustomActionStarted.ts @@ -0,0 +1,15 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains details about name of the action that was initiated for conversation part type custom_action_started. + */ +export interface CustomActionStarted { + action?: CustomActionStarted.Action; +} + +export namespace CustomActionStarted { + export interface Action { + /** Name of the action */ + name?: string; + } +} diff --git a/src/api/types/CustomAttributes.ts b/src/api/types/CustomAttributes.ts index ebc3d771..6fd00ee3 100644 --- a/src/api/types/CustomAttributes.ts +++ b/src/api/types/CustomAttributes.ts @@ -1,8 +1,12 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; /** * Custom data set for this data. */ -export type CustomAttributes = Record; +export type CustomAttributes = Record; + +export namespace CustomAttributes { + export type Value = string | number | Intercom.Datetime | Intercom.CustomObjectInstanceList; +} diff --git a/src/api/types/CustomChannelAttribute.ts b/src/api/types/CustomChannelAttribute.ts new file mode 100644 index 00000000..9afa1dd6 --- /dev/null +++ b/src/api/types/CustomChannelAttribute.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface CustomChannelAttribute { + /** Identifier for the attribute being collected. */ + id: string; + /** Value provided by the user for the attribute. */ + value: string; +} diff --git a/src/api/types/CustomChannelBaseEvent.ts b/src/api/types/CustomChannelBaseEvent.ts new file mode 100644 index 00000000..dcf9e00e --- /dev/null +++ b/src/api/types/CustomChannelBaseEvent.ts @@ -0,0 +1,11 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +export interface CustomChannelBaseEvent { + /** Unique identifier for the event. */ + event_id: string; + /** Identifier for the conversation in your application. */ + external_conversation_id: string; + contact: Intercom.CustomChannelContact; +} diff --git a/src/api/types/CustomChannelContact.ts b/src/api/types/CustomChannelContact.ts new file mode 100644 index 00000000..7d11a83c --- /dev/null +++ b/src/api/types/CustomChannelContact.ts @@ -0,0 +1,21 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface CustomChannelContact { + /** Type of contact, must be "user" or "lead". */ + type: CustomChannelContact.Type; + /** External identifier for the contact. Intercom will take care of the mapping of your external_id with our internal ones so you don't have to worry about it. */ + external_id: string; + /** Name of the contact. Required for user type. */ + name?: string; + /** Email address of the contact. Required for user type. */ + email?: string; +} + +export namespace CustomChannelContact { + /** Type of contact, must be "user" or "lead". */ + export const Type = { + User: "user", + Lead: "lead", + } as const; + export type Type = (typeof Type)[keyof typeof Type]; +} diff --git a/src/api/types/CustomChannelNotificationResponse.ts b/src/api/types/CustomChannelNotificationResponse.ts new file mode 100644 index 00000000..238b883d --- /dev/null +++ b/src/api/types/CustomChannelNotificationResponse.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface CustomChannelNotificationResponse { + /** The external conversation ID provided in the notification request */ + external_conversation_id: string; + /** The Intercom conversation ID mapped to the external conversation ID */ + conversation_id: string; + /** The external contact ID provided in the notification request */ + external_contact_id: string; + /** The Intercom contact ID mapped to the external contact ID */ + contact_id: string; +} diff --git a/src/api/types/CustomObjectInstanceDeleted.ts b/src/api/types/CustomObjectInstanceDeleted.ts new file mode 100644 index 00000000..4c14eba9 --- /dev/null +++ b/src/api/types/CustomObjectInstanceDeleted.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * deleted custom object instance object + */ +export interface CustomObjectInstanceDeleted { + /** The unique identifier of the Custom Object type that defines the structure of the Custom Object instance. */ + object?: string; + /** The Intercom defined id representing the Custom Object instance. */ + id?: string; + /** Whether the Custom Object instance is deleted or not. */ + deleted?: boolean; +} diff --git a/src/api/types/CustomObjectInstanceList.ts b/src/api/types/CustomObjectInstanceList.ts new file mode 100644 index 00000000..f537ed2d --- /dev/null +++ b/src/api/types/CustomObjectInstanceList.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * The list of associated custom object instances for a given reference attribute on the parent object. + */ +export interface CustomObjectInstanceList { + type?: string; + /** The list of associated custom object instances for a given reference attribute on the parent object. */ + instances?: (Intercom.CustomObjectInstance | undefined)[]; +} diff --git a/src/api/types/CustomerRequest.ts b/src/api/types/CustomerRequest.ts index 6ede7a3d..d86d11c7 100644 --- a/src/api/types/CustomerRequest.ts +++ b/src/api/types/CustomerRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type CustomerRequest = | { diff --git a/src/api/types/DataAttributeList.ts b/src/api/types/DataAttributeList.ts index 860b9192..6fb01c20 100644 --- a/src/api/types/DataAttributeList.ts +++ b/src/api/types/DataAttributeList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of all data attributes belonging to a workspace for contacts, companies or conversations. */ export interface DataAttributeList { /** The type of the object */ - type: "list"; + type?: "list"; /** A list of data attributes */ - data: Intercom.DataAttribute[]; + data?: Intercom.DataAttribute[]; } diff --git a/src/api/types/DataEventList.ts b/src/api/types/DataEventList.ts index 90c73811..2a68082a 100644 --- a/src/api/types/DataEventList.ts +++ b/src/api/types/DataEventList.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of data events for the App. */ export interface DataEventList { /** The type of the object */ - type: "event.list"; + type?: "event.list"; /** A list of data events */ - events: Intercom.DataEvent[]; + events?: Intercom.DataEvent[]; /** Pagination */ pages?: DataEventList.Pages; } diff --git a/src/api/types/DataEventSummary.ts b/src/api/types/DataEventSummary.ts index df7d10fd..e2791b1f 100644 --- a/src/api/types/DataEventSummary.ts +++ b/src/api/types/DataEventSummary.ts @@ -1,21 +1,19 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a summary of data events for the App. */ export interface DataEventSummary { /** The type of the object */ - type: "event.summary"; + type?: "event.summary"; /** The email address of the user */ - email: string; + email?: string; /** The Intercom user ID of the user */ - intercom_user_id: string; + intercom_user_id?: string; /** The user ID of the user */ - user_id: string; + user_id?: string; /** A summary of data events */ - events: Intercom.DataEventSummaryItem[]; + events: (Intercom.DataEventSummaryItem | undefined)[]; } diff --git a/src/api/types/DataEventSummaryItem.ts b/src/api/types/DataEventSummaryItem.ts index 581a8e54..9f0d9192 100644 --- a/src/api/types/DataEventSummaryItem.ts +++ b/src/api/types/DataEventSummaryItem.ts @@ -1,19 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * This will return a summary of a data event for the App. */ export interface DataEventSummaryItem { /** The name of the event */ - name: string; + name?: string; /** The first time the event was sent */ - first: string; + first?: string; /** The last time the event was sent */ - last: string; + last?: string; /** The number of times the event was sent */ - count: number; + count?: number; /** The description of the event */ description?: string; } diff --git a/src/api/types/DataExportCsv.ts b/src/api/types/DataExportCsv.ts index 22f1bf3c..8c268f7e 100644 --- a/src/api/types/DataExportCsv.ts +++ b/src/api/types/DataExportCsv.ts @@ -1,29 +1,27 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A CSV output file */ export interface DataExportCsv { /** The user_id of the user who was sent the message. */ - user_id: string; + user_id?: string; /** The external_user_id of the user who was sent the message */ user_external_id?: string; /** The company ID of the user in relation to the message that was sent. Will return -1 if no company is present. */ - company_id: string; + company_id?: string; /** The users email who was sent the message. */ - email: string; + email?: string; /** The full name of the user receiving the message */ - name: string; + name?: string; /** The id of the message. */ - ruleset_id: string; + ruleset_id?: string; /** The specific content that was received. In an A/B test each version has its own Content ID. */ - content_id: string; + content_id?: string; /** Email, Chat, Post etc. */ - content_type: string; + content_type?: string; /** The title of the content you see in your Intercom workspace. */ - content_title: string; + content_title?: string; /** As you edit content we record new versions. This ID can help you determine which version of a piece of content that was received. */ ruleset_version_id?: string; /** ID for this receipt. Will be included with any related stats in other files to identify this specific delivery of a message. */ diff --git a/src/api/types/DataTableComponent.ts b/src/api/types/DataTableComponent.ts deleted file mode 100644 index 64e38560..00000000 --- a/src/api/types/DataTableComponent.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A data-table component is used for rendering a table of key-value pairs. For Messenger, text will wrap around on multiple lines. For Inbox and Frame (ie. Configure) views, we will truncate and use tooltips on hover if the text overflows. - */ -export interface DataTableComponent { - /** The items that will be rendered in the data-table. */ - items: Intercom.DataTableItem[]; -} diff --git a/src/api/types/DataTableItem.ts b/src/api/types/DataTableItem.ts deleted file mode 100644 index f0b9e04f..00000000 --- a/src/api/types/DataTableItem.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A field-value pair component for use in a data table. - */ -export interface DataTableItem { - /** The type of component you are rendering. */ - type: "field-value"; - /** The text of the key in your key-value pair. */ - field: string; - /** The text of the value in your key-value pair. */ - value: string; -} diff --git a/src/api/types/Datetime.ts b/src/api/types/Datetime.ts new file mode 100644 index 00000000..63964732 --- /dev/null +++ b/src/api/types/Datetime.ts @@ -0,0 +1,9 @@ +// This file was auto-generated by Fern from our API Definition. + +export type Datetime = + /** + * A date and time following the ISO8601 notation. */ + | string + /** + * A date and time as UNIX timestamp notation. */ + | number; diff --git a/src/api/types/DeletedArticleObject.ts b/src/api/types/DeletedArticleObject.ts index b792af78..5667114c 100644 --- a/src/api/types/DeletedArticleObject.ts +++ b/src/api/types/DeletedArticleObject.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted */ export interface DeletedArticleObject { /** The unique identifier for the article which you provided in the URL. */ - id: string; + id?: string; /** The type of object which was deleted. - article */ - object: "article"; + object?: "article"; /** Whether the article was deleted successfully or not. */ - deleted: boolean; + deleted?: boolean; } diff --git a/src/api/types/DeletedCollectionObject.ts b/src/api/types/DeletedCollectionObject.ts index f01ce8e6..4d03d936 100644 --- a/src/api/types/DeletedCollectionObject.ts +++ b/src/api/types/DeletedCollectionObject.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted */ export interface DeletedCollectionObject { /** The unique identifier for the collection which you provided in the URL. */ - id: string; + id?: string; /** The type of object which was deleted. - `collection` */ - object: "collection"; + object?: "collection"; /** Whether the collection was deleted successfully or not. */ - deleted: boolean; + deleted?: boolean; } diff --git a/src/api/types/DeletedCompanyObject.ts b/src/api/types/DeletedCompanyObject.ts index e3252c3c..b5ee6cf6 100644 --- a/src/api/types/DeletedCompanyObject.ts +++ b/src/api/types/DeletedCompanyObject.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted */ export interface DeletedCompanyObject { /** The unique identifier for the company which is given by Intercom. */ - id: string; + id?: string; /** The type of object which was deleted. - `company` */ - object: "company"; + object?: "company"; /** Whether the company was deleted successfully or not. */ - deleted: boolean; + deleted?: boolean; } diff --git a/src/api/types/DeletedInternalArticleObject.ts b/src/api/types/DeletedInternalArticleObject.ts new file mode 100644 index 00000000..47d5060b --- /dev/null +++ b/src/api/types/DeletedInternalArticleObject.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Response returned when an object is deleted + */ +export interface DeletedInternalArticleObject { + /** The unique identifier for the internal article which you provided in the URL. */ + id?: string; + /** The type of object which was deleted. - internal_article */ + object?: "internal_article"; + /** Whether the internal article was deleted successfully or not. */ + deleted?: boolean; +} diff --git a/src/api/types/DeletedObject.ts b/src/api/types/DeletedObject.ts index f0bcc357..a22b393b 100644 --- a/src/api/types/DeletedObject.ts +++ b/src/api/types/DeletedObject.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted */ export interface DeletedObject { /** The unique identifier for the news item which you provided in the URL. */ - id: string; + id?: string; /** The type of object which was deleted - news-item. */ - object: "news-item"; + object?: "news-item"; /** Whether the news item was deleted successfully or not. */ - deleted: boolean; + deleted?: boolean; } diff --git a/src/api/types/DividerComponent.ts b/src/api/types/DividerComponent.ts deleted file mode 100644 index 7b37b3c8..00000000 --- a/src/api/types/DividerComponent.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A divider component is used to separate components with a line. - */ -export interface DividerComponent { - /** A unique identifier for the component. */ - id?: string; - /** Disables a component's margin-bottom of 10px. */ - bottom_margin?: "none"; -} diff --git a/src/api/types/DropdownComponent.ts b/src/api/types/DropdownComponent.ts deleted file mode 100644 index f0d36aaa..00000000 --- a/src/api/types/DropdownComponent.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A dropdown component is used to capture a choice from the options that you provide. - * - * When submitted, the dropdown choices are returned in a hash with the id from the dropdown component used as the key and the id from the chosen option as the value. - */ -export interface DropdownComponent { - /** A unique identifier for the component. */ - id: string; - /** The list of options. Can provide 2 to 10. */ - options: Intercom.DropdownOption[]; - /** The text shown above the dropdown. */ - label?: string; - /** The option that is selected by default. */ - value?: string; - /** Styles all options and prevents the action. Default is `unsaved`. Will be overridden if `save_state` is `saved`. */ - save_state?: DropdownComponent.SaveState; - /** Styles all options and prevents the action. Default is false. Will be overridden if save_state is saved. */ - disabled?: boolean; -} - -export namespace DropdownComponent { - /** - * Styles all options and prevents the action. Default is `unsaved`. Will be overridden if `save_state` is `saved`. - */ - export type SaveState = "unsaved" | "saved" | "failed"; - export const SaveState = { - Unsaved: "unsaved", - Saved: "saved", - Failed: "failed", - } as const; -} diff --git a/src/api/types/DropdownOption.ts b/src/api/types/DropdownOption.ts deleted file mode 100644 index 17bd18e5..00000000 --- a/src/api/types/DropdownOption.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A dropdown option component that can be selected. - */ -export interface DropdownOption { - /** The type of component you are rendering. */ - type: "option"; - /** A unique identifier for the option. */ - id: string; - /** The text shown within this option. */ - text: string; - /** Styles the option and prevents the action. Default is false. */ - disabled?: boolean; -} diff --git a/src/api/types/EmailAddressHeader.ts b/src/api/types/EmailAddressHeader.ts new file mode 100644 index 00000000..7e8d234d --- /dev/null +++ b/src/api/types/EmailAddressHeader.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains data for an email address header for a conversation part that was sent as an email. + */ +export interface EmailAddressHeader { + /** The type of email address header */ + type?: string; + /** The email address */ + email_address?: string; + /** The name associated with the email address */ + name?: string; +} diff --git a/src/api/types/EmailMessageMetadata.ts b/src/api/types/EmailMessageMetadata.ts new file mode 100644 index 00000000..815571b7 --- /dev/null +++ b/src/api/types/EmailMessageMetadata.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * Contains metadata if the message was sent as an email + */ +export interface EmailMessageMetadata { + /** The subject of the email */ + subject?: string; + /** A list of an email address headers. */ + email_address_headers?: Intercom.EmailAddressHeader[]; +} diff --git a/src/api/types/Error_.ts b/src/api/types/Error_.ts index a9df7613..5a4a39f0 100644 --- a/src/api/types/Error_.ts +++ b/src/api/types/Error_.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The API will return an Error List for a failed request, which will contain one or more Error objects. diff --git a/src/api/types/Event.ts b/src/api/types/Event.ts deleted file mode 100644 index b6bbe375..00000000 --- a/src/api/types/Event.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * The event object enables Intercom to know more about the actions that took place in your app. Currently, you can only tell us when an app's flow has been completed. - */ -export interface Event { - /** What action took place. The only value currently accepted is `completed`. */ - type: "completed"; -} diff --git a/src/api/types/EventDetails.ts b/src/api/types/EventDetails.ts new file mode 100644 index 00000000..6db41ca1 --- /dev/null +++ b/src/api/types/EventDetails.ts @@ -0,0 +1,10 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +export type EventDetails = + | Intercom.ConversationAttributeUpdatedByWorkflow + | Intercom.ConversationAttributeUpdatedByAdmin + | Intercom.CustomActionStarted + | Intercom.CustomActionFinished + | Intercom.OperatorWorkflowEvent; diff --git a/src/api/types/FileAttribute.ts b/src/api/types/FileAttribute.ts index e33ed602..b8fab036 100644 --- a/src/api/types/FileAttribute.ts +++ b/src/api/types/FileAttribute.ts @@ -1,22 +1,20 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The value describing a file upload set for a custom attribute */ export interface FileAttribute { - type: string; + type?: string; /** The name of the file */ - name: string; + name?: string; /** The url of the file. This is a temporary URL and will expire after 30 minutes. */ - url: string; + url?: string; /** The type of file */ - content_type: string; + content_type?: string; /** The size of the file in bytes */ - filesize: number; + filesize?: number; /** The width of the file in pixels, if applicable */ - width: number; + width?: number; /** The height of the file in pixels, if applicable */ - height: number; + height?: number; } diff --git a/src/api/types/GroupContent.ts b/src/api/types/GroupContent.ts index 92c493c6..68c5b320 100644 --- a/src/api/types/GroupContent.ts +++ b/src/api/types/GroupContent.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The Content of a Group. */ export interface GroupContent { /** The type of object - `group_content` . */ - type: "group_content"; + type?: "group_content"; /** The name of the collection or section. */ - name: string; + name?: string; /** The description of the collection. Only available for collections. */ - description: string; + description?: string; } diff --git a/src/api/types/GroupTranslatedContent.ts b/src/api/types/GroupTranslatedContent.ts index 8f89cab2..51302ff2 100644 --- a/src/api/types/GroupTranslatedContent.ts +++ b/src/api/types/GroupTranslatedContent.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * The Translated Content of an Group. The keys are the locale codes and the values are the translated content of the Group. */ export interface GroupTranslatedContent { /** The type of object - group_translated_content. */ - type: "group_translated_content"; + type?: "group_translated_content"; /** The content of the group in Arabic */ ar?: Intercom.GroupContent; /** The content of the group in Bulgarian */ diff --git a/src/api/types/ImageComponent.ts b/src/api/types/ImageComponent.ts deleted file mode 100644 index 52e8d603..00000000 --- a/src/api/types/ImageComponent.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * An image component is used to display an image. - * - * HTTPS Images: - * If your request URLs (or website URLs) are over HTTPS, you will need to ensure that images are loaded over HTTPS likewise. Otherwise, they will not work. - */ -export interface ImageComponent { - /** A unique identifier for the component. */ - id?: string; - /** The URL where the image is located. */ - url: string; - /** Aligns the image inside the component. Default is `left`. */ - align?: ImageComponent.Align; - /** The exact width of the image in pixels. */ - width: number; - /** The exact height of the image in pixels. */ - height: number; - /** Rounds the corners of the image. Default is `false`. */ - rounded?: boolean; - /** Disables a component's margin-bottom of 10px. */ - bottom_margin?: "none"; - /** This can be a URL Action only. */ - action?: Intercom.UrlActionComponent; -} - -export namespace ImageComponent { - /** - * Aligns the image inside the component. Default is `left`. - */ - export type Align = "left" | "center" | "right" | "full_width"; - export const Align = { - Left: "left", - Center: "center", - Right: "right", - FullWidth: "full_width", - } as const; -} diff --git a/src/api/types/InitializeRequest.ts b/src/api/types/InitializeRequest.ts deleted file mode 100644 index e3d617b9..00000000 --- a/src/api/types/InitializeRequest.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The request payload will have all the data needed for you to understand who is using your app, where they are using it, and how you should respond. There are different request payloads for Messenger capabilities and Inbox capabilities. - */ -export interface InitializeRequest { - /** The workspace ID of the teammate. Attribute is `app_id` for V1.2 and below. */ - workspace_id: string; - /** The Intercom hosted region that this app is located in. */ - workspace_region: string; - /** The Intercom teammate viewing the conversation. */ - admin: Intercom.Admin; - /** Key-value pairs which were given as results in response to the Configure request. */ - card_creation_options: Record; - /** The context of where the app is added, where the user last visited, and information on the Messenger settings. */ - context: Intercom.Context; - /** The conversation your app is being shown for. */ - conversation: Intercom.Conversation; - /** The contact which is currently being viewed by the teammate in the conversation details panel. We send an individual initialize request for each customer when it's a group conversation. */ - contact: Intercom.Contact; -} diff --git a/src/api/types/InitializeResponse.ts b/src/api/types/InitializeResponse.ts deleted file mode 100644 index a675eeaa..00000000 --- a/src/api/types/InitializeResponse.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The response object returned when initializing an app, specifying the UI for the first screen using components. - */ -export interface InitializeResponse { - /** The canvas object that defines the UI to be shown for the app. */ - canvas: Intercom.CanvasObject; -} diff --git a/src/api/types/InputComponent.ts b/src/api/types/InputComponent.ts deleted file mode 100644 index cd7f86fb..00000000 --- a/src/api/types/InputComponent.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * An input component is used to capture text input from the end user. You can submit the value of the input by: - * - * - Adding an `action` to the input component (which will render an inline button) - * - Using a ButtonComponent (which will submit all interactive components in the canvas) - */ -export interface InputComponent { - /** A unique identifier for the component. */ - id: string; - /** The text shown above the input. */ - label?: string; - /** An example value shown inside the component when it's empty. */ - placeholder?: string; - /** An entered value which is already inside the component. */ - value?: string; - /** This can be a Submit Action, URL Action, or Sheets Action. */ - action?: Intercom.ActionComponent; - /** Styles the input. Default is `unsaved`. Prevent action with `saved`. */ - save_state?: InputComponent.SaveState; - /** Styles the input and prevents the action. Default is false. Will be overridden if save_state is saved. */ - disabled?: boolean; -} - -export namespace InputComponent { - /** - * Styles the input. Default is `unsaved`. Prevent action with `saved`. - */ - export type SaveState = "unsaved" | "saved" | "failed"; - export const SaveState = { - Unsaved: "unsaved", - Saved: "saved", - Failed: "failed", - } as const; -} diff --git a/src/api/types/InternalArticleList.ts b/src/api/types/InternalArticleList.ts new file mode 100644 index 00000000..8de68a0a --- /dev/null +++ b/src/api/types/InternalArticleList.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * This will return a list of internal articles for the App. + */ +export interface InternalArticleList { + /** The type of the object - `list`. */ + type?: "list"; + pages?: Intercom.CursorPages; + /** A count of the total number of internal articles. */ + total_count?: number; + /** An array of Internal Article objects */ + data?: Intercom.InternalArticleListItem[]; +} diff --git a/src/api/types/LinkedObject.ts b/src/api/types/LinkedObject.ts index 262dd306..27fe77b5 100644 --- a/src/api/types/LinkedObject.ts +++ b/src/api/types/LinkedObject.ts @@ -1,26 +1,29 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A linked conversation or ticket. */ export interface LinkedObject { /** ticket or conversation */ - type: LinkedObject.Type; + type?: LinkedObject.Type; /** The ID of the linked object */ - id: string; + id?: string; /** Category of the Linked Ticket Object. */ - category?: string; + category?: LinkedObject.Category; } export namespace LinkedObject { - /** - * ticket or conversation - */ - export type Type = "ticket" | "conversation"; + /** ticket or conversation */ export const Type = { Ticket: "ticket", Conversation: "conversation", } as const; + export type Type = (typeof Type)[keyof typeof Type]; + /** Category of the Linked Ticket Object. */ + export const Category = { + Customer: "Customer", + BackOffice: "Back-office", + Tracker: "Tracker", + } as const; + export type Category = (typeof Category)[keyof typeof Category]; } diff --git a/src/api/types/LinkedObjectList.ts b/src/api/types/LinkedObjectList.ts index 043bfe1c..3443c217 100644 --- a/src/api/types/LinkedObjectList.ts +++ b/src/api/types/LinkedObjectList.ts @@ -1,19 +1,17 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * An object containing metadata about linked conversations and linked tickets. Up to 1000 can be returned. */ export interface LinkedObjectList { /** Always list. */ - type: "list"; + type?: "list"; /** The total number of linked objects. */ - total_count: number; + total_count?: number; /** Whether or not there are more linked objects than returned. */ - has_more: boolean; + has_more?: boolean; /** An array containing the linked conversations and linked tickets. */ - data: Intercom.LinkedObject[]; + data?: Intercom.LinkedObject[]; } diff --git a/src/api/types/ListComponent.ts b/src/api/types/ListComponent.ts deleted file mode 100644 index b80e900d..00000000 --- a/src/api/types/ListComponent.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A list component renders a list of items which you provide in an array. You can make each list item take an action by adding the relevant action object to the item: - * - * - [Trigger a submit request to be sent](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/submit-action) Inbox Messenger - * - [Open a link in a new page](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/url-action) Inbox Messenger - * - [Open a sheet](https://developers.intercom.com/docs/references/canvas-kit/actioncomponents/sheets-action) Messenger - */ -export interface ListComponent { - /** The items that will be rendered in the list. */ - items: ListComponent.Items.Item[]; - /** Styles all list items and prevents the action. Default is `false`. */ - disabled?: boolean; -} - -export namespace ListComponent { - export type Items = Items.Item[]; - - export namespace Items { - export type Item = Intercom.ListItemWithImage | Intercom.ListItemWithoutImage; - } -} diff --git a/src/api/types/ListItem.ts b/src/api/types/ListItem.ts deleted file mode 100644 index d85d821c..00000000 --- a/src/api/types/ListItem.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A list item component that can be rendered in a list. - */ -export interface ListItem { - /** The type of component you are rendering. */ - type: "item"; - /** A unique identifier for the item. */ - id: string; - /** The text shown as the title for the item. */ - title: string; - /** The text shown underneath the item's title. */ - subtitle?: string; - /** The text shown next to the subtitle, separates by a bullet. */ - tertiary_text?: string; - /** Rounds the corners of the image. Default is `false`. */ - rounded_image?: boolean; - /** Styles all list items and prevents the action. Default is `false`. */ - disabled?: boolean; - /** This can be a Submit Action, URL Action, or Sheets Action. */ - action?: Intercom.ActionComponent; -} diff --git a/src/api/types/ListItemWithImage.ts b/src/api/types/ListItemWithImage.ts deleted file mode 100644 index 4d62f441..00000000 --- a/src/api/types/ListItemWithImage.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -export interface ListItemWithImage extends Intercom.ListItem { - /** An image that will be displayed to the left of the item. */ - image: string; - /** The exact width of the image in pixels. */ - image_width: number; - /** The exact height of the image in pixels. */ - image_height: number; -} diff --git a/src/api/types/ListItemWithoutImage.ts b/src/api/types/ListItemWithoutImage.ts deleted file mode 100644 index d5f911ec..00000000 --- a/src/api/types/ListItemWithoutImage.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -export interface ListItemWithoutImage extends Intercom.ListItem { - /** An image that will be displayed to the left of the item. */ - image?: string; - /** The exact width of the image in pixels. */ - image_width?: number; - /** The exact height of the image in pixels. */ - image_height?: number; -} diff --git a/src/api/types/LiveCanvasRequest.ts b/src/api/types/LiveCanvasRequest.ts deleted file mode 100644 index 4c90a1d5..00000000 --- a/src/api/types/LiveCanvasRequest.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * Canvases are static by default and require a new request to come through in order to update them. Live canvases however will make requests every time the card is viewed without any interaction needed, meaning the canvas can be kept up-to-date with no action from the user. - * - * This works for every Messenger request that you can respond with a canvas object to. Instead of returning the content object within the canvas object, you should provide a `content_url` attribute instead with the value being the URL you want us to send a POST request to when someone views the app. - */ -export interface LiveCanvasRequest { - /** The workspace ID of the teammate. Attribute is `app_id` for V1.2 and below. */ - workspace_id: string; - /** The Intercom hosted region that this app is located in. */ - workspace_region: string; - /** The current_canvas the teammate can see. */ - canvas: Intercom.CanvasObject; - /** The context of where the app is added, where the user last visited, and information on the Messenger settings. */ - context: Intercom.Context; - /** The contact who viewed the card. */ - contact: Intercom.Contact; -} diff --git a/src/api/types/LiveCanvasResponse.ts b/src/api/types/LiveCanvasResponse.ts deleted file mode 100644 index fca96ef7..00000000 --- a/src/api/types/LiveCanvasResponse.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The response object returned when responding to a Live Canvas request. This contains the components you want to show. - */ -export interface LiveCanvasResponse { - /** The content object that defines the components to be shown. */ - content: Intercom.ContentObject; -} diff --git a/src/api/types/Metadata.ts b/src/api/types/Metadata.ts index 1c29cca9..8d9ca56e 100644 --- a/src/api/types/Metadata.ts +++ b/src/api/types/Metadata.ts @@ -1,7 +1,5 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type Metadata = Intercom.unstable.ConversationPartMetadata; diff --git a/src/api/types/MultipleFilterSearchRequest.ts b/src/api/types/MultipleFilterSearchRequest.ts index 8554380e..400b4119 100644 --- a/src/api/types/MultipleFilterSearchRequest.ts +++ b/src/api/types/MultipleFilterSearchRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Search using Intercoms Search APIs with more than one filter. @@ -10,16 +8,21 @@ import * as Intercom from "../index"; export interface MultipleFilterSearchRequest { /** An operator to allow boolean inspection between multiple fields. */ operator?: MultipleFilterSearchRequest.Operator; - value?: Intercom.MultipleOrSingleFilterSearchRequest[]; + value?: MultipleFilterSearchRequest.Value; } export namespace MultipleFilterSearchRequest { - /** - * An operator to allow boolean inspection between multiple fields. - */ - export type Operator = "AND" | "OR"; + /** An operator to allow boolean inspection between multiple fields. */ export const Operator = { And: "AND", Or: "OR", } as const; + export type Operator = (typeof Operator)[keyof typeof Operator]; + export type Value = + /** + * Add mutiple filters. */ + | Intercom.MultipleFilterSearchRequest[] + /** + * Add a single filter field. */ + | Intercom.SingleFilterSearchRequest[]; } diff --git a/src/api/types/MultipleOrSingleFilterSearchRequest.ts b/src/api/types/MultipleOrSingleFilterSearchRequest.ts deleted file mode 100644 index 05b7916a..00000000 --- a/src/api/types/MultipleOrSingleFilterSearchRequest.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -export type MultipleOrSingleFilterSearchRequest = - | Intercom.MultipleFilterSearchRequest - | Intercom.SingleFilterSearchRequest; diff --git a/src/api/types/NewsItemRequest.ts b/src/api/types/NewsItemRequest.ts index a7aaf7e4..89a1a61d 100644 --- a/src/api/types/NewsItemRequest.ts +++ b/src/api/types/NewsItemRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A News Item is a content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers. @@ -27,12 +25,10 @@ export interface NewsItemRequest { } export namespace NewsItemRequest { - /** - * News items will not be visible to your users in the assigned newsfeeds until they are set live. - */ - export type State = "draft" | "live"; + /** News items will not be visible to your users in the assigned newsfeeds until they are set live. */ export const State = { Draft: "draft", Live: "live", } as const; + export type State = (typeof State)[keyof typeof State]; } diff --git a/src/api/types/NotFoundErrorBody.ts b/src/api/types/NotFoundErrorBody.ts new file mode 100644 index 00000000..de9109f3 --- /dev/null +++ b/src/api/types/NotFoundErrorBody.ts @@ -0,0 +1,23 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface NotFoundErrorBody { + /** The type is error.list */ + type: string; + /** */ + request_id?: string; + /** An array of one or more error objects */ + errors: NotFoundErrorBody.Errors.Item[]; +} + +export namespace NotFoundErrorBody { + export type Errors = Errors.Item[]; + + export namespace Errors { + export interface Item { + /** ticket_not_found */ + code: string; + /** Ticket not found */ + message?: string; + } + } +} diff --git a/src/api/types/NoteList.ts b/src/api/types/NoteList.ts index e9bf93ee..5090713e 100644 --- a/src/api/types/NoteList.ts +++ b/src/api/types/NoteList.ts @@ -1,18 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A paginated list of notes associated with a contact. */ export interface NoteList { /** String representing the object's type. Always has the value `list`. */ - type: "list"; + type?: string; /** An array of notes. */ - data: Intercom.Note[]; + data?: Intercom.Note[]; /** A count of the total number of notes. */ - total_count: number; - pages?: Intercom.OffsetPages; + total_count?: number; } diff --git a/src/api/types/OffsetPages.ts b/src/api/types/OffsetPages.ts index 618d4b85..7118e2df 100644 --- a/src/api/types/OffsetPages.ts +++ b/src/api/types/OffsetPages.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface OffsetPages { /** the type of object `offset_pages` */ diff --git a/src/api/types/OpenConversationRequest.ts b/src/api/types/OpenConversationRequest.ts index 682699e3..b3e63714 100644 --- a/src/api/types/OpenConversationRequest.ts +++ b/src/api/types/OpenConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to open a conversation diff --git a/src/api/types/OperatorWorkflowEvent.ts b/src/api/types/OperatorWorkflowEvent.ts new file mode 100644 index 00000000..df8629d3 --- /dev/null +++ b/src/api/types/OperatorWorkflowEvent.ts @@ -0,0 +1,23 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * Contains details about name of the workflow for conversation part type operator_workflow_event. + */ +export interface OperatorWorkflowEvent { + workflow?: OperatorWorkflowEvent.Workflow; + event?: OperatorWorkflowEvent.Event; +} + +export namespace OperatorWorkflowEvent { + export interface Workflow { + /** The name of the workflow */ + name?: string; + } + + export interface Event { + /** Type of the workflow event initiated */ + type?: string; + /** Result of the workflow event */ + result?: string; + } +} diff --git a/src/api/types/PagesLink.ts b/src/api/types/PagesLink.ts index 9f298e78..59d698ff 100644 --- a/src/api/types/PagesLink.ts +++ b/src/api/types/PagesLink.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The majority of list resources in the API are paginated to allow clients to traverse data over multiple requests. @@ -8,10 +6,10 @@ * Their responses are likely to contain a pages object that hosts pagination links which a client can use to paginate through the data without having to construct a query. The link relations for the pages field are as follows. */ export interface PagesLink { - type: "pages"; - page: number; + type?: "pages"; + page?: number; /** A link to the next page of results. A response that does not contain a next link does not have further data to fetch. */ next?: string; - per_page: number; - total_pages: number; + per_page?: number; + total_pages?: number; } diff --git a/src/api/types/PaginatedNewsItemResponse.ts b/src/api/types/PaginatedNewsItemResponse.ts deleted file mode 100644 index dcabdedc..00000000 --- a/src/api/types/PaginatedNewsItemResponse.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * Paginated News Item Response - */ -export interface PaginatedNewsItemResponse { - /** The type of object */ - type: "list"; - pages?: Intercom.CursorPages; - /** A count of the total number of News Items. */ - total_count: number; - /** An array of News Items */ - data: Intercom.NewsItem[]; -} diff --git a/src/api/types/PaginatedNewsfeedResponse.ts b/src/api/types/PaginatedNewsfeedResponse.ts deleted file mode 100644 index 92ded308..00000000 --- a/src/api/types/PaginatedNewsfeedResponse.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * Paginated Newsfeed Response - */ -export interface PaginatedNewsfeedResponse { - /** The type of object */ - type: "list"; - pages?: Intercom.CursorPages; - /** A count of the total number of Newsfeeds. */ - total_count: number; - /** An array of Newsfeeds */ - data: Intercom.Newsfeed[]; -} diff --git a/src/api/types/PaginatedResponse.ts b/src/api/types/PaginatedResponse.ts new file mode 100644 index 00000000..320b646d --- /dev/null +++ b/src/api/types/PaginatedResponse.ts @@ -0,0 +1,25 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * Paginated Response + */ +export interface PaginatedResponse { + /** The type of object */ + type?: PaginatedResponse.Type; + pages?: Intercom.CursorPages; + /** A count of the total number of objects. */ + total_count?: number; + /** An array of Objects */ + data?: Intercom.PaginatedResponseDataItem[]; +} + +export namespace PaginatedResponse { + /** The type of object */ + export const Type = { + List: "list", + ConversationList: "conversation.list", + } as const; + export type Type = (typeof Type)[keyof typeof Type]; +} diff --git a/src/api/types/PaginatedResponseDataItem.ts b/src/api/types/PaginatedResponseDataItem.ts new file mode 100644 index 00000000..4aec3d71 --- /dev/null +++ b/src/api/types/PaginatedResponseDataItem.ts @@ -0,0 +1,17 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +export type PaginatedResponseDataItem = + | Intercom.PaginatedResponseDataItem.NewsItem + | Intercom.PaginatedResponseDataItem.Newsfeed; + +export namespace PaginatedResponseDataItem { + export interface NewsItem extends Intercom.NewsItem { + type: "news-item"; + } + + export interface Newsfeed extends Intercom.Newsfeed { + type: "newsfeed"; + } +} diff --git a/src/api/types/PartAttachment.ts b/src/api/types/PartAttachment.ts index e87f566e..3c01b778 100644 --- a/src/api/types/PartAttachment.ts +++ b/src/api/types/PartAttachment.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The file attached to a part */ export interface PartAttachment { /** The type of attachment */ - type: string; + type?: string; /** The name of the attachment */ - name: string; + name?: string; /** The URL of the attachment */ - url: string; + url?: string; /** The content type of the attachment */ - content_type: string; + content_type?: string; /** The size of the attachment */ - filesize: number; + filesize?: number; /** The width of the attachment */ - width: number; + width?: number; /** The height of the attachment */ - height: number; + height?: number; } diff --git a/src/api/types/PhoneSwitch.ts b/src/api/types/PhoneSwitch.ts index 200aa121..5fbeb892 100644 --- a/src/api/types/PhoneSwitch.ts +++ b/src/api/types/PhoneSwitch.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Phone Switch Response */ export interface PhoneSwitch { /** */ - type: "phone_call_redirect"; + type?: "phone_call_redirect"; /** Phone number in E.164 format, that has received the SMS to continue the conversation in the Messenger. */ - phone: string; + phone?: string; } diff --git a/src/api/types/QuickReplyOption.ts b/src/api/types/QuickReplyOption.ts new file mode 100644 index 00000000..8de2d400 --- /dev/null +++ b/src/api/types/QuickReplyOption.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface QuickReplyOption { + /** The text to display in this quick reply option. */ + text: string; + /** A unique identifier for this quick reply option. This value will be available within the metadata of the comment conversation part that is created when a user clicks on this reply option. */ + uuid: string; +} diff --git a/src/api/types/Recipient.ts b/src/api/types/Recipient.ts new file mode 100644 index 00000000..194d11d0 --- /dev/null +++ b/src/api/types/Recipient.ts @@ -0,0 +1,20 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * A recipient of a message + */ +export interface Recipient { + /** The role associated to the contact - `user` or `lead`. */ + type: Recipient.Type; + /** The identifier for the contact which is given by Intercom. */ + id: string; +} + +export namespace Recipient { + /** The role associated to the contact - `user` or `lead`. */ + export const Type = { + User: "user", + Lead: "lead", + } as const; + export type Type = (typeof Type)[keyof typeof Type]; +} diff --git a/src/api/types/RedactConversationRequest.ts b/src/api/types/RedactConversationRequest.ts index 521b8ca3..08d784b4 100644 --- a/src/api/types/RedactConversationRequest.ts +++ b/src/api/types/RedactConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type RedactConversationRequest = /** diff --git a/src/api/types/Reference.ts b/src/api/types/Reference.ts index 708375f6..7c9c82a3 100644 --- a/src/api/types/Reference.ts +++ b/src/api/types/Reference.ts @@ -1,13 +1,11 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * reference to another object */ export interface Reference { /** */ - type: string; + type?: string; /** */ id?: string; } diff --git a/src/api/types/ReplyConversationRequest.ts b/src/api/types/ReplyConversationRequest.ts index 47e84c5d..113e344e 100644 --- a/src/api/types/ReplyConversationRequest.ts +++ b/src/api/types/ReplyConversationRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; export type ReplyConversationRequest = | Intercom.ContactReplyConversationRequest diff --git a/src/api/types/ResultsResponse.ts b/src/api/types/ResultsResponse.ts deleted file mode 100644 index 118b3e37..00000000 --- a/src/api/types/ResultsResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * The results object should be sent when you want to end configuration of the app and trigger the [Initialize request](https://developers.intercom.com/docs/canvas-kit/#initialize) to be sent. You provide the key-value pairs of data you want access to and we will send these in the Initialize request within a [card_creation_options object](https://developers.intercom.com/docs/references/canvas-kit/requestobjects/card-creation-options/#card-creation-options). - */ -export interface ResultsResponse { - /** Key-value pairs of data you want access to in the Initialize request */ - results: Record; -} diff --git a/src/api/types/SearchRequest.ts b/src/api/types/SearchRequest.ts index 75ca8744..be8ae5af 100644 --- a/src/api/types/SearchRequest.ts +++ b/src/api/types/SearchRequest.ts @@ -1,8 +1,6 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Search using Intercoms Search APIs. diff --git a/src/api/types/SegmentList.ts b/src/api/types/SegmentList.ts index 3c5636cf..cb3efe41 100644 --- a/src/api/types/SegmentList.ts +++ b/src/api/types/SegmentList.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of Segment Objects. The result may also have a pages object if the response is paginated. */ export interface SegmentList { /** The type of the object */ - type: "segment.list"; + type?: "segment.list"; /** A list of Segment objects */ - segments: Intercom.Segment[]; + segments?: Intercom.Segment[]; /** A pagination object, which may be empty, indicating no further pages to fetch. */ pages?: Record; } diff --git a/src/api/types/SheetActionComponent.ts b/src/api/types/SheetActionComponent.ts deleted file mode 100644 index 655b7039..00000000 --- a/src/api/types/SheetActionComponent.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A sheet action opens the link you give within the Messenger as an embedded iframe. - * - * [More on how Sheets work is in our Canvas Kit documentation.](https://developers.intercom.com/docs/canvas-kit#sheets-optional) - */ -export interface SheetActionComponent { - /** The link which hosts your sheet. */ - url: string; -} diff --git a/src/api/types/SingleFilterSearchRequest.ts b/src/api/types/SingleFilterSearchRequest.ts index 94aa9dfc..b51eb1a2 100644 --- a/src/api/types/SingleFilterSearchRequest.ts +++ b/src/api/types/SingleFilterSearchRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Search using Intercoms Search APIs with a single filter. @@ -15,10 +13,7 @@ export interface SingleFilterSearchRequest { } export namespace SingleFilterSearchRequest { - /** - * The accepted operators you can use to define how you want to search for the value. - */ - export type Operator = "=" | "!=" | "IN" | "NIN" | "<" | ">" | "~" | "!~" | "^" | "$"; + /** The accepted operators you can use to define how you want to search for the value. */ export const Operator = { Equals: "=", NotEquals: "!=", @@ -31,8 +26,9 @@ export namespace SingleFilterSearchRequest { StartsWith: "^", EndsWith: "$", } as const; + export type Operator = (typeof Operator)[keyof typeof Operator]; /** * The value that you want to search on. */ - export type Value = string | number | string[] | number[]; + export type Value = string | number | (string | number)[]; } diff --git a/src/api/types/SingleSelectComponent.ts b/src/api/types/SingleSelectComponent.ts deleted file mode 100644 index 04f9cf85..00000000 --- a/src/api/types/SingleSelectComponent.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * A single-select component is used to capture a choice from up to 10 options that you provide. You can submit the value of the select option by: - * - * - Adding an `action` to the single-select component - * - Using a ButtonComponent (which will submit all interactive components in the canvas) - * - * When a submit action takes place, the results are given in a hash with the `id` from the single-select component used as the key and the `id` from the chosen option as the value. - */ -export interface SingleSelectComponent { - /** A unique identifier for the component. */ - id: string; - /** The list of options. Can provide 2 to 10. */ - options: Intercom.SingleSelectOption[]; - /** The text shown above the options. */ - label?: string; - /** The option that is selected by default. */ - value?: string; - /** Styles the input. Default is `unsaved`. Prevent action with `saved`. */ - save_state?: SingleSelectComponent.SaveState; - /** Styles all options and prevents the action. Default is false. Will be overridden if save_state is saved. */ - disabled?: boolean; - /** This can be a Submit Action, URL Action, or Sheets Action. */ - action?: Intercom.ActionComponent; -} - -export namespace SingleSelectComponent { - /** - * Styles the input. Default is `unsaved`. Prevent action with `saved`. - */ - export type SaveState = "unsaved" | "saved" | "failed"; - export const SaveState = { - Unsaved: "unsaved", - Saved: "saved", - Failed: "failed", - } as const; -} diff --git a/src/api/types/SingleSelectOption.ts b/src/api/types/SingleSelectOption.ts deleted file mode 100644 index 4fc06e87..00000000 --- a/src/api/types/SingleSelectOption.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A single select option component that can be selected. - */ -export interface SingleSelectOption { - /** The type of component you are rendering. */ - type: "option"; - /** A unique identifier for the option. */ - id: string; - /** The text shown within this option. */ - text: string; - /** Styles the option and prevents the action. Default is false. */ - disabled?: boolean; -} diff --git a/src/api/types/SlaApplied.ts b/src/api/types/SlaApplied.ts index 086c6c17..3ea77f62 100644 --- a/src/api/types/SlaApplied.ts +++ b/src/api/types/SlaApplied.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The SLA Applied object contains the details for which SLA has been applied to this conversation. @@ -8,16 +6,16 @@ */ export interface SlaApplied { /** object type */ - type: string; + type?: string; /** The name of the SLA as given by the teammate when it was created. */ - sla_name: string; + sla_name?: string; /** * SLA statuses: * - `hit`: If there’s at least one hit event in the underlying sla_events table, and no “missed” or “canceled” events for the conversation. * - `missed`: If there are any missed sla_events for the conversation and no canceled events. If there’s even a single missed sla event, the status will always be missed. A missed status is not applied when the SLA expires, only the next time a teammate replies. * - `active`: An SLA has been applied to a conversation, but has not yet been fulfilled. SLA status is active only if there are no “hit, “missed”, or “canceled” events. */ - sla_status: SlaApplied.SlaStatus; + sla_status?: SlaApplied.SlaStatus; } export namespace SlaApplied { @@ -27,11 +25,11 @@ export namespace SlaApplied { * - `missed`: If there are any missed sla_events for the conversation and no canceled events. If there’s even a single missed sla event, the status will always be missed. A missed status is not applied when the SLA expires, only the next time a teammate replies. * - `active`: An SLA has been applied to a conversation, but has not yet been fulfilled. SLA status is active only if there are no “hit, “missed”, or “canceled” events. */ - export type SlaStatus = "hit" | "missed" | "cancelled" | "active"; export const SlaStatus = { Hit: "hit", Missed: "missed", Cancelled: "cancelled", Active: "active", } as const; + export type SlaStatus = (typeof SlaStatus)[keyof typeof SlaStatus]; } diff --git a/src/api/types/SnoozeConversationRequest.ts b/src/api/types/SnoozeConversationRequest.ts index 25429753..7e3e7061 100644 --- a/src/api/types/SnoozeConversationRequest.ts +++ b/src/api/types/SnoozeConversationRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Payload of the request to snooze a conversation diff --git a/src/api/types/SocialProfile.ts b/src/api/types/SocialProfile.ts index 90befe00..78030405 100644 --- a/src/api/types/SocialProfile.ts +++ b/src/api/types/SocialProfile.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A Social Profile allows you to label your contacts, companies, and conversations and list them using that Social Profile. */ export interface SocialProfile { /** value is "social_profile" */ - type: "social_profile"; + type?: "social_profile"; /** The name of the Social media profile */ - name: string; + name?: string; /** The name of the Social media profile */ - url: string; + url?: string; } diff --git a/src/api/types/SpacerComponent.ts b/src/api/types/SpacerComponent.ts deleted file mode 100644 index d8215aa3..00000000 --- a/src/api/types/SpacerComponent.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A spacer component is used to create empty space between components. - */ -export interface SpacerComponent { - /** A unique identifier for the component. */ - id?: string; - /** The amount of space between components. Default is `s`. */ - size?: SpacerComponent.Size; -} - -export namespace SpacerComponent { - /** - * The amount of space between components. Default is `s`. - */ - export type Size = "xs" | "s" | "m" | "l" | "xl"; - export const Size = { - Xs: "xs", - S: "s", - M: "m", - L: "l", - Xl: "xl", - } as const; -} diff --git a/src/api/types/StartingAfterPaging.ts b/src/api/types/StartingAfterPaging.ts index df4feb10..6fc82b73 100644 --- a/src/api/types/StartingAfterPaging.ts +++ b/src/api/types/StartingAfterPaging.ts @@ -1,10 +1,8 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export interface StartingAfterPaging { /** The number of results to fetch per page. */ - per_page: number; + per_page?: number; /** The cursor to use in the next request to get the next page of results. */ starting_after?: string; } diff --git a/src/api/types/SubmitActionComponent.ts b/src/api/types/SubmitActionComponent.ts deleted file mode 100644 index c1eec8c9..00000000 --- a/src/api/types/SubmitActionComponent.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A submit action triggers a [Submit Request](https://developers.intercom.com/docs/canvas-kit#submit-request) to be sent. This request will include all values which have been entered into all the interactive components on the current canvas. - */ -export interface SubmitActionComponent {} diff --git a/src/api/types/SubmitRequest.ts b/src/api/types/SubmitRequest.ts deleted file mode 100644 index 38aa3f2c..00000000 --- a/src/api/types/SubmitRequest.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The Submit request is triggered when a component with a submit action is interacted with in Messenger Inbox. - */ -export interface SubmitRequest { - /** The workspace ID of the teammate. Attribute is `app_id` for V1.2 and below. */ - workspace_id: string; - /** The Intercom hosted region that this app is located in. */ - workspace_region: string; - /** The Intercom teammate viewing the conversation. */ - admin: Intercom.Admin; - /** The id of the component clicked by the teammate to trigger the request. */ - component_id: string; - /** The context of where the app is added, where the user last visited, and information on the Messenger settings. */ - context: Intercom.Context; - /** The conversation where your app is being shown. */ - conversation: Intercom.Conversation; - /** The current canvas the teammate can see. */ - current_canvas: Intercom.CurrentCanvas; - /** The contact which is currently being viewed by the teammate in the conversation details panel. */ - contact: Intercom.Contact; - /** A list of key/value pairs of data, inputted by the teammate on the current canvas. */ - input_values: Record; - /** The user who took the action. */ - user: Intercom.Contact; -} diff --git a/src/api/types/SubmitResponse.ts b/src/api/types/SubmitResponse.ts deleted file mode 100644 index 9e2ff974..00000000 --- a/src/api/types/SubmitResponse.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Intercom from "../index"; - -/** - * The response object returned when submitting an app interaction. This will replace the previous canvas that was visible until the app was interacted with. - * - * You can optionally provide an event object with the attribute `type` given as `completed` to tell us if the app has completed its purpose. For example, an email collector app would be complete when the end-user submits their email address. - * - * Apps in conversation details can also optionally insert an app into the conversation reply: - * - * 1. You respond with a card_creation_options object (https://developers.intercom.com/canvas-kit-reference/reference/card-creation-options) - * 2. We send a request to the initialize URL for Messenger capabilities (https://developers.intercom.com/docs/build-an-integration/getting-started/build-an-app-for-your-messenger/request-flows) with the card_creation_options object present - * 3. You respond with a canvas object with the components you want to insert into the conversation reply - */ -export interface SubmitResponse { - /** The canvas object that defines the new UI to be shown. */ - canvas: Intercom.CanvasObject; - /** Optional. Key-value pairs that will be sent in the initialize request to insert an app into the conversation reply. */ - card_creation_options?: Record; - /** Optional. Indicates if the app has completed its purpose. */ - event?: Intercom.Event; -} diff --git a/src/api/types/SubscriptionTypeList.ts b/src/api/types/SubscriptionTypeList.ts index 39b5ec38..134688b1 100644 --- a/src/api/types/SubscriptionTypeList.ts +++ b/src/api/types/SubscriptionTypeList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of subscription type objects. */ export interface SubscriptionTypeList { /** The type of the object */ - type: "list"; + type?: "list"; /** A list of subscription type objects associated with the workspace . */ - data: Intercom.SubscriptionType[]; + data?: Intercom.SubscriptionType[]; } diff --git a/src/api/types/TagCompanyRequest.ts b/src/api/types/TagCompanyRequest.ts index 23231949..4f4affb5 100644 --- a/src/api/types/TagCompanyRequest.ts +++ b/src/api/types/TagCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a single company or a list of companies. diff --git a/src/api/types/TagList.ts b/src/api/types/TagList.ts index 4e658c56..54b9506c 100644 --- a/src/api/types/TagList.ts +++ b/src/api/types/TagList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of tags objects in the workspace. */ export interface TagList { /** The type of the object */ - type: "list"; + type?: "list"; /** A list of tags objects associated with the workspace . */ - data: Intercom.Tag[]; + data?: Intercom.Tag[]; } diff --git a/src/api/types/TagMultipleUsersRequest.ts b/src/api/types/TagMultipleUsersRequest.ts index df2f72b2..fc697987 100644 --- a/src/api/types/TagMultipleUsersRequest.ts +++ b/src/api/types/TagMultipleUsersRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a list of users. diff --git a/src/api/types/Tags.ts b/src/api/types/Tags.ts index b1257d7d..0d3680ce 100644 --- a/src/api/types/Tags.ts +++ b/src/api/types/Tags.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of tags objects associated with a conversation */ export interface Tags { /** The type of the object */ - type: "tag.list"; + type?: "tag.list"; /** A list of tags objects associated with the conversation. */ - tags: Intercom.Tag[]; + tags?: Intercom.Tag[]; } diff --git a/src/api/types/TeamList.ts b/src/api/types/TeamList.ts index b7833bf3..def5cbe1 100644 --- a/src/api/types/TeamList.ts +++ b/src/api/types/TeamList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * This will return a list of team objects for the App. */ export interface TeamList { /** The type of the object */ - type: "team.list"; + type?: "team.list"; /** A list of team objects */ - teams: Intercom.Team[]; + teams?: Intercom.Team[]; } diff --git a/src/api/types/TeamPriorityLevel.ts b/src/api/types/TeamPriorityLevel.ts index b979fa1d..07d6bae5 100644 --- a/src/api/types/TeamPriorityLevel.ts +++ b/src/api/types/TeamPriorityLevel.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Admin priority levels for teams diff --git a/src/api/types/TextAreaComponent.ts b/src/api/types/TextAreaComponent.ts deleted file mode 100644 index 1a2d215c..00000000 --- a/src/api/types/TextAreaComponent.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A text area component is used to capture a large amount of text as input with a multi-line text box. You can submit the value of the text area by: - * - * - Using a ButtonComponent (which will submit all interactive components in the canvas) - */ -export interface TextAreaComponent { - /** A unique identifier for the component. */ - id: string; - /** The text shown above the text area. */ - label?: string; - /** An example value shown inside the component when it's empty. */ - placeholder?: string; - /** An entered value which is already inside the component. */ - value?: string; - /** Styles the input as failed. Default is false. */ - error?: boolean; - /** Styles the input and prevents the action. Default is false. */ - disabled?: boolean; -} diff --git a/src/api/types/TextComponent.ts b/src/api/types/TextComponent.ts deleted file mode 100644 index 1fe6bce2..00000000 --- a/src/api/types/TextComponent.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A text component is used for rendering blocks of text. Links and bold font can be rendered through Markdown. There are different styles provided which edit the color, weight, and font size. These cannot be edited through Markdown. - */ -export interface TextComponent { - /** A unique identifier for the component. */ - id?: string; - /** The text that will be rendered. */ - text: string; - /** Aligns the text. Default is `left`. */ - align?: TextComponent.Align; - /** Styles the text. Default is `paragraph`. */ - style?: TextComponent.Style; - /** Disables a component's margin-bottom of 10px. */ - bottom_margin?: "none"; -} - -export namespace TextComponent { - /** - * Aligns the text. Default is `left`. - */ - export type Align = "left" | "center" | "right"; - export const Align = { - Left: "left", - Center: "center", - Right: "right", - } as const; - /** - * Styles the text. Default is `paragraph`. - */ - export type Style = "header" | "paragraph" | "muted" | "error"; - export const Style = { - Header: "header", - Paragraph: "paragraph", - Muted: "muted", - Error: "error", - } as const; -} diff --git a/src/api/types/TicketCustomAttributes.ts b/src/api/types/TicketCustomAttributes.ts index fe9181ea..2596f28b 100644 --- a/src/api/types/TicketCustomAttributes.ts +++ b/src/api/types/TicketCustomAttributes.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * An object containing the different attributes associated to the ticket as key-value pairs. For the default title and description attributes, the keys are `_default_title_` and `_default_description_`. diff --git a/src/api/types/TicketList.ts b/src/api/types/TicketList.ts index 5cfdf4fe..e512f129 100644 --- a/src/api/types/TicketList.ts +++ b/src/api/types/TicketList.ts @@ -1,18 +1,16 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Tickets are how you track requests from your users. */ export interface TicketList { /** Always ticket.list */ - type: "ticket.list"; + type?: "ticket.list"; /** The list of ticket objects */ - tickets: Intercom.Ticket[]; + tickets?: (Intercom.Ticket | undefined)[]; /** A count of the total number of objects. */ - total_count: number; + total_count?: number; pages?: Intercom.CursorPages; } diff --git a/src/api/types/TicketPartAuthor.ts b/src/api/types/TicketPartAuthor.ts index c09f0739..e0ea7ff3 100644 --- a/src/api/types/TicketPartAuthor.ts +++ b/src/api/types/TicketPartAuthor.ts @@ -1,30 +1,26 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The author that wrote or triggered the part. Can be a bot, admin, team or user. */ export interface TicketPartAuthor { /** The type of the author */ - type: TicketPartAuthor.Type; + type?: TicketPartAuthor.Type; /** The id of the author */ - id: string; + id?: string; /** The name of the author */ name?: string; /** The email of the author */ - email: string; + email?: string; } export namespace TicketPartAuthor { - /** - * The type of the author - */ - export type Type = "admin" | "bot" | "team" | "user"; + /** The type of the author */ export const Type = { Admin: "admin", Bot: "bot", Team: "team", User: "user", } as const; + export type Type = (typeof Type)[keyof typeof Type]; } diff --git a/src/api/types/TicketParts.ts b/src/api/types/TicketParts.ts index f6d4ee25..9ff75bbe 100644 --- a/src/api/types/TicketParts.ts +++ b/src/api/types/TicketParts.ts @@ -1,17 +1,15 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of Ticket Part objects for each note and event in the ticket. There is a limit of 500 parts. */ export interface TicketParts { /** */ - type: "ticket_part.list"; + type?: "ticket_part.list"; /** A list of Ticket Part objects for each ticket. There is a limit of 500 parts. */ - ticket_parts: Intercom.TicketPart[]; + ticket_parts?: Intercom.TicketPart[]; /** */ - total_count: number; + total_count?: number; } diff --git a/src/api/types/TicketReply.ts b/src/api/types/TicketReply.ts index 7c3b7f11..f86b2ef4 100644 --- a/src/api/types/TicketReply.ts +++ b/src/api/types/TicketReply.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A Ticket Part representing a note, comment, or quick_reply on a ticket */ export interface TicketReply { /** Always ticket_part */ - type: "ticket_part"; + type?: "ticket_part"; /** The id representing the part. */ - id: string; + id?: string; /** Type of the part */ - part_type: TicketReply.PartType; + part_type?: TicketReply.PartType; /** The message body, which may contain HTML. */ body?: string; /** The time the note was created. */ - created_at: number; + created_at?: number; /** The last time the note was updated. */ updated_at?: number; author?: Intercom.TicketPartAuthor; @@ -28,13 +26,11 @@ export interface TicketReply { } export namespace TicketReply { - /** - * Type of the part - */ - export type PartType = "note" | "comment" | "quick_reply"; + /** Type of the part */ export const PartType = { Note: "note", Comment: "comment", QuickReply: "quick_reply", } as const; + export type PartType = (typeof PartType)[keyof typeof PartType]; } diff --git a/src/api/types/TicketRequestCustomAttributes.ts b/src/api/types/TicketRequestCustomAttributes.ts index ce59bc75..f8cce5a3 100644 --- a/src/api/types/TicketRequestCustomAttributes.ts +++ b/src/api/types/TicketRequestCustomAttributes.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * The attributes set on the ticket. When setting the default title and description attributes, the attribute keys that should be used are `_default_title_` and `_default_description_`. When setting ticket type attributes of the list attribute type, the key should be the attribute name and the value of the attribute should be the list item id, obtainable by [listing the ticket type](ref:get_ticket-types). For example, if the ticket type has an attribute called `priority` of type `list`, the key should be `priority` and the value of the attribute should be the guid of the list item (e.g. `de1825a0-0164-4070-8ca6-13e22462fa7e`). diff --git a/src/api/types/TicketStateList.ts b/src/api/types/TicketStateList.ts new file mode 100644 index 00000000..ac2fbc51 --- /dev/null +++ b/src/api/types/TicketStateList.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as Intercom from "../index.js"; + +/** + * A list of ticket states associated with a given ticket type. + */ +export interface TicketStateList { + /** String representing the object's type. Always has the value `list`. */ + type?: string; + /** A list of ticket states associated with a given ticket type. */ + data?: (Intercom.TicketStateDetailed | undefined)[]; +} diff --git a/src/api/types/TicketTypeAttribute.ts b/src/api/types/TicketTypeAttribute.ts index a0267806..855266f6 100644 --- a/src/api/types/TicketTypeAttribute.ts +++ b/src/api/types/TicketTypeAttribute.ts @@ -1,52 +1,47 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Ticket type attribute, used to define each data field to be captured in a ticket. */ export interface TicketTypeAttribute { /** String representing the object's type. Always has the value `ticket_type_attribute`. */ - type: "ticket_type_attribute"; + type?: string; /** The id representing the ticket type attribute. */ - id: string; + id?: string; /** The id of the workspace that the ticket type attribute belongs to. */ - workspace_id: string; + workspace_id?: string; /** The name of the ticket type attribute */ - name: string; + name?: string; /** The description of the ticket type attribute */ - description: string; + description?: string; /** The type of the data attribute (allowed values: "string list integer decimal boolean datetime files") */ - data_type: TicketTypeAttribute.DataType; + data_type?: TicketTypeAttribute.DataType; /** Input options for the attribute */ - input_options: Record; + input_options?: Record; /** The order of the attribute against other attributes */ - order: number; + order?: number; /** Whether the attribute is required or not for teammates. */ - required_to_create: boolean; + required_to_create?: boolean; /** Whether the attribute is required or not for contacts. */ - required_to_create_for_contacts: boolean; + required_to_create_for_contacts?: boolean; /** Whether the attribute is visible or not to teammates. */ - visible_on_create: boolean; + visible_on_create?: boolean; /** Whether the attribute is visible or not to contacts. */ - visible_to_contacts: boolean; + visible_to_contacts?: boolean; /** Whether the attribute is built in or not. */ - default: boolean; + default?: boolean; /** The id of the ticket type that the attribute belongs to. */ - ticket_type_id: number; + ticket_type_id?: number; /** Whether the ticket type attribute is archived or not. */ - archived: boolean; + archived?: boolean; /** The date and time the ticket type attribute was created. */ - created_at: number; + created_at?: number; /** The date and time the ticket type attribute was last updated. */ updated_at?: number; } export namespace TicketTypeAttribute { - /** - * The type of the data attribute (allowed values: "string list integer decimal boolean datetime files") - */ - export type DataType = "string" | "list" | "integer" | "decimal" | "boolean" | "datetime" | "files"; + /** The type of the data attribute (allowed values: "string list integer decimal boolean datetime files") */ export const DataType = { String: "string", List: "list", @@ -56,4 +51,5 @@ export namespace TicketTypeAttribute { Datetime: "datetime", Files: "files", } as const; + export type DataType = (typeof DataType)[keyof typeof DataType]; } diff --git a/src/api/types/TicketTypeAttributeList.ts b/src/api/types/TicketTypeAttributeList.ts index 011e3cc2..6a9b00dc 100644 --- a/src/api/types/TicketTypeAttributeList.ts +++ b/src/api/types/TicketTypeAttributeList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of attributes associated with a given ticket type. */ export interface TicketTypeAttributeList { /** String representing the object's type. Always has the value `ticket_type_attributes.list`. */ - type: "ticket_type_attributes.list"; + type?: string; /** A list of ticket type attributes associated with a given ticket type. */ - ticket_type_attributes: Intercom.TicketTypeAttribute[]; + ticket_type_attributes?: (Intercom.TicketTypeAttribute | undefined)[]; } diff --git a/src/api/types/TicketTypeList.ts b/src/api/types/TicketTypeList.ts index 3a4d2b86..d76acea8 100644 --- a/src/api/types/TicketTypeList.ts +++ b/src/api/types/TicketTypeList.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * A list of ticket types associated with a given workspace. */ export interface TicketTypeList { - /** String representing the object's type. Always has the value `ticket_type.list`. */ - type: "ticket_type_attributes.list"; + /** String representing the object's type. Always has the value `list`. */ + type?: string; /** A list of ticket_types associated with a given workspace. */ - ticket_types: Intercom.TicketType[]; + data?: (Intercom.TicketType | undefined)[]; } diff --git a/src/api/types/Translation.ts b/src/api/types/Translation.ts index 19b73881..3d656a16 100644 --- a/src/api/types/Translation.ts +++ b/src/api/types/Translation.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * A translation object contains the localised details of a subscription type. */ export interface Translation { /** The localised name of the subscription type. */ - name: string; + name?: string; /** The localised description of the subscription type. */ - description: string; + description?: string; /** The two character identifier for the language of the translation object. */ - locale: string; + locale?: string; } diff --git a/src/api/types/UntagCompanyRequest.ts b/src/api/types/UntagCompanyRequest.ts index dd179dde..09886bd1 100644 --- a/src/api/types/UntagCompanyRequest.ts +++ b/src/api/types/UntagCompanyRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * You can tag a single company or a list of companies. @@ -18,11 +16,11 @@ export namespace UntagCompanyRequest { export namespace Companies { export interface Item { /** The Intercom defined id representing the company. */ - id: string; + id?: string; /** The company id you have defined for the company. */ - company_id: string; + company_id?: string; /** Always set to true */ - untag: true; + untag?: boolean; } } } diff --git a/src/api/types/UpdateArticleRequestBody.ts b/src/api/types/UpdateArticleRequestBody.ts new file mode 100644 index 00000000..3a5100b8 --- /dev/null +++ b/src/api/types/UpdateArticleRequestBody.ts @@ -0,0 +1,13 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface UpdateArticleRequestBody { + parent_type?: UpdateArticleRequestBody.ParentType; +} + +export namespace UpdateArticleRequestBody { + export const ParentType = { + Collection: "collection", + Section: "section", + } as const; + export type ParentType = (typeof ParentType)[keyof typeof ParentType]; +} diff --git a/src/api/types/UpdateCompanyRequestBody.ts b/src/api/types/UpdateCompanyRequestBody.ts new file mode 100644 index 00000000..8949ca97 --- /dev/null +++ b/src/api/types/UpdateCompanyRequestBody.ts @@ -0,0 +1,21 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * You can update a Company + */ +export interface UpdateCompanyRequestBody { + /** The name of the Company */ + name?: string; + /** The name of the plan you have associated with the company. */ + plan?: string; + /** The number of employees in this company. */ + size?: number; + /** The URL for this company's website. Please note that the value specified here is not validated. Accepts any string. */ + website?: string; + /** The industry that this company operates in. */ + industry?: string; + /** A hash of key/value pairs containing any other data about the company you want Intercom to store. */ + custom_attributes?: Record; + /** How much revenue the company generates for your business. Note that this will truncate floats. i.e. it only allow for whole integers, 155.98 will be truncated to 155. Note that this has an upper limit of 2**31-1 or 2147483647.. */ + monthly_spend?: number; +} diff --git a/src/api/types/UpdateDataAttributeRequestBody.ts b/src/api/types/UpdateDataAttributeRequestBody.ts new file mode 100644 index 00000000..6524ae99 --- /dev/null +++ b/src/api/types/UpdateDataAttributeRequestBody.ts @@ -0,0 +1,12 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * + */ +export type UpdateDataAttributeRequestBody = + | { + options: { + value?: string | undefined; + }[]; + } + | unknown; diff --git a/src/api/types/UpdateVisitorRequest.ts b/src/api/types/UpdateVisitorRequest.ts index a81aa7d3..349fd6b2 100644 --- a/src/api/types/UpdateVisitorRequest.ts +++ b/src/api/types/UpdateVisitorRequest.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Update an existing visitor. diff --git a/src/api/types/UpdateVisitorRequestOne.ts b/src/api/types/UpdateVisitorRequestOne.ts index 67858b8e..cfdac3c4 100644 --- a/src/api/types/UpdateVisitorRequestOne.ts +++ b/src/api/types/UpdateVisitorRequestOne.ts @@ -1,5 +1,3 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export type UpdateVisitorRequestOne = unknown; diff --git a/src/api/types/UrlActionComponent.ts b/src/api/types/UrlActionComponent.ts deleted file mode 100644 index 34d44dcf..00000000 --- a/src/api/types/UrlActionComponent.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * A URL action opens a given link in a new browser tab. - */ -export interface UrlActionComponent { - /** The link you want to open. */ - url: string; -} diff --git a/src/api/types/Visitor.ts b/src/api/types/Visitor.ts index 6865b074..195792a3 100644 --- a/src/api/types/Visitor.ts +++ b/src/api/types/Visitor.ts @@ -1,23 +1,21 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as Intercom from "../index"; +import type * as Intercom from "../index.js"; /** * Visitors are useful for representing anonymous people that have not yet been identified. They usually represent website visitors. Visitors are not visible in Intercom platform. The Visitors resource provides methods to fetch, update, convert and delete. */ export interface Visitor { /** Value is 'visitor' */ - type: "visitor"; + type?: "visitor"; /** The Intercom defined id representing the Visitor. */ - id: string; + id?: string; /** Automatically generated identifier for the Visitor. */ - user_id: string; + user_id?: string; /** Identifies if this visitor is anonymous. */ - anonymous: boolean; + anonymous?: boolean; /** The email of the visitor. */ - email: string; + email?: string; /** The phone number of the visitor. */ phone?: string; /** The name of the visitor. */ @@ -26,17 +24,17 @@ export interface Visitor { pseudonym?: string; avatar?: Visitor.Avatar; /** The id of the app the visitor is associated with. */ - app_id: string; + app_id?: string; companies?: Visitor.Companies; location_data?: Visitor.LocationData; /** The time the Lead last recorded making a request. */ las_request_at?: number; /** The time the Visitor was added to Intercom. */ - created_at: number; + created_at?: number; /** The time the Visitor was added to Intercom. */ remote_created_at?: number; /** The time the Visitor signed up for your product. */ - signed_up_at: number; + signed_up_at?: number; /** The last time the Visitor was updated. */ updated_at?: number; /** The number of sessions the Visitor has had. */ diff --git a/src/api/types/VisitorDeletedObject.ts b/src/api/types/VisitorDeletedObject.ts index 3195b30d..6a3cc196 100644 --- a/src/api/types/VisitorDeletedObject.ts +++ b/src/api/types/VisitorDeletedObject.ts @@ -1,15 +1,13 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** * Response returned when an object is deleted */ export interface VisitorDeletedObject { /** The unique identifier for the visitor which is given by Intercom. */ - id: string; + id?: string; /** The type of object which was deleted */ - type: "visitor"; + type?: "visitor"; /** Automatically generated identifier for the Visitor. */ - user_id: string; + user_id?: string; } diff --git a/src/api/types/WhatsappMessageStatusList.ts b/src/api/types/WhatsappMessageStatusList.ts new file mode 100644 index 00000000..b1d0e8d8 --- /dev/null +++ b/src/api/types/WhatsappMessageStatusList.ts @@ -0,0 +1,67 @@ +// This file was auto-generated by Fern from our API Definition. + +export interface WhatsappMessageStatusList { + type: "list"; + /** The provided ruleset ID */ + ruleset_id: string; + pages: WhatsappMessageStatusList.Pages; + /** Total number of events */ + total_count: number; + events: WhatsappMessageStatusList.Events.Item[]; +} + +export namespace WhatsappMessageStatusList { + export interface Pages { + type: "pages"; + /** Number of results per page */ + per_page: number; + /** Total number of pages */ + total_pages: number; + /** Information for fetching next page (null if no more pages) */ + next?: Pages.Next; + } + + export namespace Pages { + /** + * Information for fetching next page (null if no more pages) + */ + export interface Next { + /** Cursor for the next page */ + starting_after?: string; + } + } + + export type Events = Events.Item[]; + + export namespace Events { + export interface Item { + /** Event ID */ + id: string; + /** ID of the conversation */ + conversation_id: string; + /** Current status of the message */ + status: Item.Status; + /** Event type */ + type: "broadcast_outbound"; + /** Creation timestamp */ + created_at: number; + /** Last update timestamp */ + updated_at: number; + /** WhatsApp's message identifier */ + whatsapp_message_id: string; + /** Name of the WhatsApp template used */ + template_name?: string; + } + + export namespace Item { + /** Current status of the message */ + export const Status = { + Sent: "sent", + Delivered: "delivered", + Read: "read", + Failed: "failed", + } as const; + export type Status = (typeof Status)[keyof typeof Status]; + } + } +} diff --git a/src/api/types/index.ts b/src/api/types/index.ts index 2a4c1060..f81547cc 100644 --- a/src/api/types/index.ts +++ b/src/api/types/index.ts @@ -1,165 +1,162 @@ -export * from "./ActionComponent"; -export * from "./ActivityLog"; -export * from "./ActivityLogList"; -export * from "./ActivityLogMetadata"; -export * from "./AddressableList"; -export * from "./AdminList"; -export * from "./AdminPriorityLevel"; -export * from "./AdminReplyConversationRequest"; -export * from "./AdminReplyTicketRequest"; -export * from "./AdminWithApp"; -export * from "./App"; -export * from "./ArticleContent"; -export * from "./ArticleList"; -export * from "./ArticleStatistics"; -export * from "./ArticleTranslatedContent"; -export * from "./AssignConversationRequest"; -export * from "./ButtonComponent"; -export * from "./CanvasObject"; -export * from "./CheckboxOption"; -export * from "./CheckboxComponent"; -export * from "./CloseConversationRequest"; -export * from "./CollectionList"; -export * from "./CompanyAttachedContacts"; -export * from "./CompanyAttachedSegments"; -export * from "./CompanyList"; -export * from "./CompanyScroll"; -export * from "./Component"; -export * from "./ConfigureRequest"; -export * from "./ConfigureResponse"; -export * from "./ContactArchived"; -export * from "./ContactAttachedCompanies"; -export * from "./ContactCompanies"; -export * from "./ContactCompany"; -export * from "./ContactDeleted"; -export * from "./ContactList"; -export * from "./ContactLocation"; -export * from "./ContactNotes"; -export * from "./ContactReference"; -export * from "./ContactReplyBaseRequest"; -export * from "./ContactReplyConversationRequest"; -export * from "./ContactReplyEmailRequest"; -export * from "./ContactReplyIntercomUserIdRequest"; -export * from "./ContactReplyTicketEmailRequest"; -export * from "./ContactReplyTicketIntercomUserIdRequest"; -export * from "./ContactReplyTicketRequest"; -export * from "./ContactReplyTicketUserIdRequest"; -export * from "./ContactReplyUserIdRequest"; -export * from "./ContactSegments"; -export * from "./ContactSocialProfiles"; -export * from "./ContactSubscriptionTypes"; -export * from "./ContactTags"; -export * from "./ContactUnarchived"; -export * from "./ContentObject"; -export * from "./ContentSourcesList"; -export * from "./Context"; -export * from "./ConversationAttachmentFiles"; -export * from "./ConversationContacts"; -export * from "./ConversationFirstContactReply"; -export * from "./PaginatedConversationResponse"; -export * from "./ConversationPart"; -export * from "./ConversationPartAuthor"; -export * from "./ConversationParts"; -export * from "./ConversationRating"; -export * from "./ConversationSource"; -export * from "./ConversationStatistics"; -export * from "./ConversationTeammates"; -export * from "./CreateContactRequest"; -export * from "./CreateDataEventRequest"; -export * from "./CreateMessageRequest"; -export * from "./CreateOrUpdateTagRequest"; -export * from "./CreateTicketReplyWithCommentRequest"; -export * from "./CreateTicketRequest"; -export * from "./CurrentCanvas"; -export * from "./CursorPages"; -export * from "./CustomerRequest"; -export * from "./DataAttributeList"; -export * from "./DataEventList"; -export * from "./DataEventSummary"; -export * from "./DataEventSummaryItem"; -export * from "./DataExportCsv"; -export * from "./DataTableItem"; -export * from "./DataTableComponent"; -export * from "./DeletedArticleObject"; -export * from "./DeletedCollectionObject"; -export * from "./DeletedCompanyObject"; -export * from "./DeletedObject"; -export * from "./DividerComponent"; -export * from "./DropdownOption"; -export * from "./DropdownComponent"; -export * from "./Error_"; -export * from "./Event"; -export * from "./FileAttribute"; -export * from "./GroupContent"; -export * from "./GroupTranslatedContent"; -export * from "./ImageComponent"; -export * from "./InitializeRequest"; -export * from "./InitializeResponse"; -export * from "./InputComponent"; -export * from "./LinkedObject"; -export * from "./LinkedObjectList"; -export * from "./ListItem"; -export * from "./ListItemWithImage"; -export * from "./ListItemWithoutImage"; -export * from "./ListComponent"; -export * from "./LiveCanvasRequest"; -export * from "./LiveCanvasResponse"; -export * from "./MultipleOrSingleFilterSearchRequest"; -export * from "./MultipleFilterSearchRequest"; -export * from "./NewsItemRequest"; -export * from "./NoteList"; -export * from "./OpenConversationRequest"; -export * from "./PagesLink"; -export * from "./PaginatedNewsItemResponse"; -export * from "./PaginatedNewsfeedResponse"; -export * from "./PartAttachment"; -export * from "./PhoneSwitch"; -export * from "./RedactConversationRequest"; -export * from "./Reference"; -export * from "./ReplyConversationRequest"; -export * from "./ResultsResponse"; -export * from "./SearchRequest"; -export * from "./SegmentList"; -export * from "./SheetActionComponent"; -export * from "./SingleFilterSearchRequest"; -export * from "./SingleSelectOption"; -export * from "./SingleSelectComponent"; -export * from "./SlaApplied"; -export * from "./SnoozeConversationRequest"; -export * from "./SocialProfile"; -export * from "./SpacerComponent"; -export * from "./StartingAfterPaging"; -export * from "./SubmitActionComponent"; -export * from "./SubmitRequest"; -export * from "./SubmitResponse"; -export * from "./SubscriptionTypeList"; -export * from "./TagCompanyRequest"; -export * from "./TagList"; -export * from "./TagMultipleUsersRequest"; -export * from "./Tags"; -export * from "./TeamList"; -export * from "./TeamPriorityLevel"; -export * from "./TextComponent"; -export * from "./TextAreaComponent"; -export * from "./TicketCustomAttributes"; -export * from "./TicketList"; -export * from "./TicketPartAuthor"; -export * from "./TicketParts"; -export * from "./TicketReply"; -export * from "./TicketRequestCustomAttributes"; -export * from "./TicketTypeAttribute"; -export * from "./TicketTypeAttributeList"; -export * from "./TicketTypeList"; -export * from "./Translation"; -export * from "./UntagCompanyRequest"; -export * from "./UpdateVisitorRequest"; -export * from "./UrlActionComponent"; -export * from "./Visitor"; -export * from "./VisitorDeletedObject"; -export * from "./CustomAttributes"; -export * from "./OffsetPages"; -export * from "./CreateContactRequestTwo"; -export * from "./CreateDataEventRequestTwo"; -export * from "./CreateMessageRequestTwo"; -export * from "./Metadata"; -export * from "./UpdateVisitorRequestOne"; +export * from "./ActivityLog.js"; +export * from "./ActivityLogList.js"; +export * from "./ActivityLogMetadata.js"; +export * from "./AddressableList.js"; +export * from "./AdminList.js"; +export * from "./AdminPriorityLevel.js"; +export * from "./AdminReplyConversationRequest.js"; +export * from "./AdminReplyTicketRequest.js"; +export * from "./AdminWithApp.js"; +export * from "./App.js"; +export * from "./ArticleContent.js"; +export * from "./ArticleList.js"; +export * from "./ArticleStatistics.js"; +export * from "./ArticleTranslatedContent.js"; +export * from "./AssignConversationRequest.js"; +export * from "./AwayStatusReason.js"; +export * from "./CallList.js"; +export * from "./CloseConversationRequest.js"; +export * from "./CollectionList.js"; +export * from "./CompanyAttachedContacts.js"; +export * from "./CompanyAttachedSegments.js"; +export * from "./CompanyData.js"; +export * from "./CompanyList.js"; +export * from "./CompanyScroll.js"; +export * from "./ContactArchived.js"; +export * from "./ContactAttachedCompanies.js"; +export * from "./ContactBlocked.js"; +export * from "./ContactCompanies.js"; +export * from "./ContactDeleted.js"; +export * from "./ContactList.js"; +export * from "./ContactLocation.js"; +export * from "./ContactNotes.js"; +export * from "./ContactReference.js"; +export * from "./ContactReplyBaseRequest.js"; +export * from "./ContactReplyConversationRequest.js"; +export * from "./ContactReplyEmailRequest.js"; +export * from "./ContactReplyIntercomUserIdRequest.js"; +export * from "./ContactReplyTicketEmailRequest.js"; +export * from "./ContactReplyTicketIntercomUserIdRequest.js"; +export * from "./ContactReplyTicketRequest.js"; +export * from "./ContactReplyTicketUserIdRequest.js"; +export * from "./ContactReplyUserIdRequest.js"; +export * from "./ContactSegments.js"; +export * from "./ContactSocialProfiles.js"; +export * from "./ContactSubscriptionTypes.js"; +export * from "./ContactTags.js"; +export * from "./ContactUnarchived.js"; +export * from "./ContentSourcesList.js"; +export * from "./ConversationAttachmentFiles.js"; +export * from "./ConversationAttributeUpdatedByAdmin.js"; +export * from "./ConversationAttributeUpdatedByWorkflow.js"; +export * from "./ConversationContacts.js"; +export * from "./ConversationDeleted.js"; +export * from "./ConversationFirstContactReply.js"; +export * from "./ConversationList.js"; +export * from "./ConversationPart.js"; +export * from "./ConversationPartAuthor.js"; +export * from "./ConversationPartMetadata.js"; +export * from "./ConversationParts.js"; +export * from "./ConversationRating.js"; +export * from "./ConversationResponseTime.js"; +export * from "./ConversationSource.js"; +export * from "./ConversationStatistics.js"; +export * from "./ConversationTeammates.js"; +export * from "./CreateArticleRequest.js"; +export * from "./CreateContactRequest.js"; +export * from "./CreateContactRequestTwo.js"; +export * from "./CreateDataAttributeRequest.js"; +export * from "./CreateDataEventRequest.js"; +export * from "./CreateDataEventRequestTwo.js"; +export * from "./CreateInternalArticleRequest.js"; +export * from "./CreateMessageRequest.js"; +export * from "./CreateOrUpdateCompanyRequest.js"; +export * from "./CreateOrUpdateTagRequest.js"; +export * from "./CreatePhoneSwitchRequest.js"; +export * from "./CreateTicketReplyWithCommentRequest.js"; +export * from "./CreateTicketRequestBody.js"; +export * from "./CreateTicketTypeRequest.js"; +export * from "./CursorPages.js"; +export * from "./CustomActionFinished.js"; +export * from "./CustomActionStarted.js"; +export * from "./CustomAttributes.js"; +export * from "./CustomChannelAttribute.js"; +export * from "./CustomChannelBaseEvent.js"; +export * from "./CustomChannelContact.js"; +export * from "./CustomChannelNotificationResponse.js"; +export * from "./CustomerRequest.js"; +export * from "./CustomObjectInstanceDeleted.js"; +export * from "./CustomObjectInstanceList.js"; +export * from "./DataAttributeList.js"; +export * from "./DataEventList.js"; +export * from "./DataEventSummary.js"; +export * from "./DataEventSummaryItem.js"; +export * from "./DataExportCsv.js"; +export * from "./Datetime.js"; +export * from "./DeletedArticleObject.js"; +export * from "./DeletedCollectionObject.js"; +export * from "./DeletedCompanyObject.js"; +export * from "./DeletedInternalArticleObject.js"; +export * from "./DeletedObject.js"; +export * from "./EmailAddressHeader.js"; +export * from "./EmailMessageMetadata.js"; +export * from "./Error_.js"; +export * from "./EventDetails.js"; +export * from "./FileAttribute.js"; +export * from "./GroupContent.js"; +export * from "./GroupTranslatedContent.js"; +export * from "./InternalArticleList.js"; +export * from "./LinkedObject.js"; +export * from "./LinkedObjectList.js"; +export * from "./Metadata.js"; +export * from "./MultipleFilterSearchRequest.js"; +export * from "./NewsItemRequest.js"; +export * from "./NoteList.js"; +export * from "./NotFoundErrorBody.js"; +export * from "./OffsetPages.js"; +export * from "./OpenConversationRequest.js"; +export * from "./OperatorWorkflowEvent.js"; +export * from "./PagesLink.js"; +export * from "./PaginatedResponse.js"; +export * from "./PaginatedResponseDataItem.js"; +export * from "./PartAttachment.js"; +export * from "./PhoneSwitch.js"; +export * from "./QuickReplyOption.js"; +export * from "./Recipient.js"; +export * from "./RedactConversationRequest.js"; +export * from "./Reference.js"; +export * from "./ReplyConversationRequest.js"; +export * from "./SearchRequest.js"; +export * from "./SegmentList.js"; +export * from "./SingleFilterSearchRequest.js"; +export * from "./SlaApplied.js"; +export * from "./SnoozeConversationRequest.js"; +export * from "./SocialProfile.js"; +export * from "./StartingAfterPaging.js"; +export * from "./SubscriptionTypeList.js"; +export * from "./TagCompanyRequest.js"; +export * from "./TagList.js"; +export * from "./TagMultipleUsersRequest.js"; +export * from "./Tags.js"; +export * from "./TeamList.js"; +export * from "./TeamPriorityLevel.js"; +export * from "./TicketCustomAttributes.js"; +export * from "./TicketList.js"; +export * from "./TicketPartAuthor.js"; +export * from "./TicketParts.js"; +export * from "./TicketReply.js"; +export * from "./TicketRequestCustomAttributes.js"; +export * from "./TicketStateList.js"; +export * from "./TicketTypeAttribute.js"; +export * from "./TicketTypeAttributeList.js"; +export * from "./TicketTypeList.js"; +export * from "./Translation.js"; +export * from "./UntagCompanyRequest.js"; +export * from "./UpdateArticleRequestBody.js"; +export * from "./UpdateCompanyRequestBody.js"; +export * from "./UpdateDataAttributeRequestBody.js"; +export * from "./UpdateVisitorRequest.js"; +export * from "./UpdateVisitorRequestOne.js"; +export * from "./Visitor.js"; +export * from "./VisitorDeletedObject.js"; +export * from "./WhatsappMessageStatusList.js"; diff --git a/src/api/version.ts b/src/api/version.ts index 834369d5..54e211cb 100644 --- a/src/api/version.ts +++ b/src/api/version.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. /** The version of the API, sent as the Intercom-Version header. */ export type IntercomVersion = @@ -21,4 +19,7 @@ export type IntercomVersion = | "2.9" | "2.10" | "2.11" + | "2.12" + | "2.13" + | "2.14" | "Unstable"; diff --git a/src/auth/BearerAuthProvider.ts b/src/auth/BearerAuthProvider.ts new file mode 100644 index 00000000..fc69deba --- /dev/null +++ b/src/auth/BearerAuthProvider.ts @@ -0,0 +1,36 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as core from "../core/index.js"; +import * as errors from "../errors/index.js"; + +export namespace BearerAuthProvider { + export interface Options { + token?: core.Supplier; + } +} + +export class BearerAuthProvider implements core.AuthProvider { + private readonly token: core.Supplier | undefined; + + constructor(options: BearerAuthProvider.Options) { + this.token = options.token; + } + + public static canCreate(options: BearerAuthProvider.Options): boolean { + return options.token != null || process.env?.INTERCOM_API_KEY != null; + } + + public async getAuthRequest(_arg?: { endpointMetadata?: core.EndpointMetadata }): Promise { + const token = (await core.Supplier.get(this.token)) ?? process.env?.INTERCOM_API_KEY; + if (token == null) { + throw new errors.IntercomError({ + message: + "Please specify a token by either passing it in to the constructor or initializing a INTERCOM_API_KEY environment variable", + }); + } + + return { + headers: { Authorization: `Bearer ${token}` }, + }; + } +} diff --git a/src/auth/index.ts b/src/auth/index.ts new file mode 100644 index 00000000..0ecb12b7 --- /dev/null +++ b/src/auth/index.ts @@ -0,0 +1 @@ +export { BearerAuthProvider } from "./BearerAuthProvider.js"; diff --git a/src/core/auth/AuthProvider.ts b/src/core/auth/AuthProvider.ts new file mode 100644 index 00000000..895a50ff --- /dev/null +++ b/src/core/auth/AuthProvider.ts @@ -0,0 +1,6 @@ +import type { EndpointMetadata } from "../fetcher/EndpointMetadata.js"; +import type { AuthRequest } from "./AuthRequest.js"; + +export interface AuthProvider { + getAuthRequest(arg?: { endpointMetadata?: EndpointMetadata }): Promise; +} diff --git a/src/core/auth/AuthRequest.ts b/src/core/auth/AuthRequest.ts new file mode 100644 index 00000000..f6218b42 --- /dev/null +++ b/src/core/auth/AuthRequest.ts @@ -0,0 +1,9 @@ +/** + * Request parameters for authentication requests. + */ +export interface AuthRequest { + /** + * The headers to be included in the request. + */ + headers: Record; +} diff --git a/src/core/auth/BasicAuth.ts b/src/core/auth/BasicAuth.ts index 146df215..a6423591 100644 --- a/src/core/auth/BasicAuth.ts +++ b/src/core/auth/BasicAuth.ts @@ -1,4 +1,4 @@ -import { Base64 } from "js-base64"; +import { base64Decode, base64Encode } from "../base64.js"; export interface BasicAuth { username: string; @@ -12,13 +12,14 @@ export const BasicAuth = { if (basicAuth == null) { return undefined; } - const token = Base64.encode(`${basicAuth.username}:${basicAuth.password}`); + const token = base64Encode(`${basicAuth.username}:${basicAuth.password}`); return `Basic ${token}`; }, fromAuthorizationHeader: (header: string): BasicAuth => { const credentials = header.replace(BASIC_AUTH_HEADER_PREFIX, ""); - const decoded = Base64.decode(credentials); - const [username, password] = decoded.split(":", 2); + const decoded = base64Decode(credentials); + const [username, ...passwordParts] = decoded.split(":"); + const password = passwordParts.length > 0 ? passwordParts.join(":") : undefined; if (username == null || password == null) { throw new Error("Invalid basic auth"); diff --git a/src/core/auth/BearerToken.ts b/src/core/auth/BearerToken.ts index fe987fc9..c44a06c3 100644 --- a/src/core/auth/BearerToken.ts +++ b/src/core/auth/BearerToken.ts @@ -2,13 +2,18 @@ export type BearerToken = string; const BEARER_AUTH_HEADER_PREFIX = /^Bearer /i; -export const BearerToken = { - toAuthorizationHeader: (token: BearerToken | undefined): string | undefined => { - if (token == null) { - return undefined; - } - return `Bearer ${token}`; - }, +function toAuthorizationHeader(token: string | undefined): string | undefined { + if (token == null) { + return undefined; + } + return `Bearer ${token}`; +} + +export const BearerToken: { + toAuthorizationHeader: typeof toAuthorizationHeader; + fromAuthorizationHeader: (header: string) => BearerToken; +} = { + toAuthorizationHeader: toAuthorizationHeader, fromAuthorizationHeader: (header: string): BearerToken => { return header.replace(BEARER_AUTH_HEADER_PREFIX, "").trim() as BearerToken; }, diff --git a/src/core/auth/NoOpAuthProvider.ts b/src/core/auth/NoOpAuthProvider.ts new file mode 100644 index 00000000..5b7acfd2 --- /dev/null +++ b/src/core/auth/NoOpAuthProvider.ts @@ -0,0 +1,8 @@ +import type { AuthProvider } from "./AuthProvider.js"; +import type { AuthRequest } from "./AuthRequest.js"; + +export class NoOpAuthProvider implements AuthProvider { + public getAuthRequest(): Promise { + return Promise.resolve({ headers: {} }); + } +} diff --git a/src/core/auth/index.ts b/src/core/auth/index.ts index ee293b34..2215b227 100644 --- a/src/core/auth/index.ts +++ b/src/core/auth/index.ts @@ -1,2 +1,5 @@ -export { BasicAuth } from "./BasicAuth"; -export { BearerToken } from "./BearerToken"; +export type { AuthProvider } from "./AuthProvider.js"; +export type { AuthRequest } from "./AuthRequest.js"; +export { BasicAuth } from "./BasicAuth.js"; +export { BearerToken } from "./BearerToken.js"; +export { NoOpAuthProvider } from "./NoOpAuthProvider.js"; diff --git a/src/core/base64.ts b/src/core/base64.ts new file mode 100644 index 00000000..448a0db6 --- /dev/null +++ b/src/core/base64.ts @@ -0,0 +1,27 @@ +function base64ToBytes(base64: string): Uint8Array { + const binString = atob(base64); + return Uint8Array.from(binString, (m) => m.codePointAt(0)!); +} + +function bytesToBase64(bytes: Uint8Array): string { + const binString = String.fromCodePoint(...bytes); + return btoa(binString); +} + +export function base64Encode(input: string): string { + if (typeof Buffer !== "undefined") { + return Buffer.from(input, "utf8").toString("base64"); + } + + const bytes = new TextEncoder().encode(input); + return bytesToBase64(bytes); +} + +export function base64Decode(input: string): string { + if (typeof Buffer !== "undefined") { + return Buffer.from(input, "base64").toString("utf8"); + } + + const bytes = base64ToBytes(input); + return new TextDecoder().decode(bytes); +} diff --git a/src/core/exports.ts b/src/core/exports.ts new file mode 100644 index 00000000..d2774491 --- /dev/null +++ b/src/core/exports.ts @@ -0,0 +1,2 @@ +export * from "./logging/exports.js"; +export * from "./pagination/exports.js"; diff --git a/src/core/fetcher/APIResponse.ts b/src/core/fetcher/APIResponse.ts index 6335291b..97ab83c2 100644 --- a/src/core/fetcher/APIResponse.ts +++ b/src/core/fetcher/APIResponse.ts @@ -1,4 +1,4 @@ -import { RawResponse } from "./RawResponse"; +import type { RawResponse } from "./RawResponse.js"; /** * The response of an API call. diff --git a/src/core/fetcher/BinaryResponse.ts b/src/core/fetcher/BinaryResponse.ts new file mode 100644 index 00000000..bca7f4c7 --- /dev/null +++ b/src/core/fetcher/BinaryResponse.ts @@ -0,0 +1,34 @@ +export type BinaryResponse = { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + bodyUsed: Response["bodyUsed"]; + /** + * Returns a ReadableStream of the response body. + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) + */ + stream: () => Response["body"]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer: () => ReturnType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob: () => ReturnType; + /** + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) + * Some versions of the Fetch API may not support this method. + */ + bytes?(): ReturnType; +}; + +export function getBinaryResponse(response: Response): BinaryResponse { + const binaryResponse: BinaryResponse = { + get bodyUsed() { + return response.bodyUsed; + }, + stream: () => response.body, + arrayBuffer: response.arrayBuffer.bind(response), + blob: response.blob.bind(response), + }; + if ("bytes" in response && typeof response.bytes === "function") { + binaryResponse.bytes = response.bytes.bind(response); + } + + return binaryResponse; +} diff --git a/src/core/fetcher/EndpointMetadata.ts b/src/core/fetcher/EndpointMetadata.ts new file mode 100644 index 00000000..998d68f5 --- /dev/null +++ b/src/core/fetcher/EndpointMetadata.ts @@ -0,0 +1,13 @@ +export type SecuritySchemeKey = string; +/** + * A collection of security schemes, where the key is the name of the security scheme and the value is the list of scopes required for that scheme. + * All schemes in the collection must be satisfied for authentication to be successful. + */ +export type SecuritySchemeCollection = Record; +export type AuthScope = string; +export type EndpointMetadata = { + /** + * An array of security scheme collections. Each collection represents an alternative way to authenticate. + */ + security?: SecuritySchemeCollection[]; +}; diff --git a/src/core/fetcher/EndpointSupplier.ts b/src/core/fetcher/EndpointSupplier.ts new file mode 100644 index 00000000..8079841c --- /dev/null +++ b/src/core/fetcher/EndpointSupplier.ts @@ -0,0 +1,14 @@ +import type { EndpointMetadata } from "./EndpointMetadata.js"; +import type { Supplier } from "./Supplier.js"; + +type EndpointSupplierFn = (arg: { endpointMetadata: EndpointMetadata }) => T | Promise; +export type EndpointSupplier = Supplier | EndpointSupplierFn; +export const EndpointSupplier = { + get: async (supplier: EndpointSupplier, arg: { endpointMetadata: EndpointMetadata }): Promise => { + if (typeof supplier === "function") { + return (supplier as EndpointSupplierFn)(arg); + } else { + return supplier; + } + }, +}; diff --git a/src/core/fetcher/Fetcher.ts b/src/core/fetcher/Fetcher.ts index 336ee10b..58bb0e3e 100644 --- a/src/core/fetcher/Fetcher.ts +++ b/src/core/fetcher/Fetcher.ts @@ -1,12 +1,17 @@ -import { toJson } from "../json"; -import { APIResponse } from "./APIResponse"; -import { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse"; -import { createRequestUrl } from "./createRequestUrl"; -import { getFetchFn } from "./getFetchFn"; -import { getRequestBody } from "./getRequestBody"; -import { getResponseBody } from "./getResponseBody"; -import { makeRequest } from "./makeRequest"; -import { requestWithRetries } from "./requestWithRetries"; +import { toJson } from "../json.js"; +import { createLogger, type LogConfig, type Logger } from "../logging/logger.js"; +import type { APIResponse } from "./APIResponse.js"; +import { createRequestUrl } from "./createRequestUrl.js"; +import type { EndpointMetadata } from "./EndpointMetadata.js"; +import { EndpointSupplier } from "./EndpointSupplier.js"; +import { getErrorResponseBody } from "./getErrorResponseBody.js"; +import { getFetchFn } from "./getFetchFn.js"; +import { getRequestBody } from "./getRequestBody.js"; +import { getResponseBody } from "./getResponseBody.js"; +import { Headers } from "./Headers.js"; +import { makeRequest } from "./makeRequest.js"; +import { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse.js"; +import { requestWithRetries } from "./requestWithRetries.js"; export type FetchFunction = (args: Fetcher.Args) => Promise>; @@ -15,19 +20,22 @@ export declare namespace Fetcher { url: string; method: string; contentType?: string; - headers?: Record; - queryParameters?: Record; + headers?: Record | null | undefined>; + queryParameters?: Record; body?: unknown; timeoutMs?: number; maxRetries?: number; withCredentials?: boolean; abortSignal?: AbortSignal; - requestType?: "json" | "file" | "bytes"; - responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer"; + requestType?: "json" | "file" | "bytes" | "form" | "other"; + responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer" | "binary-response"; duplex?: "half"; + endpointMetadata?: EndpointMetadata; + fetchFn?: typeof fetch; + logging?: LogConfig | Logger; } - export type Error = FailedStatusCodeError | NonJsonError | TimeoutError | UnknownError; + export type Error = FailedStatusCodeError | NonJsonError | BodyIsNullError | TimeoutError | UnknownError; export interface FailedStatusCodeError { reason: "status-code"; @@ -41,6 +49,11 @@ export declare namespace Fetcher { rawBody: string; } + export interface BodyIsNullError { + reason: "body-is-null"; + statusCode: number; + } + export interface TimeoutError { reason: "timeout"; } @@ -51,26 +64,204 @@ export declare namespace Fetcher { } } -export async function fetcherImpl(args: Fetcher.Args): Promise> { - const headers: Record = {}; +const SENSITIVE_HEADERS = new Set([ + "authorization", + "www-authenticate", + "x-api-key", + "api-key", + "apikey", + "x-api-token", + "x-auth-token", + "auth-token", + "cookie", + "set-cookie", + "proxy-authorization", + "proxy-authenticate", + "x-csrf-token", + "x-xsrf-token", + "x-session-token", + "x-access-token", +]); + +function redactHeaders(headers: Headers | Record): Record { + const filtered: Record = {}; + for (const [key, value] of headers instanceof Headers ? headers.entries() : Object.entries(headers)) { + if (SENSITIVE_HEADERS.has(key.toLowerCase())) { + filtered[key] = "[REDACTED]"; + } else { + filtered[key] = value; + } + } + return filtered; +} + +const SENSITIVE_QUERY_PARAMS = new Set([ + "api_key", + "api-key", + "apikey", + "token", + "access_token", + "access-token", + "auth_token", + "auth-token", + "password", + "passwd", + "secret", + "api_secret", + "api-secret", + "apisecret", + "key", + "session", + "session_id", + "session-id", +]); + +function redactQueryParameters(queryParameters?: Record): Record | undefined { + if (queryParameters == null) { + return queryParameters; + } + const redacted: Record = {}; + for (const [key, value] of Object.entries(queryParameters)) { + if (SENSITIVE_QUERY_PARAMS.has(key.toLowerCase())) { + redacted[key] = "[REDACTED]"; + } else { + redacted[key] = value; + } + } + return redacted; +} + +function redactUrl(url: string): string { + const protocolIndex = url.indexOf("://"); + if (protocolIndex === -1) return url; + + const afterProtocol = protocolIndex + 3; + + // Find the first delimiter that marks the end of the authority section + const pathStart = url.indexOf("/", afterProtocol); + let queryStart = url.indexOf("?", afterProtocol); + let fragmentStart = url.indexOf("#", afterProtocol); + + const firstDelimiter = Math.min( + pathStart === -1 ? url.length : pathStart, + queryStart === -1 ? url.length : queryStart, + fragmentStart === -1 ? url.length : fragmentStart, + ); + + // Find the LAST @ before the delimiter (handles multiple @ in credentials) + let atIndex = -1; + for (let i = afterProtocol; i < firstDelimiter; i++) { + if (url[i] === "@") { + atIndex = i; + } + } + + if (atIndex !== -1) { + url = `${url.slice(0, afterProtocol)}[REDACTED]@${url.slice(atIndex + 1)}`; + } + + // Recalculate queryStart since url might have changed + queryStart = url.indexOf("?"); + if (queryStart === -1) return url; + + fragmentStart = url.indexOf("#", queryStart); + const queryEnd = fragmentStart !== -1 ? fragmentStart : url.length; + const queryString = url.slice(queryStart + 1, queryEnd); + + if (queryString.length === 0) return url; + + // FAST PATH: Quick check if any sensitive keywords present + // Using indexOf is faster than regex for simple substring matching + const lower = queryString.toLowerCase(); + const hasSensitive = + lower.includes("token") || + lower.includes("key") || + lower.includes("password") || + lower.includes("passwd") || + lower.includes("secret") || + lower.includes("session") || + lower.includes("auth"); + + if (!hasSensitive) { + return url; + } + + // SLOW PATH: Parse and redact + const redactedParams: string[] = []; + const params = queryString.split("&"); + + for (const param of params) { + const equalIndex = param.indexOf("="); + if (equalIndex === -1) { + redactedParams.push(param); + continue; + } + + const key = param.slice(0, equalIndex); + let shouldRedact = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase()); + + if (!shouldRedact && key.includes("%")) { + try { + const decodedKey = decodeURIComponent(key); + shouldRedact = SENSITIVE_QUERY_PARAMS.has(decodedKey.toLowerCase()); + } catch {} + } + + redactedParams.push(shouldRedact ? `${key}=[REDACTED]` : param); + } + + return url.slice(0, queryStart + 1) + redactedParams.join("&") + url.slice(queryEnd); +} + +async function getHeaders(args: Fetcher.Args): Promise { + const newHeaders: Headers = new Headers(); + + newHeaders.set( + "Accept", + args.responseType === "json" ? "application/json" : args.responseType === "text" ? "text/plain" : "*/*", + ); if (args.body !== undefined && args.contentType != null) { - headers["Content-Type"] = args.contentType; + newHeaders.set("Content-Type", args.contentType); } - if (args.headers != null) { - for (const [key, value] of Object.entries(args.headers)) { - if (value != null) { - headers[key] = value; - } + if (args.headers == null) { + return newHeaders; + } + + for (const [key, value] of Object.entries(args.headers)) { + const result = await EndpointSupplier.get(value, { endpointMetadata: args.endpointMetadata ?? {} }); + if (typeof result === "string") { + newHeaders.set(key, result); + continue; + } + if (result == null) { + continue; } + newHeaders.set(key, `${result}`); } + return newHeaders; +} +export async function fetcherImpl(args: Fetcher.Args): Promise> { const url = createRequestUrl(args.url, args.queryParameters); const requestBody: BodyInit | undefined = await getRequestBody({ body: args.body, - type: args.requestType === "json" ? "json" : "other", + type: args.requestType ?? "other", }); - const fetchFn = await getFetchFn(); + const fetchFn = args.fetchFn ?? (await getFetchFn()); + const headers = await getHeaders(args); + const logger = createLogger(args.logging); + + if (logger.isDebug()) { + const metadata = { + method: args.method, + url: redactUrl(url), + headers: redactHeaders(headers), + queryParameters: redactQueryParameters(args.queryParameters), + hasBody: requestBody != null, + }; + logger.debug("Making HTTP request", metadata); + } try { const response = await requestWithRetries( @@ -88,28 +279,53 @@ export async function fetcherImpl(args: Fetcher.Args): Promise= 200 && response.status < 400) { + if (logger.isDebug()) { + const metadata = { + method: args.method, + url: redactUrl(url), + statusCode: response.status, + responseHeaders: redactHeaders(response.headers), + }; + logger.debug("HTTP request succeeded", metadata); + } + const body = await getResponseBody(response, args.responseType); return { ok: true, - body: responseBody as R, + body: body as R, headers: response.headers, rawResponse: toRawResponse(response), }; } else { + if (logger.isError()) { + const metadata = { + method: args.method, + url: redactUrl(url), + statusCode: response.status, + responseHeaders: redactHeaders(Object.fromEntries(response.headers.entries())), + }; + logger.error("HTTP request failed with error status", metadata); + } return { ok: false, error: { reason: "status-code", statusCode: response.status, - body: responseBody, + body: await getErrorResponseBody(response), }, rawResponse: toRawResponse(response), }; } } catch (error) { - if (args.abortSignal != null && args.abortSignal.aborted) { + if (args.abortSignal?.aborted) { + if (logger.isError()) { + const metadata = { + method: args.method, + url: redactUrl(url), + }; + logger.error("HTTP request was aborted", metadata); + } return { ok: false, error: { @@ -119,6 +335,14 @@ export async function fetcherImpl(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise, -): string { - return Object.keys(queryParameters ?? {}).length > 0 - ? `${baseUrl}?${qs.stringify(queryParameters, { arrayFormat: "repeat" })}` - : baseUrl; +export function createRequestUrl(baseUrl: string, queryParameters?: Record): string { + const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" }); + return queryString ? `${baseUrl}?${queryString}` : baseUrl; } diff --git a/src/core/fetcher/getErrorResponseBody.ts b/src/core/fetcher/getErrorResponseBody.ts new file mode 100644 index 00000000..7cf4e623 --- /dev/null +++ b/src/core/fetcher/getErrorResponseBody.ts @@ -0,0 +1,33 @@ +import { fromJson } from "../json.js"; +import { getResponseBody } from "./getResponseBody.js"; + +export async function getErrorResponseBody(response: Response): Promise { + let contentType = response.headers.get("Content-Type")?.toLowerCase(); + if (contentType == null || contentType.length === 0) { + return getResponseBody(response); + } + + if (contentType.indexOf(";") !== -1) { + contentType = contentType.split(";")[0]?.trim() ?? ""; + } + switch (contentType) { + case "application/hal+json": + case "application/json": + case "application/ld+json": + case "application/problem+json": + case "application/vnd.api+json": + case "text/json": { + const text = await response.text(); + return text.length > 0 ? fromJson(text) : undefined; + } + default: + if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) { + const text = await response.text(); + return text.length > 0 ? fromJson(text) : undefined; + } + + // Fallback to plain text if content type is not recognized + // Even if no body is present, the response will be an empty string + return await response.text(); + } +} diff --git a/src/core/fetcher/getFetchFn.ts b/src/core/fetcher/getFetchFn.ts index 9fd9bfc4..9f845b95 100644 --- a/src/core/fetcher/getFetchFn.ts +++ b/src/core/fetcher/getFetchFn.ts @@ -1,25 +1,3 @@ -import { RUNTIME } from "../runtime"; - -/** - * Returns a fetch function based on the runtime - */ -export async function getFetchFn(): Promise { - // In Node.js 18+ environments, use native fetch - if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { - return fetch; - } - - // In Node.js 18 or lower environments, the SDK always uses`node-fetch`. - if (RUNTIME.type === "node") { - return (await import("node-fetch")).default as any; - } - - // Otherwise the SDK uses global fetch if available, - // and falls back to node-fetch. - if (typeof fetch == "function") { - return fetch; - } - - // Defaults to node `node-fetch` if global fetch isn't available - return (await import("node-fetch")).default as any; +export async function getFetchFn(): Promise { + return fetch; } diff --git a/src/core/fetcher/getRequestBody.ts b/src/core/fetcher/getRequestBody.ts index fce5589c..91d9d81f 100644 --- a/src/core/fetcher/getRequestBody.ts +++ b/src/core/fetcher/getRequestBody.ts @@ -1,13 +1,17 @@ -import { toJson } from "../json"; +import { toJson } from "../json.js"; +import { toQueryString } from "../url/qs.js"; export declare namespace GetRequestBody { interface Args { body: unknown; - type: "json" | "file" | "bytes" | "other"; + type: "json" | "file" | "bytes" | "form" | "other"; } } export async function getRequestBody({ body, type }: GetRequestBody.Args): Promise { + if (type === "form") { + return toQueryString(body, { arrayFormat: "repeat", encode: true }); + } if (type.includes("json")) { return toJson(body); } else { diff --git a/src/core/fetcher/getResponseBody.ts b/src/core/fetcher/getResponseBody.ts index d046e6ea..708d5572 100644 --- a/src/core/fetcher/getResponseBody.ts +++ b/src/core/fetcher/getResponseBody.ts @@ -1,34 +1,58 @@ -import { chooseStreamWrapper } from "./stream-wrappers/chooseStreamWrapper"; +import { fromJson } from "../json.js"; +import { getBinaryResponse } from "./BinaryResponse.js"; export async function getResponseBody(response: Response, responseType?: string): Promise { - if (response.body != null && responseType === "blob") { - return await response.blob(); - } else if (response.body != null && responseType === "arrayBuffer") { - return await response.arrayBuffer(); - } else if (response.body != null && responseType === "sse") { - return response.body; - } else if (response.body != null && responseType === "streaming") { - return chooseStreamWrapper(response.body); - } else if (response.body != null && responseType === "text") { - return await response.text(); - } else { - const text = await response.text(); - if (text.length > 0) { - try { - let responseBody = JSON.parse(text); - return responseBody; - } catch (err) { + switch (responseType) { + case "binary-response": + return getBinaryResponse(response); + case "blob": + return await response.blob(); + case "arrayBuffer": + return await response.arrayBuffer(); + case "sse": + if (response.body == null) { return { ok: false, error: { - reason: "non-json", + reason: "body-is-null", statusCode: response.status, - rawBody: text, }, }; } - } else { - return undefined; + return response.body; + case "streaming": + if (response.body == null) { + return { + ok: false, + error: { + reason: "body-is-null", + statusCode: response.status, + }, + }; + } + + return response.body; + + case "text": + return await response.text(); + } + + // if responseType is "json" or not specified, try to parse as JSON + const text = await response.text(); + if (text.length > 0) { + try { + const responseBody = fromJson(text); + return responseBody; + } catch (_err) { + return { + ok: false, + error: { + reason: "non-json", + statusCode: response.status, + rawBody: text, + }, + }; } } + return undefined; } diff --git a/src/core/fetcher/index.ts b/src/core/fetcher/index.ts index 249f5176..c3bc6da2 100644 --- a/src/core/fetcher/index.ts +++ b/src/core/fetcher/index.ts @@ -1,8 +1,11 @@ -export type { APIResponse } from "./APIResponse"; -export { fetcher } from "./Fetcher"; -export type { Fetcher, FetchFunction } from "./Fetcher"; -export { getHeader } from "./getHeader"; -export { Supplier } from "./Supplier"; -export { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse"; -export type { RawResponse, WithRawResponse } from "./RawResponse"; -export { HttpResponsePromise } from "./HttpResponsePromise"; +export type { APIResponse } from "./APIResponse.js"; +export type { BinaryResponse } from "./BinaryResponse.js"; +export type { EndpointMetadata } from "./EndpointMetadata.js"; +export { EndpointSupplier } from "./EndpointSupplier.js"; +export type { Fetcher, FetchFunction } from "./Fetcher.js"; +export { fetcher } from "./Fetcher.js"; +export { getHeader } from "./getHeader.js"; +export { HttpResponsePromise } from "./HttpResponsePromise.js"; +export type { RawResponse, WithRawResponse } from "./RawResponse.js"; +export { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse.js"; +export { Supplier } from "./Supplier.js"; diff --git a/src/core/fetcher/makeRequest.ts b/src/core/fetcher/makeRequest.ts index 1af42bb9..921565eb 100644 --- a/src/core/fetcher/makeRequest.ts +++ b/src/core/fetcher/makeRequest.ts @@ -1,10 +1,10 @@ -import { anySignal, getTimeoutSignal } from "./signals"; +import { anySignal, getTimeoutSignal } from "./signals.js"; export const makeRequest = async ( fetchFn: (url: string, init: RequestInit) => Promise, url: string, method: string, - headers: Record, + headers: Headers | Record, requestBody: BodyInit | undefined, timeoutMs?: number, abortSignal?: AbortSignal, @@ -13,19 +13,17 @@ export const makeRequest = async ( ): Promise => { const signals: AbortSignal[] = []; - // Add timeout signal - let timeoutAbortId: NodeJS.Timeout | undefined = undefined; + let timeoutAbortId: ReturnType | undefined; if (timeoutMs != null) { const { signal, abortId } = getTimeoutSignal(timeoutMs); timeoutAbortId = abortId; signals.push(signal); } - // Add arbitrary signal if (abortSignal != null) { signals.push(abortSignal); } - let newSignals = anySignal(signals); + const newSignals = anySignal(signals); const response = await fetchFn(url, { method: method, headers, diff --git a/src/core/fetcher/requestWithRetries.ts b/src/core/fetcher/requestWithRetries.ts index add3cce0..1f689688 100644 --- a/src/core/fetcher/requestWithRetries.ts +++ b/src/core/fetcher/requestWithRetries.ts @@ -3,12 +3,47 @@ const MAX_RETRY_DELAY = 60000; // in milliseconds const DEFAULT_MAX_RETRIES = 2; const JITTER_FACTOR = 0.2; // 20% random jitter -function addJitter(delay: number): number { - // Generate a random value between -JITTER_FACTOR and +JITTER_FACTOR - const jitterMultiplier = 1 + (Math.random() * 2 - 1) * JITTER_FACTOR; +function addPositiveJitter(delay: number): number { + const jitterMultiplier = 1 + Math.random() * JITTER_FACTOR; return delay * jitterMultiplier; } +function addSymmetricJitter(delay: number): number { + const jitterMultiplier = 1 + (Math.random() - 0.5) * JITTER_FACTOR; + return delay * jitterMultiplier; +} + +function getRetryDelayFromHeaders(response: Response, retryAttempt: number): number { + const retryAfter = response.headers.get("Retry-After"); + if (retryAfter) { + const retryAfterSeconds = parseInt(retryAfter, 10); + if (!Number.isNaN(retryAfterSeconds) && retryAfterSeconds > 0) { + return Math.min(retryAfterSeconds * 1000, MAX_RETRY_DELAY); + } + + const retryAfterDate = new Date(retryAfter); + if (!Number.isNaN(retryAfterDate.getTime())) { + const delay = retryAfterDate.getTime() - Date.now(); + if (delay > 0) { + return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY); + } + } + } + + const rateLimitReset = response.headers.get("X-RateLimit-Reset"); + if (rateLimitReset) { + const resetTime = parseInt(rateLimitReset, 10); + if (!Number.isNaN(resetTime)) { + const delay = resetTime * 1000 - Date.now(); + if (delay > 0) { + return addPositiveJitter(Math.min(delay, MAX_RETRY_DELAY)); + } + } + } + + return addSymmetricJitter(Math.min(INITIAL_RETRY_DELAY * 2 ** retryAttempt, MAX_RETRY_DELAY)); +} + export async function requestWithRetries( requestFn: () => Promise, maxRetries: number = DEFAULT_MAX_RETRIES, @@ -17,13 +52,9 @@ export async function requestWithRetries( for (let i = 0; i < maxRetries; ++i) { if ([408, 429].includes(response.status) || response.status >= 500) { - // Calculate base delay using exponential backoff (in milliseconds) - const baseDelay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i), MAX_RETRY_DELAY); - - // Add jitter to the delay - const delayWithJitter = addJitter(baseDelay); + const delay = getRetryDelayFromHeaders(response, i); - await new Promise((resolve) => setTimeout(resolve, delayWithJitter)); + await new Promise((resolve) => setTimeout(resolve, delay)); response = await requestFn(); } else { break; diff --git a/src/core/fetcher/signals.ts b/src/core/fetcher/signals.ts index a8d32a2e..7bd3757e 100644 --- a/src/core/fetcher/signals.ts +++ b/src/core/fetcher/signals.ts @@ -1,34 +1,22 @@ const TIMEOUT = "timeout"; -export function getTimeoutSignal(timeoutMs: number): { signal: AbortSignal; abortId: NodeJS.Timeout } { +export function getTimeoutSignal(timeoutMs: number): { signal: AbortSignal; abortId: ReturnType } { const controller = new AbortController(); const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs); return { signal: controller.signal, abortId }; } -/** - * Returns an abort signal that is getting aborted when - * at least one of the specified abort signals is aborted. - * - * Requires at least node.js 18. - */ export function anySignal(...args: AbortSignal[] | [AbortSignal[]]): AbortSignal { - // Allowing signals to be passed either as array - // of signals or as multiple arguments. const signals = (args.length === 1 && Array.isArray(args[0]) ? args[0] : args) as AbortSignal[]; const controller = new AbortController(); for (const signal of signals) { if (signal.aborted) { - // Exiting early if one of the signals - // is already aborted. controller.abort((signal as any)?.reason); break; } - // Listening for signals and removing the listeners - // when at least one symbol is aborted. signal.addEventListener("abort", () => controller.abort((signal as any)?.reason), { signal: controller.signal, }); diff --git a/src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts b/src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts deleted file mode 100644 index 6f1a82e9..00000000 --- a/src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.ts +++ /dev/null @@ -1,257 +0,0 @@ -import type { Writable } from "readable-stream"; - -import { EventCallback, StreamWrapper } from "./chooseStreamWrapper"; - -export class Node18UniversalStreamWrapper - implements - StreamWrapper | Writable | WritableStream, ReadFormat> -{ - private readableStream: ReadableStream; - private reader: ReadableStreamDefaultReader; - private events: Record; - private paused: boolean; - private resumeCallback: ((value?: unknown) => void) | null; - private encoding: string | null; - - constructor(readableStream: ReadableStream) { - this.readableStream = readableStream; - this.reader = this.readableStream.getReader(); - this.events = { - data: [], - end: [], - error: [], - readable: [], - close: [], - pause: [], - resume: [], - }; - this.paused = false; - this.resumeCallback = null; - this.encoding = null; - } - - public on(event: string, callback: EventCallback): void { - this.events[event]?.push(callback); - } - - public off(event: string, callback: EventCallback): void { - this.events[event] = this.events[event]?.filter((cb) => cb !== callback); - } - - public pipe( - dest: Node18UniversalStreamWrapper | Writable | WritableStream, - ): Node18UniversalStreamWrapper | Writable | WritableStream { - this.on("data", async (chunk) => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._write(chunk); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.write(chunk).then(() => writer.releaseLock()); - } else { - dest.write(chunk); - } - }); - - this.on("end", async () => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._end(); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.close(); - } else { - dest.end(); - } - }); - - this.on("error", async (error) => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._error(error); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.abort(error); - } else { - dest.destroy(error); - } - }); - - this._startReading(); - - return dest; - } - - public pipeTo( - dest: Node18UniversalStreamWrapper | Writable | WritableStream, - ): Node18UniversalStreamWrapper | Writable | WritableStream { - return this.pipe(dest); - } - - public unpipe(dest: Node18UniversalStreamWrapper | Writable | WritableStream): void { - this.off("data", async (chunk) => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._write(chunk); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.write(chunk).then(() => writer.releaseLock()); - } else { - dest.write(chunk); - } - }); - - this.off("end", async () => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._end(); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.close(); - } else { - dest.end(); - } - }); - - this.off("error", async (error) => { - if (dest instanceof Node18UniversalStreamWrapper) { - dest._error(error); - } else if (dest instanceof WritableStream) { - const writer = dest.getWriter(); - writer.abort(error); - } else { - dest.destroy(error); - } - }); - } - - public destroy(error?: Error): void { - this.reader - .cancel(error) - .then(() => { - this._emit("close"); - }) - .catch((err) => { - this._emit("error", err); - }); - } - - public pause(): void { - this.paused = true; - this._emit("pause"); - } - - public resume(): void { - if (this.paused) { - this.paused = false; - this._emit("resume"); - if (this.resumeCallback) { - this.resumeCallback(); - this.resumeCallback = null; - } - } - } - - public get isPaused(): boolean { - return this.paused; - } - - public async read(): Promise { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - - if (done) { - return undefined; - } - return value; - } - - public setEncoding(encoding: string): void { - this.encoding = encoding; - } - - public async text(): Promise { - const chunks: ReadFormat[] = []; - - while (true) { - const { done, value } = await this.reader.read(); - if (done) { - break; - } - if (value) { - chunks.push(value); - } - } - - const decoder = new TextDecoder(this.encoding || "utf-8"); - return decoder.decode(await new Blob(chunks).arrayBuffer()); - } - - public async json(): Promise { - const text = await this.text(); - return JSON.parse(text); - } - - private _write(chunk: ReadFormat): void { - this._emit("data", chunk); - } - - private _end(): void { - this._emit("end"); - } - - private _error(error: any): void { - this._emit("error", error); - } - - private _emit(event: string, data?: any): void { - if (this.events[event]) { - for (const callback of this.events[event] || []) { - callback(data); - } - } - } - - private async _startReading(): Promise { - try { - this._emit("readable"); - while (true) { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - if (done) { - this._emit("end"); - this._emit("close"); - break; - } - if (value) { - this._emit("data", value); - } - } - } catch (error) { - this._emit("error", error); - } - } - - [Symbol.asyncIterator](): AsyncIterableIterator { - return { - next: async () => { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - if (done) { - return { done: true, value: undefined }; - } - return { done: false, value }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; - } -} diff --git a/src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts b/src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts deleted file mode 100644 index 23c01a1a..00000000 --- a/src/core/fetcher/stream-wrappers/NodePre18StreamWrapper.ts +++ /dev/null @@ -1,107 +0,0 @@ -import type { Readable, Writable } from "readable-stream"; - -import { EventCallback, StreamWrapper } from "./chooseStreamWrapper"; - -export class NodePre18StreamWrapper implements StreamWrapper { - private readableStream: Readable; - private encoding: string | undefined; - - constructor(readableStream: Readable) { - this.readableStream = readableStream; - } - - public on(event: string, callback: EventCallback): void { - this.readableStream.on(event, callback); - } - - public off(event: string, callback: EventCallback): void { - this.readableStream.off(event, callback); - } - - public pipe(dest: Writable): Writable { - this.readableStream.pipe(dest); - return dest; - } - - public pipeTo(dest: Writable): Writable { - return this.pipe(dest); - } - - public unpipe(dest?: Writable): void { - if (dest) { - this.readableStream.unpipe(dest); - } else { - this.readableStream.unpipe(); - } - } - - public destroy(error?: Error): void { - this.readableStream.destroy(error); - } - - public pause(): void { - this.readableStream.pause(); - } - - public resume(): void { - this.readableStream.resume(); - } - - public get isPaused(): boolean { - return this.readableStream.isPaused(); - } - - public async read(): Promise { - return new Promise((resolve, reject) => { - const chunk = this.readableStream.read(); - if (chunk) { - resolve(chunk); - } else { - this.readableStream.once("readable", () => { - const chunk = this.readableStream.read(); - resolve(chunk); - }); - this.readableStream.once("error", reject); - } - }); - } - - public setEncoding(encoding?: string): void { - this.readableStream.setEncoding(encoding as BufferEncoding); - this.encoding = encoding; - } - - public async text(): Promise { - const chunks: Uint8Array[] = []; - const encoder = new TextEncoder(); - this.readableStream.setEncoding((this.encoding || "utf-8") as BufferEncoding); - - for await (const chunk of this.readableStream) { - chunks.push(encoder.encode(chunk)); - } - - const decoder = new TextDecoder(this.encoding || "utf-8"); - return decoder.decode(Buffer.concat(chunks)); - } - - public async json(): Promise { - const text = await this.text(); - return JSON.parse(text); - } - - public [Symbol.asyncIterator](): AsyncIterableIterator { - const readableStream = this.readableStream; - const iterator = readableStream[Symbol.asyncIterator](); - - // Create and return an async iterator that yields buffers - return { - async next(): Promise> { - const { value, done } = await iterator.next(); - return { value: value as Buffer, done }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; - } -} diff --git a/src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts b/src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts deleted file mode 100644 index 091e2a7f..00000000 --- a/src/core/fetcher/stream-wrappers/UndiciStreamWrapper.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { StreamWrapper } from "./chooseStreamWrapper"; - -type EventCallback = (data?: any) => void; - -export class UndiciStreamWrapper - implements StreamWrapper | WritableStream, ReadFormat> -{ - private readableStream: ReadableStream; - private reader: ReadableStreamDefaultReader; - private events: Record; - private paused: boolean; - private resumeCallback: ((value?: unknown) => void) | null; - private encoding: string | null; - - constructor(readableStream: ReadableStream) { - this.readableStream = readableStream; - this.reader = this.readableStream.getReader(); - this.events = { - data: [], - end: [], - error: [], - readable: [], - close: [], - pause: [], - resume: [], - }; - this.paused = false; - this.resumeCallback = null; - this.encoding = null; - } - - public on(event: string, callback: EventCallback): void { - this.events[event]?.push(callback); - } - - public off(event: string, callback: EventCallback): void { - this.events[event] = this.events[event]?.filter((cb) => cb !== callback); - } - - public pipe( - dest: UndiciStreamWrapper | WritableStream, - ): UndiciStreamWrapper | WritableStream { - this.on("data", (chunk) => { - if (dest instanceof UndiciStreamWrapper) { - dest._write(chunk); - } else { - const writer = dest.getWriter(); - writer.write(chunk).then(() => writer.releaseLock()); - } - }); - - this.on("end", () => { - if (dest instanceof UndiciStreamWrapper) { - dest._end(); - } else { - const writer = dest.getWriter(); - writer.close(); - } - }); - - this.on("error", (error) => { - if (dest instanceof UndiciStreamWrapper) { - dest._error(error); - } else { - const writer = dest.getWriter(); - writer.abort(error); - } - }); - - this._startReading(); - - return dest; - } - - public pipeTo( - dest: UndiciStreamWrapper | WritableStream, - ): UndiciStreamWrapper | WritableStream { - return this.pipe(dest); - } - - public unpipe(dest: UndiciStreamWrapper | WritableStream): void { - this.off("data", (chunk) => { - if (dest instanceof UndiciStreamWrapper) { - dest._write(chunk); - } else { - const writer = dest.getWriter(); - writer.write(chunk).then(() => writer.releaseLock()); - } - }); - - this.off("end", () => { - if (dest instanceof UndiciStreamWrapper) { - dest._end(); - } else { - const writer = dest.getWriter(); - writer.close(); - } - }); - - this.off("error", (error) => { - if (dest instanceof UndiciStreamWrapper) { - dest._error(error); - } else { - const writer = dest.getWriter(); - writer.abort(error); - } - }); - } - - public destroy(error?: Error): void { - this.reader - .cancel(error) - .then(() => { - this._emit("close"); - }) - .catch((err) => { - this._emit("error", err); - }); - } - - public pause(): void { - this.paused = true; - this._emit("pause"); - } - - public resume(): void { - if (this.paused) { - this.paused = false; - this._emit("resume"); - if (this.resumeCallback) { - this.resumeCallback(); - this.resumeCallback = null; - } - } - } - - public get isPaused(): boolean { - return this.paused; - } - - public async read(): Promise { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - if (done) { - return undefined; - } - return value; - } - - public setEncoding(encoding: string): void { - this.encoding = encoding; - } - - public async text(): Promise { - const chunks: BlobPart[] = []; - - while (true) { - const { done, value } = await this.reader.read(); - if (done) { - break; - } - if (value) { - chunks.push(value); - } - } - - const decoder = new TextDecoder(this.encoding || "utf-8"); - return decoder.decode(await new Blob(chunks).arrayBuffer()); - } - - public async json(): Promise { - const text = await this.text(); - return JSON.parse(text); - } - - private _write(chunk: ReadFormat): void { - this._emit("data", chunk); - } - - private _end(): void { - this._emit("end"); - } - - private _error(error: any): void { - this._emit("error", error); - } - - private _emit(event: string, data?: any): void { - if (this.events[event]) { - for (const callback of this.events[event] || []) { - callback(data); - } - } - } - - private async _startReading(): Promise { - try { - this._emit("readable"); - while (true) { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - if (done) { - this._emit("end"); - this._emit("close"); - break; - } - if (value) { - this._emit("data", value); - } - } - } catch (error) { - this._emit("error", error); - } - } - - [Symbol.asyncIterator](): AsyncIterableIterator { - return { - next: async () => { - if (this.paused) { - await new Promise((resolve) => { - this.resumeCallback = resolve; - }); - } - const { done, value } = await this.reader.read(); - if (done) { - return { done: true, value: undefined }; - } - return { done: false, value }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; - } -} diff --git a/src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts b/src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts deleted file mode 100644 index 8c7492fc..00000000 --- a/src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { Readable } from "readable-stream"; - -import { RUNTIME } from "../../runtime"; - -export type EventCallback = (data?: any) => void; - -export interface StreamWrapper { - setEncoding(encoding?: string): void; - on(event: string, callback: EventCallback): void; - off(event: string, callback: EventCallback): void; - pipe(dest: WritableStream): WritableStream; - pipeTo(dest: WritableStream): WritableStream; - unpipe(dest?: WritableStream): void; - destroy(error?: Error): void; - pause(): void; - resume(): void; - get isPaused(): boolean; - read(): Promise; - text(): Promise; - json(): Promise; - [Symbol.asyncIterator](): AsyncIterableIterator; -} - -export async function chooseStreamWrapper(responseBody: any): Promise>> { - if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { - return new (await import("./Node18UniversalStreamWrapper")).Node18UniversalStreamWrapper( - responseBody as ReadableStream, - ); - } else if (RUNTIME.type !== "node" && typeof fetch === "function") { - return new (await import("./UndiciStreamWrapper")).UndiciStreamWrapper(responseBody as ReadableStream); - } else { - return new (await import("./NodePre18StreamWrapper")).NodePre18StreamWrapper(responseBody as Readable); - } -} diff --git a/src/core/headers.ts b/src/core/headers.ts new file mode 100644 index 00000000..78ed8b50 --- /dev/null +++ b/src/core/headers.ts @@ -0,0 +1,35 @@ +export function mergeHeaders( + ...headersArray: (Record | null | undefined)[] +): Record { + const result: Record = {}; + + for (const [key, value] of headersArray + .filter((headers) => headers != null) + .flatMap((headers) => Object.entries(headers))) { + const insensitiveKey = key.toLowerCase(); + if (value != null) { + result[insensitiveKey] = value; + } else if (insensitiveKey in result) { + delete result[insensitiveKey]; + } + } + + return result; +} + +export function mergeOnlyDefinedHeaders( + ...headersArray: (Record | null | undefined)[] +): Record { + const result: Record = {}; + + for (const [key, value] of headersArray + .filter((headers) => headers != null) + .flatMap((headers) => Object.entries(headers))) { + const insensitiveKey = key.toLowerCase(); + if (value != null) { + result[insensitiveKey] = value; + } + } + + return result; +} diff --git a/src/core/index.ts b/src/core/index.ts index 466b3c3a..f25662a5 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,5 +1,8 @@ -export * from "./fetcher"; -export * from "./runtime"; -export * from "./auth"; -export * from "./utils"; -export * from "./pagination"; +export * from "./auth/index.js"; +export * from "./base64.js"; +export * from "./fetcher/index.js"; +export * as logging from "./logging/index.js"; +export * from "./pagination/index.js"; +export * from "./runtime/index.js"; +export * as url from "./url/index.js"; +export * from "./utils/index.js"; diff --git a/src/core/logging/exports.ts b/src/core/logging/exports.ts new file mode 100644 index 00000000..88f6c00d --- /dev/null +++ b/src/core/logging/exports.ts @@ -0,0 +1,19 @@ +import * as logger from "./logger.js"; + +export namespace logging { + /** + * Configuration for logger instances. + */ + export type LogConfig = logger.LogConfig; + export type LogLevel = logger.LogLevel; + export const LogLevel: typeof logger.LogLevel = logger.LogLevel; + export type ILogger = logger.ILogger; + /** + * Console logger implementation that outputs to the console. + */ + export type ConsoleLogger = logger.ConsoleLogger; + /** + * Console logger implementation that outputs to the console. + */ + export const ConsoleLogger: typeof logger.ConsoleLogger = logger.ConsoleLogger; +} diff --git a/src/core/logging/index.ts b/src/core/logging/index.ts new file mode 100644 index 00000000..d81cc32c --- /dev/null +++ b/src/core/logging/index.ts @@ -0,0 +1 @@ +export * from "./logger.js"; diff --git a/src/core/logging/logger.ts b/src/core/logging/logger.ts new file mode 100644 index 00000000..a3f3673c --- /dev/null +++ b/src/core/logging/logger.ts @@ -0,0 +1,203 @@ +export const LogLevel = { + Debug: "debug", + Info: "info", + Warn: "warn", + Error: "error", +} as const; +export type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]; +const logLevelMap: Record = { + [LogLevel.Debug]: 1, + [LogLevel.Info]: 2, + [LogLevel.Warn]: 3, + [LogLevel.Error]: 4, +}; + +export interface ILogger { + /** + * Logs a debug message. + * @param message - The message to log + * @param args - Additional arguments to log + */ + debug(message: string, ...args: unknown[]): void; + /** + * Logs an info message. + * @param message - The message to log + * @param args - Additional arguments to log + */ + info(message: string, ...args: unknown[]): void; + /** + * Logs a warning message. + * @param message - The message to log + * @param args - Additional arguments to log + */ + warn(message: string, ...args: unknown[]): void; + /** + * Logs an error message. + * @param message - The message to log + * @param args - Additional arguments to log + */ + error(message: string, ...args: unknown[]): void; +} + +/** + * Configuration for logger initialization. + */ +export interface LogConfig { + /** + * Minimum log level to output. + * @default LogLevel.Info + */ + level?: LogLevel; + /** + * Logger implementation to use. + * @default new ConsoleLogger() + */ + logger?: ILogger; + /** + * Whether logging should be silenced. + * @default true + */ + silent?: boolean; +} + +/** + * Default console-based logger implementation. + */ +export class ConsoleLogger implements ILogger { + debug(message: string, ...args: unknown[]): void { + console.debug(message, ...args); + } + info(message: string, ...args: unknown[]): void { + console.info(message, ...args); + } + warn(message: string, ...args: unknown[]): void { + console.warn(message, ...args); + } + error(message: string, ...args: unknown[]): void { + console.error(message, ...args); + } +} + +/** + * Logger class that provides level-based logging functionality. + */ +export class Logger { + private readonly level: number; + private readonly logger: ILogger; + private readonly silent: boolean; + + /** + * Creates a new logger instance. + * @param config - Logger configuration + */ + constructor(config: Required) { + this.level = logLevelMap[config.level]; + this.logger = config.logger; + this.silent = config.silent; + } + + /** + * Checks if a log level should be output based on configuration. + * @param level - The log level to check + * @returns True if the level should be logged + */ + public shouldLog(level: LogLevel): boolean { + return !this.silent && this.level <= logLevelMap[level]; + } + + /** + * Checks if debug logging is enabled. + * @returns True if debug logs should be output + */ + public isDebug(): boolean { + return this.shouldLog(LogLevel.Debug); + } + + /** + * Logs a debug message if debug logging is enabled. + * @param message - The message to log + * @param args - Additional arguments to log + */ + public debug(message: string, ...args: unknown[]): void { + if (this.isDebug()) { + this.logger.debug(message, ...args); + } + } + + /** + * Checks if info logging is enabled. + * @returns True if info logs should be output + */ + public isInfo(): boolean { + return this.shouldLog(LogLevel.Info); + } + + /** + * Logs an info message if info logging is enabled. + * @param message - The message to log + * @param args - Additional arguments to log + */ + public info(message: string, ...args: unknown[]): void { + if (this.isInfo()) { + this.logger.info(message, ...args); + } + } + + /** + * Checks if warning logging is enabled. + * @returns True if warning logs should be output + */ + public isWarn(): boolean { + return this.shouldLog(LogLevel.Warn); + } + + /** + * Logs a warning message if warning logging is enabled. + * @param message - The message to log + * @param args - Additional arguments to log + */ + public warn(message: string, ...args: unknown[]): void { + if (this.isWarn()) { + this.logger.warn(message, ...args); + } + } + + /** + * Checks if error logging is enabled. + * @returns True if error logs should be output + */ + public isError(): boolean { + return this.shouldLog(LogLevel.Error); + } + + /** + * Logs an error message if error logging is enabled. + * @param message - The message to log + * @param args - Additional arguments to log + */ + public error(message: string, ...args: unknown[]): void { + if (this.isError()) { + this.logger.error(message, ...args); + } + } +} + +export function createLogger(config?: LogConfig | Logger): Logger { + if (config == null) { + return defaultLogger; + } + if (config instanceof Logger) { + return config; + } + config = config ?? {}; + config.level ??= LogLevel.Info; + config.logger ??= new ConsoleLogger(); + config.silent ??= true; + return new Logger(config as Required); +} + +const defaultLogger: Logger = new Logger({ + level: LogLevel.Info, + logger: new ConsoleLogger(), + silent: true, +}); diff --git a/src/core/pagination/Page.ts b/src/core/pagination/Page.ts index 30df7280..6621a6f1 100644 --- a/src/core/pagination/Page.ts +++ b/src/core/pagination/Page.ts @@ -1,18 +1,19 @@ -import { HttpResponsePromise, RawResponse } from "../fetcher"; +import type { HttpResponsePromise, RawResponse } from "../fetcher/index.js"; /** * A page of results from a paginated API. * * @template T The type of the items in the page. + * @template R The type of the API response. */ -export class Page implements AsyncIterable { +export class Page implements AsyncIterable { public data: T[]; public rawResponse: RawResponse; + public response: R; - private response: unknown; - private _hasNextPage: (response: unknown) => boolean; - private getItems: (response: unknown) => T[]; - private loadNextPage: (response: unknown) => HttpResponsePromise; + private _hasNextPage: (response: R) => boolean; + private getItems: (response: R) => T[]; + private loadNextPage: (response: R) => HttpResponsePromise; constructor({ response, @@ -21,11 +22,11 @@ export class Page implements AsyncIterable { getItems, loadPage, }: { - response: unknown; + response: R; rawResponse: RawResponse; - hasNextPage: (response: unknown) => boolean; - getItems: (response: unknown) => T[]; - loadPage: (response: unknown) => HttpResponsePromise; + hasNextPage: (response: R) => boolean; + getItems: (response: R) => T[]; + loadPage: (response: R) => HttpResponsePromise; }) { this.response = response; this.rawResponse = rawResponse; diff --git a/src/core/pagination/Pageable.ts b/src/core/pagination/Pageable.ts deleted file mode 100644 index 3a5220eb..00000000 --- a/src/core/pagination/Pageable.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { RawResponse } from "../fetcher"; -import { Page } from "./Page"; - -export declare namespace Pageable { - interface Args { - response: Response; - rawResponse: RawResponse; - hasNextPage: (response: Response) => boolean; - getItems: (response: Response) => Item[]; - loadPage: (response: Response) => Promise; - } -} - -export class Pageable extends Page { - constructor(args: Pageable.Args) { - super(args as any); - } -} diff --git a/src/core/pagination/exports.ts b/src/core/pagination/exports.ts new file mode 100644 index 00000000..d3acc60b --- /dev/null +++ b/src/core/pagination/exports.ts @@ -0,0 +1 @@ +export type { Page } from "./Page.js"; diff --git a/src/core/pagination/index.ts b/src/core/pagination/index.ts index 2ceb2684..7781cbd6 100644 --- a/src/core/pagination/index.ts +++ b/src/core/pagination/index.ts @@ -1,2 +1 @@ -export { Page } from "./Page"; -export { Pageable } from "./Pageable"; +export { Page } from "./Page.js"; diff --git a/src/core/runtime/index.ts b/src/core/runtime/index.ts index 5c76dbb1..cfab23f9 100644 --- a/src/core/runtime/index.ts +++ b/src/core/runtime/index.ts @@ -1 +1 @@ -export { RUNTIME } from "./runtime"; +export { RUNTIME } from "./runtime.js"; diff --git a/src/core/runtime/runtime.ts b/src/core/runtime/runtime.ts index a9750175..56ebbb87 100644 --- a/src/core/runtime/runtime.ts +++ b/src/core/runtime/runtime.ts @@ -11,6 +11,9 @@ interface BunGlobal { declare const Deno: DenoGlobal | undefined; declare const Bun: BunGlobal | undefined; declare const EdgeRuntime: string | undefined; +declare const self: typeof globalThis.self & { + importScripts?: unknown; +}; /** * A constant that indicates which environment and version the SDK is running in. @@ -62,7 +65,6 @@ function evaluateRuntime(): Runtime { */ const isWebWorker = typeof self === "object" && - // @ts-ignore typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || @@ -97,6 +99,18 @@ function evaluateRuntime(): Runtime { }; } + /** + * A constant that indicates whether the environment the code is running is in React-Native. + * This check should come before Node.js detection since React Native may have a process polyfill. + * https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js + */ + const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative"; + if (isReactNative) { + return { + type: "react-native", + }; + } + /** * A constant that indicates whether the environment the code is running is Node.JS. */ @@ -114,17 +128,6 @@ function evaluateRuntime(): Runtime { }; } - /** - * A constant that indicates whether the environment the code is running is in React-Native. - * https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js - */ - const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative"; - if (isReactNative) { - return { - type: "react-native", - }; - } - return { type: "unknown", }; diff --git a/src/core/url/encodePathParam.ts b/src/core/url/encodePathParam.ts new file mode 100644 index 00000000..19b90124 --- /dev/null +++ b/src/core/url/encodePathParam.ts @@ -0,0 +1,18 @@ +export function encodePathParam(param: unknown): string { + if (param === null) { + return "null"; + } + const typeofParam = typeof param; + switch (typeofParam) { + case "undefined": + return "undefined"; + case "string": + case "number": + case "boolean": + break; + default: + param = String(param); + break; + } + return encodeURIComponent(param as string | number | boolean); +} diff --git a/src/core/url/index.ts b/src/core/url/index.ts new file mode 100644 index 00000000..f2e0fa2d --- /dev/null +++ b/src/core/url/index.ts @@ -0,0 +1,3 @@ +export { encodePathParam } from "./encodePathParam.js"; +export { join } from "./join.js"; +export { toQueryString } from "./qs.js"; diff --git a/src/core/url/join.ts b/src/core/url/join.ts new file mode 100644 index 00000000..7ca7daef --- /dev/null +++ b/src/core/url/join.ts @@ -0,0 +1,79 @@ +export function join(base: string, ...segments: string[]): string { + if (!base) { + return ""; + } + + if (segments.length === 0) { + return base; + } + + if (base.includes("://")) { + let url: URL; + try { + url = new URL(base); + } catch { + return joinPath(base, ...segments); + } + + const lastSegment = segments[segments.length - 1]; + const shouldPreserveTrailingSlash = lastSegment?.endsWith("/"); + + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) { + url.pathname = joinPathSegments(url.pathname, cleanSegment); + } + } + + if (shouldPreserveTrailingSlash && !url.pathname.endsWith("/")) { + url.pathname += "/"; + } + + return url.toString(); + } + + return joinPath(base, ...segments); +} + +function joinPath(base: string, ...segments: string[]): string { + if (segments.length === 0) { + return base; + } + + let result = base; + + const lastSegment = segments[segments.length - 1]; + const shouldPreserveTrailingSlash = lastSegment?.endsWith("/"); + + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) { + result = joinPathSegments(result, cleanSegment); + } + } + + if (shouldPreserveTrailingSlash && !result.endsWith("/")) { + result += "/"; + } + + return result; +} + +function joinPathSegments(left: string, right: string): string { + if (left.endsWith("/")) { + return left + right; + } + return `${left}/${right}`; +} + +function trimSlashes(str: string): string { + if (!str) return str; + + let start = 0; + let end = str.length; + + if (str.startsWith("/")) start = 1; + if (str.endsWith("/")) end = str.length - 1; + + return start === 0 && end === str.length ? str : str.slice(start, end); +} diff --git a/src/core/url/qs.ts b/src/core/url/qs.ts new file mode 100644 index 00000000..13e89be9 --- /dev/null +++ b/src/core/url/qs.ts @@ -0,0 +1,74 @@ +interface QueryStringOptions { + arrayFormat?: "indices" | "repeat"; + encode?: boolean; +} + +const defaultQsOptions: Required = { + arrayFormat: "indices", + encode: true, +} as const; + +function encodeValue(value: unknown, shouldEncode: boolean): string { + if (value === undefined) { + return ""; + } + if (value === null) { + return ""; + } + const stringValue = String(value); + return shouldEncode ? encodeURIComponent(stringValue) : stringValue; +} + +function stringifyObject(obj: Record, prefix = "", options: Required): string[] { + const parts: string[] = []; + + for (const [key, value] of Object.entries(obj)) { + const fullKey = prefix ? `${prefix}[${key}]` : key; + + if (value === undefined) { + continue; + } + + if (Array.isArray(value)) { + if (value.length === 0) { + continue; + } + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === undefined) { + continue; + } + if (typeof item === "object" && !Array.isArray(item) && item !== null) { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + parts.push(...stringifyObject(item as Record, arrayKey, options)); + } else { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + const encodedKey = options.encode ? encodeURIComponent(arrayKey) : arrayKey; + parts.push(`${encodedKey}=${encodeValue(item, options.encode)}`); + } + } + } else if (typeof value === "object" && value !== null) { + if (Object.keys(value as Record).length === 0) { + continue; + } + parts.push(...stringifyObject(value as Record, fullKey, options)); + } else { + const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey; + parts.push(`${encodedKey}=${encodeValue(value, options.encode)}`); + } + } + + return parts; +} + +export function toQueryString(obj: unknown, options?: QueryStringOptions): string { + if (obj == null || typeof obj !== "object") { + return ""; + } + + const parts = stringifyObject(obj as Record, "", { + ...defaultQsOptions, + ...options, + }); + return parts.join("&"); +} diff --git a/src/core/utils/index.ts b/src/core/utils/index.ts index b168f599..11ff8f25 100644 --- a/src/core/utils/index.ts +++ b/src/core/utils/index.ts @@ -1 +1 @@ -export { setObjectProperty } from "./setObjectProperty"; +export { setObjectProperty } from "./setObjectProperty.js"; diff --git a/src/environments.ts b/src/environments.ts index d2816275..752460d1 100644 --- a/src/environments.ts +++ b/src/environments.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export const IntercomEnvironment = { UsProduction: "https://api.intercom.io", diff --git a/src/errors/IntercomError.ts b/src/errors/IntercomError.ts index 0f91cad3..de63f5e0 100644 --- a/src/errors/IntercomError.ts +++ b/src/errors/IntercomError.ts @@ -1,9 +1,7 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. -import * as core from "../core"; -import { toJson } from "../core/json"; +import type * as core from "../core/index.js"; +import { toJson } from "../core/json.js"; export class IntercomError extends Error { public readonly statusCode?: number; @@ -38,7 +36,7 @@ function buildMessage({ statusCode: number | undefined; body: unknown | undefined; }): string { - let lines: string[] = []; + const lines: string[] = []; if (message != null) { lines.push(message); } diff --git a/src/errors/IntercomTimeoutError.ts b/src/errors/IntercomTimeoutError.ts index 52bd429f..e0c388db 100644 --- a/src/errors/IntercomTimeoutError.ts +++ b/src/errors/IntercomTimeoutError.ts @@ -1,6 +1,4 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ +// This file was auto-generated by Fern from our API Definition. export class IntercomTimeoutError extends Error { constructor(message: string) { diff --git a/src/errors/handleNonStatusCodeError.ts b/src/errors/handleNonStatusCodeError.ts new file mode 100644 index 00000000..75076b10 --- /dev/null +++ b/src/errors/handleNonStatusCodeError.ts @@ -0,0 +1,37 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as core from "../core/index.js"; +import * as errors from "./index.js"; + +export function handleNonStatusCodeError( + error: core.Fetcher.Error, + rawResponse: core.RawResponse, + method: string, + path: string, +): never { + switch (error.reason) { + case "non-json": + throw new errors.IntercomError({ + statusCode: error.statusCode, + body: error.rawBody, + rawResponse: rawResponse, + }); + case "body-is-null": + throw new errors.IntercomError({ + statusCode: error.statusCode, + rawResponse: rawResponse, + }); + case "timeout": + throw new errors.IntercomTimeoutError(`Timeout exceeded when calling ${method} ${path}.`); + case "unknown": + throw new errors.IntercomError({ + message: error.errorMessage, + rawResponse: rawResponse, + }); + default: + throw new errors.IntercomError({ + message: "Unknown error", + rawResponse: rawResponse, + }); + } +} diff --git a/src/errors/index.ts b/src/errors/index.ts index 25abf2ea..280a57f9 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -1,2 +1,2 @@ -export { IntercomError } from "./IntercomError"; -export { IntercomTimeoutError } from "./IntercomTimeoutError"; +export { IntercomError } from "./IntercomError.js"; +export { IntercomTimeoutError } from "./IntercomTimeoutError.js"; diff --git a/src/exports.ts b/src/exports.ts new file mode 100644 index 00000000..7b70ee14 --- /dev/null +++ b/src/exports.ts @@ -0,0 +1 @@ +export * from "./core/exports.js"; diff --git a/src/index.ts b/src/index.ts index 5394f30c..e8fc688d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,6 @@ -export * as Intercom from "./api"; -export { IntercomClient } from "./Client"; -export { IntercomEnvironment } from "./environments"; -export { IntercomError, IntercomTimeoutError } from "./errors"; +export * as Intercom from "./api/index.js"; +export type { BaseClientOptions, BaseRequestOptions } from "./BaseClient.js"; +export { IntercomClient } from "./Client.js"; +export { IntercomEnvironment } from "./environments.js"; +export { IntercomError, IntercomTimeoutError } from "./errors/index.js"; +export * from "./exports.js"; diff --git a/src/version.ts b/src/version.ts index 1420c168..6bb53d57 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const SDK_VERSION = "6.4.0"; +export const SDK_VERSION = "7.0.0"; diff --git a/tests/integration/conversations.test.ts b/tests/integration/conversations.test.ts index 474b318b..fed0a9b9 100644 --- a/tests/integration/conversations.test.ts +++ b/tests/integration/conversations.test.ts @@ -168,11 +168,12 @@ describe("Conversations", () => { }); it("run assignment rules", async () => { + const legacyClient = createClient({ version: "2.11" }); // arrange - const message = await createConversation(client, user.id); + const message = await createConversation(legacyClient, user.id); // act - const response = await client.conversations.runAssignmentRules({ + const response = await legacyClient.conversations.runAssignmentRules({ conversation_id: message.conversation_id, }); diff --git a/tests/integration/dataAttributes.test.ts b/tests/integration/dataAttributes.test.ts index 22c3ca10..f5889fa2 100644 --- a/tests/integration/dataAttributes.test.ts +++ b/tests/integration/dataAttributes.test.ts @@ -13,7 +13,7 @@ describe("Data Attributes", () => { randomDataAttribute = attributes.data.find((attribute) => attribute.id !== undefined); }); - xit("create", async () => { + it.skip("create", async () => { //act // The workspace we test on has hit the CDA limit, so we can't create any more diff --git a/tests/integration/utils/createClient.ts b/tests/integration/utils/createClient.ts index 4b2c5475..f2662688 100644 --- a/tests/integration/utils/createClient.ts +++ b/tests/integration/utils/createClient.ts @@ -1,5 +1,11 @@ -import { IntercomClient } from "../../../src"; +import { type Intercom, IntercomClient } from "../../../src"; -export function createClient(): IntercomClient { - return new IntercomClient({ token: process.env.API_TOKEN as string }); +type IntercomVersion = Intercom.IntercomVersion; + +export function createClient(options?: { version?: IntercomVersion }): IntercomClient { + const { version } = options || {}; + return new IntercomClient({ + token: process.env.API_TOKEN as string, + version, + }); } diff --git a/tests/mock-server/MockServer.ts b/tests/mock-server/MockServer.ts new file mode 100644 index 00000000..95487215 --- /dev/null +++ b/tests/mock-server/MockServer.ts @@ -0,0 +1,29 @@ +import type { RequestHandlerOptions } from "msw"; +import type { SetupServer } from "msw/node"; + +import { mockEndpointBuilder } from "./mockEndpointBuilder"; + +export interface MockServerOptions { + baseUrl: string; + server: SetupServer; +} + +export class MockServer { + private readonly server: SetupServer; + public readonly baseUrl: string; + + constructor({ baseUrl, server }: MockServerOptions) { + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl; + this.server = server; + } + + public mockEndpoint(options?: RequestHandlerOptions): ReturnType { + const builder = mockEndpointBuilder({ + once: options?.once ?? true, + onBuild: (handler) => { + this.server.use(handler); + }, + }).baseUrl(this.baseUrl); + return builder; + } +} diff --git a/tests/mock-server/MockServerPool.ts b/tests/mock-server/MockServerPool.ts new file mode 100644 index 00000000..e1a90f7f --- /dev/null +++ b/tests/mock-server/MockServerPool.ts @@ -0,0 +1,106 @@ +import { setupServer } from "msw/node"; + +import { fromJson, toJson } from "../../src/core/json"; +import { MockServer } from "./MockServer"; +import { randomBaseUrl } from "./randomBaseUrl"; + +const mswServer = setupServer(); +interface MockServerOptions { + baseUrl?: string; +} + +async function formatHttpRequest(request: Request, id?: string): Promise { + try { + const clone = request.clone(); + const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n"); + + let body = ""; + try { + const contentType = clone.headers.get("content-type"); + if (contentType?.includes("application/json")) { + body = toJson(fromJson(await clone.text()), undefined, 2); + } else if (clone.body) { + body = await clone.text(); + } + } catch (_e) { + body = "(unable to parse body)"; + } + + const title = id ? `### Request ${id} ###\n` : ""; + const firstLine = `${title}${request.method} ${request.url.toString()} HTTP/1.1`; + + return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`; + } catch (e) { + return `Error formatting request: ${e}`; + } +} + +async function formatHttpResponse(response: Response, id?: string): Promise { + try { + const clone = response.clone(); + const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n"); + + let body = ""; + try { + const contentType = clone.headers.get("content-type"); + if (contentType?.includes("application/json")) { + body = toJson(fromJson(await clone.text()), undefined, 2); + } else if (clone.body) { + body = await clone.text(); + } + } catch (_e) { + body = "(unable to parse body)"; + } + + const title = id ? `### Response for ${id} ###\n` : ""; + const firstLine = `${title}HTTP/1.1 ${response.status} ${response.statusText}`; + + return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`; + } catch (e) { + return `Error formatting response: ${e}`; + } +} + +class MockServerPool { + private servers: MockServer[] = []; + + public createServer(options?: Partial): MockServer { + const baseUrl = options?.baseUrl || randomBaseUrl(); + const server = new MockServer({ baseUrl, server: mswServer }); + this.servers.push(server); + return server; + } + + public getServers(): MockServer[] { + return [...this.servers]; + } + + public listen(): void { + const onUnhandledRequest = process.env.LOG_LEVEL === "debug" ? "warn" : "bypass"; + mswServer.listen({ onUnhandledRequest }); + + if (process.env.LOG_LEVEL === "debug") { + mswServer.events.on("request:start", async ({ request, requestId }) => { + const formattedRequest = await formatHttpRequest(request, requestId); + console.debug(`request:start\n${formattedRequest}`); + }); + + mswServer.events.on("request:unhandled", async ({ request, requestId }) => { + const formattedRequest = await formatHttpRequest(request, requestId); + console.debug(`request:unhandled\n${formattedRequest}`); + }); + + mswServer.events.on("response:mocked", async ({ request, response, requestId }) => { + const formattedResponse = await formatHttpResponse(response, requestId); + console.debug(`response:mocked\n${formattedResponse}`); + }); + } + } + + public close(): void { + this.servers = []; + mswServer.close(); + } +} + +export const mockServerPool = new MockServerPool(); diff --git a/tests/mock-server/mockEndpointBuilder.ts b/tests/mock-server/mockEndpointBuilder.ts new file mode 100644 index 00000000..1b0e5107 --- /dev/null +++ b/tests/mock-server/mockEndpointBuilder.ts @@ -0,0 +1,227 @@ +import { type DefaultBodyType, type HttpHandler, HttpResponse, type HttpResponseResolver, http } from "msw"; + +import { url } from "../../src/core"; +import { toJson } from "../../src/core/json"; +import { withFormUrlEncoded } from "./withFormUrlEncoded"; +import { withHeaders } from "./withHeaders"; +import { withJson } from "./withJson"; + +type HttpMethod = "all" | "get" | "post" | "put" | "delete" | "patch" | "options" | "head"; + +interface MethodStage { + baseUrl(baseUrl: string): MethodStage; + all(path: string): RequestHeadersStage; + get(path: string): RequestHeadersStage; + post(path: string): RequestHeadersStage; + put(path: string): RequestHeadersStage; + delete(path: string): RequestHeadersStage; + patch(path: string): RequestHeadersStage; + options(path: string): RequestHeadersStage; + head(path: string): RequestHeadersStage; +} + +interface RequestHeadersStage extends RequestBodyStage, ResponseStage { + header(name: string, value: string): RequestHeadersStage; + headers(headers: Record): RequestBodyStage; +} + +interface RequestBodyStage extends ResponseStage { + jsonBody(body: unknown): ResponseStage; + formUrlEncodedBody(body: unknown): ResponseStage; +} + +interface ResponseStage { + respondWith(): ResponseStatusStage; +} +interface ResponseStatusStage { + statusCode(statusCode: number): ResponseHeaderStage; +} + +interface ResponseHeaderStage extends ResponseBodyStage, BuildStage { + header(name: string, value: string): ResponseHeaderStage; + headers(headers: Record): ResponseHeaderStage; +} + +interface ResponseBodyStage { + jsonBody(body: unknown): BuildStage; +} + +interface BuildStage { + build(): HttpHandler; +} + +export interface HttpHandlerBuilderOptions { + onBuild?: (handler: HttpHandler) => void; + once?: boolean; +} + +class RequestBuilder implements MethodStage, RequestHeadersStage, RequestBodyStage, ResponseStage { + private method: HttpMethod = "get"; + private _baseUrl: string = ""; + private path: string = "/"; + private readonly predicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[] = []; + private readonly handlerOptions?: HttpHandlerBuilderOptions; + + constructor(options?: HttpHandlerBuilderOptions) { + this.handlerOptions = options; + } + + baseUrl(baseUrl: string): MethodStage { + this._baseUrl = baseUrl; + return this; + } + + all(path: string): RequestHeadersStage { + this.method = "all"; + this.path = path; + return this; + } + + get(path: string): RequestHeadersStage { + this.method = "get"; + this.path = path; + return this; + } + + post(path: string): RequestHeadersStage { + this.method = "post"; + this.path = path; + return this; + } + + put(path: string): RequestHeadersStage { + this.method = "put"; + this.path = path; + return this; + } + + delete(path: string): RequestHeadersStage { + this.method = "delete"; + this.path = path; + return this; + } + + patch(path: string): RequestHeadersStage { + this.method = "patch"; + this.path = path; + return this; + } + + options(path: string): RequestHeadersStage { + this.method = "options"; + this.path = path; + return this; + } + + head(path: string): RequestHeadersStage { + this.method = "head"; + this.path = path; + return this; + } + + header(name: string, value: string): RequestHeadersStage { + this.predicates.push((resolver) => withHeaders({ [name]: value }, resolver)); + return this; + } + + headers(headers: Record): RequestBodyStage { + this.predicates.push((resolver) => withHeaders(headers, resolver)); + return this; + } + + jsonBody(body: unknown): ResponseStage { + if (body === undefined) { + throw new Error("Undefined is not valid JSON. Do not call jsonBody if you want an empty body."); + } + this.predicates.push((resolver) => withJson(body, resolver)); + return this; + } + + formUrlEncodedBody(body: unknown): ResponseStage { + if (body === undefined) { + throw new Error( + "Undefined is not valid for form-urlencoded. Do not call formUrlEncodedBody if you want an empty body.", + ); + } + this.predicates.push((resolver) => withFormUrlEncoded(body, resolver)); + return this; + } + + respondWith(): ResponseStatusStage { + return new ResponseBuilder(this.method, this.buildUrl(), this.predicates, this.handlerOptions); + } + + private buildUrl(): string { + return url.join(this._baseUrl, this.path); + } +} + +class ResponseBuilder implements ResponseStatusStage, ResponseHeaderStage, ResponseBodyStage, BuildStage { + private readonly method: HttpMethod; + private readonly url: string; + private readonly requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[]; + private readonly handlerOptions?: HttpHandlerBuilderOptions; + + private responseStatusCode: number = 200; + private responseHeaders: Record = {}; + private responseBody: DefaultBodyType = undefined; + + constructor( + method: HttpMethod, + url: string, + requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[], + options?: HttpHandlerBuilderOptions, + ) { + this.method = method; + this.url = url; + this.requestPredicates = requestPredicates; + this.handlerOptions = options; + } + + public statusCode(code: number): ResponseHeaderStage { + this.responseStatusCode = code; + return this; + } + + public header(name: string, value: string): ResponseHeaderStage { + this.responseHeaders[name] = value; + return this; + } + + public headers(headers: Record): ResponseHeaderStage { + this.responseHeaders = { ...this.responseHeaders, ...headers }; + return this; + } + + public jsonBody(body: unknown): BuildStage { + if (body === undefined) { + throw new Error("Undefined is not valid JSON. Do not call jsonBody if you expect an empty body."); + } + this.responseBody = toJson(body); + return this; + } + + public build(): HttpHandler { + const responseResolver: HttpResponseResolver = () => { + const response = new HttpResponse(this.responseBody, { + status: this.responseStatusCode, + headers: this.responseHeaders, + }); + // if no Content-Type header is set, delete the default text content type that is set + if (Object.keys(this.responseHeaders).some((key) => key.toLowerCase() === "content-type") === false) { + response.headers.delete("Content-Type"); + } + return response; + }; + + const finalResolver = this.requestPredicates.reduceRight((acc, predicate) => predicate(acc), responseResolver); + + const handler = http[this.method](this.url, finalResolver, this.handlerOptions); + this.handlerOptions?.onBuild?.(handler); + return handler; + } +} + +export function mockEndpointBuilder(options?: HttpHandlerBuilderOptions): MethodStage { + return new RequestBuilder(options); +} diff --git a/tests/mock-server/randomBaseUrl.ts b/tests/mock-server/randomBaseUrl.ts new file mode 100644 index 00000000..031aa640 --- /dev/null +++ b/tests/mock-server/randomBaseUrl.ts @@ -0,0 +1,4 @@ +export function randomBaseUrl(): string { + const randomString = Math.random().toString(36).substring(2, 15); + return `http://${randomString}.localhost`; +} diff --git a/tests/mock-server/setup.ts b/tests/mock-server/setup.ts new file mode 100644 index 00000000..aeb3a95a --- /dev/null +++ b/tests/mock-server/setup.ts @@ -0,0 +1,10 @@ +import { afterAll, beforeAll } from "vitest"; + +import { mockServerPool } from "./MockServerPool"; + +beforeAll(() => { + mockServerPool.listen(); +}); +afterAll(() => { + mockServerPool.close(); +}); diff --git a/tests/mock-server/withFormUrlEncoded.ts b/tests/mock-server/withFormUrlEncoded.ts new file mode 100644 index 00000000..e9e6ff2d --- /dev/null +++ b/tests/mock-server/withFormUrlEncoded.ts @@ -0,0 +1,80 @@ +import { type HttpResponseResolver, passthrough } from "msw"; + +import { toJson } from "../../src/core/json"; + +/** + * Creates a request matcher that validates if the request form-urlencoded body exactly matches the expected object + * @param expectedBody - The exact body object to match against + * @param resolver - Response resolver to execute if body matches + */ +export function withFormUrlEncoded(expectedBody: unknown, resolver: HttpResponseResolver): HttpResponseResolver { + return async (args) => { + const { request } = args; + + let clonedRequest: Request; + let bodyText: string | undefined; + let actualBody: Record; + try { + clonedRequest = request.clone(); + bodyText = await clonedRequest.text(); + if (bodyText === "") { + console.error("Request body is empty, expected a form-urlencoded body."); + return passthrough(); + } + const params = new URLSearchParams(bodyText); + actualBody = {}; + for (const [key, value] of params.entries()) { + actualBody[key] = value; + } + } catch (error) { + console.error(`Error processing form-urlencoded request body:\n\tError: ${error}\n\tBody: ${bodyText}`); + return passthrough(); + } + + const mismatches = findMismatches(actualBody, expectedBody); + if (Object.keys(mismatches).length > 0) { + console.error("Form-urlencoded body mismatch:", toJson(mismatches, undefined, 2)); + return passthrough(); + } + + return resolver(args); + }; +} + +function findMismatches(actual: any, expected: any): Record { + const mismatches: Record = {}; + + if (typeof actual !== typeof expected) { + return { value: { actual, expected } }; + } + + if (typeof actual !== "object" || actual === null || expected === null) { + if (actual !== expected) { + return { value: { actual, expected } }; + } + return {}; + } + + const actualKeys = Object.keys(actual); + const expectedKeys = Object.keys(expected); + + const allKeys = new Set([...actualKeys, ...expectedKeys]); + + for (const key of allKeys) { + if (!expectedKeys.includes(key)) { + if (actual[key] === undefined) { + continue; + } + mismatches[key] = { actual: actual[key], expected: undefined }; + } else if (!actualKeys.includes(key)) { + if (expected[key] === undefined) { + continue; + } + mismatches[key] = { actual: undefined, expected: expected[key] }; + } else if (actual[key] !== expected[key]) { + mismatches[key] = { actual: actual[key], expected: expected[key] }; + } + } + + return mismatches; +} diff --git a/tests/mock-server/withHeaders.ts b/tests/mock-server/withHeaders.ts new file mode 100644 index 00000000..6599d2b4 --- /dev/null +++ b/tests/mock-server/withHeaders.ts @@ -0,0 +1,70 @@ +import { type HttpResponseResolver, passthrough } from "msw"; + +/** + * Creates a request matcher that validates if request headers match specified criteria + * @param expectedHeaders - Headers to match against + * @param resolver - Response resolver to execute if headers match + */ +export function withHeaders( + expectedHeaders: Record boolean)>, + resolver: HttpResponseResolver, +): HttpResponseResolver { + return (args) => { + const { request } = args; + const { headers } = request; + + const mismatches: Record< + string, + { actual: string | null; expected: string | RegExp | ((value: string) => boolean) } + > = {}; + + for (const [key, expectedValue] of Object.entries(expectedHeaders)) { + const actualValue = headers.get(key); + + if (actualValue === null) { + mismatches[key] = { actual: null, expected: expectedValue }; + continue; + } + + if (typeof expectedValue === "function") { + if (!expectedValue(actualValue)) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } else if (expectedValue instanceof RegExp) { + if (!expectedValue.test(actualValue)) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } else if (expectedValue !== actualValue) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } + + if (Object.keys(mismatches).length > 0) { + const formattedMismatches = formatHeaderMismatches(mismatches); + console.error("Header mismatch:", formattedMismatches); + return passthrough(); + } + + return resolver(args); + }; +} + +function formatHeaderMismatches( + mismatches: Record boolean) }>, +): Record { + const formatted: Record = {}; + + for (const [key, { actual, expected }] of Object.entries(mismatches)) { + formatted[key] = { + actual, + expected: + expected instanceof RegExp + ? expected.toString() + : typeof expected === "function" + ? "[Function]" + : expected, + }; + } + + return formatted; +} diff --git a/tests/mock-server/withJson.ts b/tests/mock-server/withJson.ts new file mode 100644 index 00000000..b627638b --- /dev/null +++ b/tests/mock-server/withJson.ts @@ -0,0 +1,158 @@ +import { type HttpResponseResolver, passthrough } from "msw"; + +import { fromJson, toJson } from "../../src/core/json"; + +/** + * Creates a request matcher that validates if the request JSON body exactly matches the expected object + * @param expectedBody - The exact body object to match against + * @param resolver - Response resolver to execute if body matches + */ +export function withJson(expectedBody: unknown, resolver: HttpResponseResolver): HttpResponseResolver { + return async (args) => { + const { request } = args; + + let clonedRequest: Request; + let bodyText: string | undefined; + let actualBody: unknown; + try { + clonedRequest = request.clone(); + bodyText = await clonedRequest.text(); + if (bodyText === "") { + console.error("Request body is empty, expected a JSON object."); + return passthrough(); + } + actualBody = fromJson(bodyText); + } catch (error) { + console.error(`Error processing request body:\n\tError: ${error}\n\tBody: ${bodyText}`); + return passthrough(); + } + + const mismatches = findMismatches(actualBody, expectedBody); + if (Object.keys(mismatches).filter((key) => !key.startsWith("pagination.")).length > 0) { + console.error("JSON body mismatch:", toJson(mismatches, undefined, 2)); + return passthrough(); + } + + return resolver(args); + }; +} + +function findMismatches(actual: any, expected: any): Record { + const mismatches: Record = {}; + + if (typeof actual !== typeof expected) { + if (areEquivalent(actual, expected)) { + return {}; + } + return { value: { actual, expected } }; + } + + if (typeof actual !== "object" || actual === null || expected === null) { + if (actual !== expected) { + if (areEquivalent(actual, expected)) { + return {}; + } + return { value: { actual, expected } }; + } + return {}; + } + + if (Array.isArray(actual) && Array.isArray(expected)) { + if (actual.length !== expected.length) { + return { length: { actual: actual.length, expected: expected.length } }; + } + + const arrayMismatches: Record = {}; + for (let i = 0; i < actual.length; i++) { + const itemMismatches = findMismatches(actual[i], expected[i]); + if (Object.keys(itemMismatches).length > 0) { + for (const [mismatchKey, mismatchValue] of Object.entries(itemMismatches)) { + arrayMismatches[`[${i}]${mismatchKey === "value" ? "" : `.${mismatchKey}`}`] = mismatchValue; + } + } + } + return arrayMismatches; + } + + const actualKeys = Object.keys(actual); + const expectedKeys = Object.keys(expected); + + const allKeys = new Set([...actualKeys, ...expectedKeys]); + + for (const key of allKeys) { + if (!expectedKeys.includes(key)) { + if (actual[key] === undefined) { + continue; // Skip undefined values in actual + } + mismatches[key] = { actual: actual[key], expected: undefined }; + } else if (!actualKeys.includes(key)) { + if (expected[key] === undefined) { + continue; // Skip undefined values in expected + } + mismatches[key] = { actual: undefined, expected: expected[key] }; + } else if ( + typeof actual[key] === "object" && + actual[key] !== null && + typeof expected[key] === "object" && + expected[key] !== null + ) { + const nestedMismatches = findMismatches(actual[key], expected[key]); + if (Object.keys(nestedMismatches).length > 0) { + for (const [nestedKey, nestedValue] of Object.entries(nestedMismatches)) { + mismatches[`${key}${nestedKey === "value" ? "" : `.${nestedKey}`}`] = nestedValue; + } + } + } else if (actual[key] !== expected[key]) { + if (areEquivalent(actual[key], expected[key])) { + continue; + } + mismatches[key] = { actual: actual[key], expected: expected[key] }; + } + } + + return mismatches; +} + +function areEquivalent(actual: unknown, expected: unknown): boolean { + if (actual === expected) { + return true; + } + if (isEquivalentBigInt(actual, expected)) { + return true; + } + if (isEquivalentDatetime(actual, expected)) { + return true; + } + return false; +} + +function isEquivalentBigInt(actual: unknown, expected: unknown) { + if (typeof actual === "number") { + actual = BigInt(actual); + } + if (typeof expected === "number") { + expected = BigInt(expected); + } + if (typeof actual === "bigint" && typeof expected === "bigint") { + return actual === expected; + } + return false; +} + +function isEquivalentDatetime(str1: unknown, str2: unknown): boolean { + if (typeof str1 !== "string" || typeof str2 !== "string") { + return false; + } + const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/; + if (!isoDatePattern.test(str1) || !isoDatePattern.test(str2)) { + return false; + } + + try { + const date1 = new Date(str1).getTime(); + const date2 = new Date(str2).getTime(); + return date1 === date2; + } catch { + return false; + } +} diff --git a/tests/setup.ts b/tests/setup.ts new file mode 100644 index 00000000..a5651f81 --- /dev/null +++ b/tests/setup.ts @@ -0,0 +1,80 @@ +import { expect } from "vitest"; + +interface CustomMatchers { + toContainHeaders(expectedHeaders: Record): R; +} + +declare module "vitest" { + interface Assertion extends CustomMatchers {} + interface AsymmetricMatchersContaining extends CustomMatchers {} +} + +expect.extend({ + toContainHeaders(actual: unknown, expectedHeaders: Record) { + const isHeaders = actual instanceof Headers; + const isPlainObject = typeof actual === "object" && actual !== null && !Array.isArray(actual); + + if (!isHeaders && !isPlainObject) { + throw new TypeError("Received value must be an instance of Headers or a plain object!"); + } + + if (typeof expectedHeaders !== "object" || expectedHeaders === null || Array.isArray(expectedHeaders)) { + throw new TypeError("Expected headers must be a plain object!"); + } + + const missingHeaders: string[] = []; + const mismatchedHeaders: Array<{ key: string; expected: string; actual: string | null }> = []; + + for (const [key, value] of Object.entries(expectedHeaders)) { + let actualValue: string | null = null; + + if (isHeaders) { + // Headers.get() is already case-insensitive + actualValue = (actual as Headers).get(key); + } else { + // For plain objects, do case-insensitive lookup + const actualObj = actual as Record; + const lowerKey = key.toLowerCase(); + const foundKey = Object.keys(actualObj).find((k) => k.toLowerCase() === lowerKey); + actualValue = foundKey ? actualObj[foundKey] : null; + } + + if (actualValue === null || actualValue === undefined) { + missingHeaders.push(key); + } else if (actualValue !== value) { + mismatchedHeaders.push({ key, expected: value, actual: actualValue }); + } + } + + const pass = missingHeaders.length === 0 && mismatchedHeaders.length === 0; + + const actualType = isHeaders ? "Headers" : "object"; + + if (pass) { + return { + message: () => `expected ${actualType} not to contain ${this.utils.printExpected(expectedHeaders)}`, + pass: true, + }; + } else { + const messages: string[] = []; + + if (missingHeaders.length > 0) { + messages.push(`Missing headers: ${this.utils.printExpected(missingHeaders.join(", "))}`); + } + + if (mismatchedHeaders.length > 0) { + const mismatches = mismatchedHeaders.map( + ({ key, expected, actual }) => + `${key}: expected ${this.utils.printExpected(expected)} but got ${this.utils.printReceived(actual)}`, + ); + messages.push(mismatches.join("\n")); + } + + return { + message: () => + `expected ${actualType} to contain ${this.utils.printExpected(expectedHeaders)}\n\n${messages.join("\n")}`, + pass: false, + }; + } + }, +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json new file mode 100644 index 00000000..a477df47 --- /dev/null +++ b/tests/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "outDir": null, + "rootDir": "..", + "baseUrl": "..", + "types": ["vitest/globals"] + }, + "include": ["../src", "../tests"], + "exclude": [] +} diff --git a/tests/unit/auth/BasicAuth.test.ts b/tests/unit/auth/BasicAuth.test.ts index 79ef9799..9b512336 100644 --- a/tests/unit/auth/BasicAuth.test.ts +++ b/tests/unit/auth/BasicAuth.test.ts @@ -1,21 +1,91 @@ import { BasicAuth } from "../../../src/core/auth/BasicAuth"; describe("BasicAuth", () => { + interface ToHeaderTestCase { + description: string; + input: { username: string; password: string }; + expected: string; + } + + interface FromHeaderTestCase { + description: string; + input: string; + expected: { username: string; password: string }; + } + + interface ErrorTestCase { + description: string; + input: string; + expectedError: string; + } + describe("toAuthorizationHeader", () => { - it("correctly converts to header", () => { - expect( - BasicAuth.toAuthorizationHeader({ - username: "username", - password: "password", - }), - ).toBe("Basic dXNlcm5hbWU6cGFzc3dvcmQ="); + const toHeaderTests: ToHeaderTestCase[] = [ + { + description: "correctly converts to header", + input: { username: "username", password: "password" }, + expected: "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + }, + ]; + + toHeaderTests.forEach(({ description, input, expected }) => { + it(description, () => { + expect(BasicAuth.toAuthorizationHeader(input)).toBe(expected); + }); }); }); + describe("fromAuthorizationHeader", () => { - it("correctly parses header", () => { - expect(BasicAuth.fromAuthorizationHeader("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")).toEqual({ - username: "username", - password: "password", + const fromHeaderTests: FromHeaderTestCase[] = [ + { + description: "correctly parses header", + input: "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", + expected: { username: "username", password: "password" }, + }, + { + description: "handles password with colons", + input: "Basic dXNlcjpwYXNzOndvcmQ=", + expected: { username: "user", password: "pass:word" }, + }, + { + description: "handles empty username and password (just colon)", + input: "Basic Og==", + expected: { username: "", password: "" }, + }, + { + description: "handles empty username", + input: "Basic OnBhc3N3b3Jk", + expected: { username: "", password: "password" }, + }, + { + description: "handles empty password", + input: "Basic dXNlcm5hbWU6", + expected: { username: "username", password: "" }, + }, + ]; + + fromHeaderTests.forEach(({ description, input, expected }) => { + it(description, () => { + expect(BasicAuth.fromAuthorizationHeader(input)).toEqual(expected); + }); + }); + + const errorTests: ErrorTestCase[] = [ + { + description: "throws error for completely empty credentials", + input: "Basic ", + expectedError: "Invalid basic auth", + }, + { + description: "throws error for credentials without colon", + input: "Basic dXNlcm5hbWU=", + expectedError: "Invalid basic auth", + }, + ]; + + errorTests.forEach(({ description, input, expectedError }) => { + it(description, () => { + expect(() => BasicAuth.fromAuthorizationHeader(input)).toThrow(expectedError); }); }); }); diff --git a/tests/unit/base64.test.ts b/tests/unit/base64.test.ts new file mode 100644 index 00000000..939594ca --- /dev/null +++ b/tests/unit/base64.test.ts @@ -0,0 +1,53 @@ +import { base64Decode, base64Encode } from "../../src/core/base64"; + +describe("base64", () => { + describe("base64Encode", () => { + it("should encode ASCII strings", () => { + expect(base64Encode("hello")).toBe("aGVsbG8="); + expect(base64Encode("")).toBe(""); + }); + + it("should encode UTF-8 strings", () => { + expect(base64Encode("café")).toBe("Y2Fmw6k="); + expect(base64Encode("🎉")).toBe("8J+OiQ=="); + }); + + it("should handle basic auth credentials", () => { + expect(base64Encode("username:password")).toBe("dXNlcm5hbWU6cGFzc3dvcmQ="); + }); + }); + + describe("base64Decode", () => { + it("should decode ASCII strings", () => { + expect(base64Decode("aGVsbG8=")).toBe("hello"); + expect(base64Decode("")).toBe(""); + }); + + it("should decode UTF-8 strings", () => { + expect(base64Decode("Y2Fmw6k=")).toBe("café"); + expect(base64Decode("8J+OiQ==")).toBe("🎉"); + }); + + it("should handle basic auth credentials", () => { + expect(base64Decode("dXNlcm5hbWU6cGFzc3dvcmQ=")).toBe("username:password"); + }); + }); + + describe("round-trip encoding", () => { + const testStrings = [ + "hello world", + "test@example.com", + "café", + "username:password", + "user@domain.com:super$ecret123!", + ]; + + testStrings.forEach((testString) => { + it(`should round-trip encode/decode: "${testString}"`, () => { + const encoded = base64Encode(testString); + const decoded = base64Decode(encoded); + expect(decoded).toBe(testString); + }); + }); + }); +}); diff --git a/tests/unit/fetcher/Fetcher.test.ts b/tests/unit/fetcher/Fetcher.test.ts index a32945e9..60df2b5e 100644 --- a/tests/unit/fetcher/Fetcher.test.ts +++ b/tests/unit/fetcher/Fetcher.test.ts @@ -1,7 +1,8 @@ import fs from "fs"; import { join } from "path"; - -import { Fetcher, fetcherImpl } from "../../../src/core/fetcher/Fetcher"; +import stream from "stream"; +import type { BinaryResponse } from "../../../src/core"; +import { type Fetcher, fetcherImpl } from "../../../src/core/fetcher/Fetcher"; describe("Test fetcherImpl", () => { it("should handle successful request", async () => { @@ -12,14 +13,16 @@ describe("Test fetcherImpl", () => { body: { data: "test" }, contentType: "application/json", requestType: "json", + maxRetries: 0, + responseType: "json", }; - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - text: () => Promise.resolve(JSON.stringify({ data: "test" })), - json: () => ({ data: "test" }), - }); + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + }), + ); const result = await fetcherImpl(mockArgs); expect(result.ok).toBe(true); @@ -31,7 +34,7 @@ describe("Test fetcherImpl", () => { "https://httpbin.org/post", expect.objectContaining({ method: "POST", - headers: expect.objectContaining({ "X-Test": "x-test-header" }), + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), body: JSON.stringify({ data: "test" }), }), ); @@ -45,16 +48,17 @@ describe("Test fetcherImpl", () => { headers: { "X-Test": "x-test-header" }, contentType: "application/octet-stream", requestType: "bytes", - duplex: "half", + maxRetries: 0, + responseType: "json", body: fs.createReadStream(join(__dirname, "test-file.txt")), }; - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - text: () => Promise.resolve(JSON.stringify({ data: "test" })), - json: () => Promise.resolve({ data: "test" }), - }); + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + }), + ); const result = await fetcherImpl(mockArgs); @@ -62,7 +66,7 @@ describe("Test fetcherImpl", () => { url, expect.objectContaining({ method: "POST", - headers: expect.objectContaining({ "X-Test": "x-test-header" }), + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), body: expect.any(fs.ReadStream), }), ); @@ -71,4 +75,187 @@ describe("Test fetcherImpl", () => { expect(result.body).toEqual({ data: "test" }); } }); + + it("should receive file as stream", async () => { + const url = "https://httpbin.org/post/file"; + const mockArgs: Fetcher.Args = { + url, + method: "GET", + headers: { "X-Test": "x-test-header" }, + maxRetries: 0, + responseType: "binary-response", + }; + + global.fetch = vi.fn().mockResolvedValue( + new Response( + stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream, + { + status: 200, + statusText: "OK", + }, + ), + ); + + const result = await fetcherImpl(mockArgs); + + expect(global.fetch).toHaveBeenCalledWith( + url, + expect.objectContaining({ + method: "GET", + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), + }), + ); + expect(result.ok).toBe(true); + if (result.ok) { + const body = result.body as BinaryResponse; + expect(body).toBeDefined(); + expect(body.bodyUsed).toBe(false); + expect(typeof body.stream).toBe("function"); + const stream = body.stream(); + expect(stream).toBeInstanceOf(ReadableStream); + const reader = stream.getReader(); + const { value } = await reader.read(); + const decoder = new TextDecoder(); + const streamContent = decoder.decode(value); + expect(streamContent).toBe("This is a test file!\n"); + expect(body.bodyUsed).toBe(true); + } + }); + + it("should receive file as blob", async () => { + const url = "https://httpbin.org/post/file"; + const mockArgs: Fetcher.Args = { + url, + method: "GET", + headers: { "X-Test": "x-test-header" }, + maxRetries: 0, + responseType: "binary-response", + }; + + global.fetch = vi.fn().mockResolvedValue( + new Response( + stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream, + { + status: 200, + statusText: "OK", + }, + ), + ); + + const result = await fetcherImpl(mockArgs); + + expect(global.fetch).toHaveBeenCalledWith( + url, + expect.objectContaining({ + method: "GET", + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), + }), + ); + expect(result.ok).toBe(true); + if (result.ok) { + const body = result.body as BinaryResponse; + expect(body).toBeDefined(); + expect(body.bodyUsed).toBe(false); + expect(typeof body.blob).toBe("function"); + const blob = await body.blob(); + expect(blob).toBeInstanceOf(Blob); + const reader = blob.stream().getReader(); + const { value } = await reader.read(); + const decoder = new TextDecoder(); + const streamContent = decoder.decode(value); + expect(streamContent).toBe("This is a test file!\n"); + expect(body.bodyUsed).toBe(true); + } + }); + + it("should receive file as arraybuffer", async () => { + const url = "https://httpbin.org/post/file"; + const mockArgs: Fetcher.Args = { + url, + method: "GET", + headers: { "X-Test": "x-test-header" }, + maxRetries: 0, + responseType: "binary-response", + }; + + global.fetch = vi.fn().mockResolvedValue( + new Response( + stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream, + { + status: 200, + statusText: "OK", + }, + ), + ); + + const result = await fetcherImpl(mockArgs); + + expect(global.fetch).toHaveBeenCalledWith( + url, + expect.objectContaining({ + method: "GET", + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), + }), + ); + expect(result.ok).toBe(true); + if (result.ok) { + const body = result.body as BinaryResponse; + expect(body).toBeDefined(); + expect(body.bodyUsed).toBe(false); + expect(typeof body.arrayBuffer).toBe("function"); + const arrayBuffer = await body.arrayBuffer(); + expect(arrayBuffer).toBeInstanceOf(ArrayBuffer); + const decoder = new TextDecoder(); + const streamContent = decoder.decode(new Uint8Array(arrayBuffer)); + expect(streamContent).toBe("This is a test file!\n"); + expect(body.bodyUsed).toBe(true); + } + }); + + it("should receive file as bytes", async () => { + const url = "https://httpbin.org/post/file"; + const mockArgs: Fetcher.Args = { + url, + method: "GET", + headers: { "X-Test": "x-test-header" }, + maxRetries: 0, + responseType: "binary-response", + }; + + global.fetch = vi.fn().mockResolvedValue( + new Response( + stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream, + { + status: 200, + statusText: "OK", + }, + ), + ); + + const result = await fetcherImpl(mockArgs); + + expect(global.fetch).toHaveBeenCalledWith( + url, + expect.objectContaining({ + method: "GET", + headers: expect.toContainHeaders({ "X-Test": "x-test-header" }), + }), + ); + expect(result.ok).toBe(true); + if (result.ok) { + const body = result.body as BinaryResponse; + expect(body).toBeDefined(); + expect(body.bodyUsed).toBe(false); + expect(typeof body.bytes).toBe("function"); + if (!body.bytes) { + return; + } + const bytes = await body.bytes(); + expect(bytes).toBeInstanceOf(Uint8Array); + const decoder = new TextDecoder(); + const streamContent = decoder.decode(bytes); + expect(streamContent).toBe("This is a test file!\n"); + expect(body.bodyUsed).toBe(true); + } + }); }); diff --git a/tests/unit/fetcher/HttpResponsePromise.test.ts b/tests/unit/fetcher/HttpResponsePromise.test.ts index 2216a33e..2ec008e5 100644 --- a/tests/unit/fetcher/HttpResponsePromise.test.ts +++ b/tests/unit/fetcher/HttpResponsePromise.test.ts @@ -1,7 +1,7 @@ -import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { HttpResponsePromise } from "../../../src/core/fetcher/HttpResponsePromise"; -import { RawResponse, WithRawResponse } from "../../../src/core/fetcher/RawResponse"; +import type { RawResponse, WithRawResponse } from "../../../src/core/fetcher/RawResponse"; describe("HttpResponsePromise", () => { const mockRawResponse: RawResponse = { @@ -20,7 +20,7 @@ describe("HttpResponsePromise", () => { describe("fromFunction", () => { it("should create an HttpResponsePromise from a function", async () => { - const mockFn = jest + const mockFn = vi .fn<(arg1: string, arg2: string) => Promise>>() .mockResolvedValue(mockWithRawResponse); @@ -111,7 +111,7 @@ describe("HttpResponsePromise", () => { reject(new Error("Test error")); }); - const catchSpy = jest.fn(); + const catchSpy = vi.fn(); await errorResponsePromise.catch(catchSpy); expect(catchSpy).toHaveBeenCalled(); @@ -121,7 +121,7 @@ describe("HttpResponsePromise", () => { }); it("should support finally() method", async () => { - const finallySpy = jest.fn(); + const finallySpy = vi.fn(); await responsePromise.finally(finallySpy); expect(finallySpy).toHaveBeenCalled(); diff --git a/tests/unit/fetcher/RawResponse.test.ts b/tests/unit/fetcher/RawResponse.test.ts index 9ccd5e1e..375ee3f3 100644 --- a/tests/unit/fetcher/RawResponse.test.ts +++ b/tests/unit/fetcher/RawResponse.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "@jest/globals"; +import { describe, expect, it } from "vitest"; import { toRawResponse } from "../../../src/core/fetcher/RawResponse"; diff --git a/tests/unit/fetcher/createRequestUrl.test.ts b/tests/unit/fetcher/createRequestUrl.test.ts index 486e1e61..a92f1b5e 100644 --- a/tests/unit/fetcher/createRequestUrl.test.ts +++ b/tests/unit/fetcher/createRequestUrl.test.ts @@ -1,51 +1,163 @@ import { createRequestUrl } from "../../../src/core/fetcher/createRequestUrl"; describe("Test createRequestUrl", () => { - it("should return the base URL when no query parameters are provided", () => { - const baseUrl = "https://api.example.com"; - expect(createRequestUrl(baseUrl)).toBe(baseUrl); - }); + const BASE_URL = "https://api.example.com"; - it("should append simple query parameters", () => { - const baseUrl = "https://api.example.com"; - const queryParams = { key: "value", another: "param" }; - expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?key=value&another=param"); - }); + interface TestCase { + description: string; + baseUrl: string; + queryParams?: Record; + expected: string; + } - it("should handle array query parameters", () => { - const baseUrl = "https://api.example.com"; - const queryParams = { items: ["a", "b", "c"] }; - expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?items=a&items=b&items=c"); - }); - - it("should handle object query parameters", () => { - const baseUrl = "https://api.example.com"; - const queryParams = { filter: { name: "John", age: 30 } }; - expect(createRequestUrl(baseUrl, queryParams)).toBe( - "https://api.example.com?filter%5Bname%5D=John&filter%5Bage%5D=30", - ); - }); - - it("should handle mixed types of query parameters", () => { - const baseUrl = "https://api.example.com"; - const queryParams = { - simple: "value", - array: ["x", "y"], - object: { key: "value" }, - }; - expect(createRequestUrl(baseUrl, queryParams)).toBe( - "https://api.example.com?simple=value&array=x&array=y&object%5Bkey%5D=value", - ); - }); - - it("should handle empty query parameters object", () => { - const baseUrl = "https://api.example.com"; - expect(createRequestUrl(baseUrl, {})).toBe(baseUrl); - }); + const testCases: TestCase[] = [ + { + description: "should return the base URL when no query parameters are provided", + baseUrl: BASE_URL, + expected: BASE_URL, + }, + { + description: "should append simple query parameters", + baseUrl: BASE_URL, + queryParams: { key: "value", another: "param" }, + expected: "https://api.example.com?key=value&another=param", + }, + { + description: "should handle array query parameters", + baseUrl: BASE_URL, + queryParams: { items: ["a", "b", "c"] }, + expected: "https://api.example.com?items=a&items=b&items=c", + }, + { + description: "should handle object query parameters", + baseUrl: BASE_URL, + queryParams: { filter: { name: "John", age: 30 } }, + expected: "https://api.example.com?filter%5Bname%5D=John&filter%5Bage%5D=30", + }, + { + description: "should handle mixed types of query parameters", + baseUrl: BASE_URL, + queryParams: { + simple: "value", + array: ["x", "y"], + object: { key: "value" }, + }, + expected: "https://api.example.com?simple=value&array=x&array=y&object%5Bkey%5D=value", + }, + { + description: "should handle empty query parameters object", + baseUrl: BASE_URL, + queryParams: {}, + expected: BASE_URL, + }, + { + description: "should encode special characters in query parameters", + baseUrl: BASE_URL, + queryParams: { special: "a&b=c d" }, + expected: "https://api.example.com?special=a%26b%3Dc%20d", + }, + { + description: "should handle numeric values", + baseUrl: BASE_URL, + queryParams: { count: 42, price: 19.99, active: 1, inactive: 0 }, + expected: "https://api.example.com?count=42&price=19.99&active=1&inactive=0", + }, + { + description: "should handle boolean values", + baseUrl: BASE_URL, + queryParams: { enabled: true, disabled: false }, + expected: "https://api.example.com?enabled=true&disabled=false", + }, + { + description: "should handle null and undefined values", + baseUrl: BASE_URL, + queryParams: { + valid: "value", + nullValue: null, + undefinedValue: undefined, + emptyString: "", + }, + expected: "https://api.example.com?valid=value&nullValue=&emptyString=", + }, + { + description: "should handle deeply nested objects", + baseUrl: BASE_URL, + queryParams: { + user: { + profile: { + name: "John", + settings: { theme: "dark" }, + }, + }, + }, + expected: + "https://api.example.com?user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark", + }, + { + description: "should handle arrays of objects", + baseUrl: BASE_URL, + queryParams: { + users: [ + { name: "John", age: 30 }, + { name: "Jane", age: 25 }, + ], + }, + expected: + "https://api.example.com?users%5Bname%5D=John&users%5Bage%5D=30&users%5Bname%5D=Jane&users%5Bage%5D=25", + }, + { + description: "should handle mixed arrays", + baseUrl: BASE_URL, + queryParams: { + mixed: ["string", 42, true, { key: "value" }], + }, + expected: "https://api.example.com?mixed=string&mixed=42&mixed=true&mixed%5Bkey%5D=value", + }, + { + description: "should handle empty arrays", + baseUrl: BASE_URL, + queryParams: { emptyArray: [] }, + expected: BASE_URL, + }, + { + description: "should handle empty objects", + baseUrl: BASE_URL, + queryParams: { emptyObject: {} }, + expected: BASE_URL, + }, + { + description: "should handle special characters in keys", + baseUrl: BASE_URL, + queryParams: { "key with spaces": "value", "key[with]brackets": "value" }, + expected: "https://api.example.com?key%20with%20spaces=value&key%5Bwith%5Dbrackets=value", + }, + { + description: "should handle URL with existing query parameters", + baseUrl: "https://api.example.com?existing=param", + queryParams: { new: "value" }, + expected: "https://api.example.com?existing=param?new=value", + }, + { + description: "should handle complex nested structures", + baseUrl: BASE_URL, + queryParams: { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }, + expected: + "https://api.example.com?filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + }, + ]; - it("should encode special characters in query parameters", () => { - const baseUrl = "https://api.example.com"; - const queryParams = { special: "a&b=c d" }; - expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?special=a%26b%3Dc%20d"); + testCases.forEach(({ description, baseUrl, queryParams, expected }) => { + it(description, () => { + expect(createRequestUrl(baseUrl, queryParams)).toBe(expected); + }); }); }); diff --git a/tests/unit/fetcher/getFetchFn.test.ts b/tests/unit/fetcher/getFetchFn.test.ts deleted file mode 100644 index 9b315ad0..00000000 --- a/tests/unit/fetcher/getFetchFn.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { RUNTIME } from "../../../src/core/runtime"; -import { getFetchFn } from "../../../src/core/fetcher/getFetchFn"; - -describe("Test for getFetchFn", () => { - it("should get node-fetch function", async () => { - if (RUNTIME.type == "node") { - if (RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { - expect(await getFetchFn()).toBe(fetch); - } else { - expect(await getFetchFn()).toEqual((await import("node-fetch")).default as any); - } - } - }); - - it("should get fetch function", async () => { - if (RUNTIME.type == "browser") { - const fetchFn = await getFetchFn(); - expect(typeof fetchFn).toBe("function"); - expect(fetchFn.name).toBe("fetch"); - } - }); -}); diff --git a/tests/unit/fetcher/getRequestBody.test.ts b/tests/unit/fetcher/getRequestBody.test.ts index 919604c2..8a6c3a57 100644 --- a/tests/unit/fetcher/getRequestBody.test.ts +++ b/tests/unit/fetcher/getRequestBody.test.ts @@ -1,33 +1,123 @@ -import { RUNTIME } from "../../../src/core/runtime"; import { getRequestBody } from "../../../src/core/fetcher/getRequestBody"; +import { RUNTIME } from "../../../src/core/runtime"; describe("Test getRequestBody", () => { - it("should return FormData as is in Node environment", async () => { - if (RUNTIME.type === "node") { - const formData = new (await import("formdata-node")).FormData(); - formData.append("key", "value"); - const result = await getRequestBody({ - body: formData, - type: "file", - }); - expect(result).toBe(formData); - } - }); + interface TestCase { + description: string; + input: any; + type: "json" | "form" | "file" | "bytes" | "other"; + expected: any; + skipCondition?: () => boolean; + } + + const testCases: TestCase[] = [ + { + description: "should stringify body if not FormData in Node environment", + input: { key: "value" }, + type: "json", + expected: '{"key":"value"}', + skipCondition: () => RUNTIME.type !== "node", + }, + { + description: "should stringify body if not FormData in browser environment", + input: { key: "value" }, + type: "json", + expected: '{"key":"value"}', + skipCondition: () => RUNTIME.type !== "browser", + }, + { + description: "should return the Uint8Array", + input: new Uint8Array([1, 2, 3]), + type: "bytes", + expected: new Uint8Array([1, 2, 3]), + }, + { + description: "should serialize objects for form-urlencoded content type", + input: { username: "johndoe", email: "john@example.com" }, + type: "form", + expected: "username=johndoe&email=john%40example.com", + }, + { + description: "should serialize complex nested objects and arrays for form-urlencoded content type", + input: { + user: { + profile: { + name: "John Doe", + settings: { + theme: "dark", + notifications: true, + }, + }, + tags: ["admin", "user"], + contacts: [ + { type: "email", value: "john@example.com" }, + { type: "phone", value: "+1234567890" }, + ], + }, + filters: { + status: ["active", "pending"], + metadata: { + created: "2024-01-01", + categories: ["electronics", "books"], + }, + }, + preferences: ["notifications", "updates"], + }, + type: "form", + expected: + "user%5Bprofile%5D%5Bname%5D=John%20Doe&" + + "user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark&" + + "user%5Bprofile%5D%5Bsettings%5D%5Bnotifications%5D=true&" + + "user%5Btags%5D=admin&" + + "user%5Btags%5D=user&" + + "user%5Bcontacts%5D%5Btype%5D=email&" + + "user%5Bcontacts%5D%5Bvalue%5D=john%40example.com&" + + "user%5Bcontacts%5D%5Btype%5D=phone&" + + "user%5Bcontacts%5D%5Bvalue%5D=%2B1234567890&" + + "filters%5Bstatus%5D=active&" + + "filters%5Bstatus%5D=pending&" + + "filters%5Bmetadata%5D%5Bcreated%5D=2024-01-01&" + + "filters%5Bmetadata%5D%5Bcategories%5D=electronics&" + + "filters%5Bmetadata%5D%5Bcategories%5D=books&" + + "preferences=notifications&" + + "preferences=updates", + }, + { + description: "should return the input for pre-serialized form-urlencoded strings", + input: "key=value&another=param", + type: "other", + expected: "key=value&another=param", + }, + { + description: "should JSON stringify objects", + input: { key: "value" }, + type: "json", + expected: '{"key":"value"}', + }, + ]; + + testCases.forEach(({ description, input, type, expected, skipCondition }) => { + it(description, async () => { + if (skipCondition?.()) { + return; + } - it("should stringify body if not FormData in Node environment", async () => { - if (RUNTIME.type === "node") { - const body = { key: "value" }; const result = await getRequestBody({ - body, - type: "json", + body: input, + type, }); - expect(result).toBe('{"key":"value"}'); - } + + if (input instanceof Uint8Array) { + expect(result).toBe(input); + } else { + expect(result).toBe(expected); + } + }); }); it("should return FormData in browser environment", async () => { if (RUNTIME.type === "browser") { - const formData = new (await import("form-data")).default(); + const formData = new FormData(); formData.append("key", "value"); const result = await getRequestBody({ body: formData, @@ -36,42 +126,4 @@ describe("Test getRequestBody", () => { expect(result).toBe(formData); } }); - - it("should stringify body if not FormData in browser environment", async () => { - if (RUNTIME.type === "browser") { - const body = { key: "value" }; - const result = await getRequestBody({ - body, - type: "json", - }); - expect(result).toBe('{"key":"value"}'); - } - }); - - it("should return the Uint8Array", async () => { - const input = new Uint8Array([1, 2, 3]); - const result = await getRequestBody({ - body: input, - type: "bytes", - }); - expect(result).toBe(input); - }); - - it("should return the input for content-type 'application/x-www-form-urlencoded'", async () => { - const input = "key=value&another=param"; - const result = await getRequestBody({ - body: input, - type: "other", - }); - expect(result).toBe(input); - }); - - it("should JSON stringify objects", async () => { - const input = { key: "value" }; - const result = await getRequestBody({ - body: input, - type: "json", - }); - expect(result).toBe('{"key":"value"}'); - }); }); diff --git a/tests/unit/fetcher/getResponseBody.test.ts b/tests/unit/fetcher/getResponseBody.test.ts index 1030c517..ad6be7fc 100644 --- a/tests/unit/fetcher/getResponseBody.test.ts +++ b/tests/unit/fetcher/getResponseBody.test.ts @@ -1,8 +1,61 @@ -import { RUNTIME } from "../../../src/core/runtime"; import { getResponseBody } from "../../../src/core/fetcher/getResponseBody"; -import { chooseStreamWrapper } from "../../../src/core/fetcher/stream-wrappers/chooseStreamWrapper"; + +import { RUNTIME } from "../../../src/core/runtime"; describe("Test getResponseBody", () => { + interface SimpleTestCase { + description: string; + responseData: string | Record; + responseType?: "blob" | "sse" | "streaming" | "text"; + expected: any; + skipCondition?: () => boolean; + } + + const simpleTestCases: SimpleTestCase[] = [ + { + description: "should handle text response type", + responseData: "test text", + responseType: "text", + expected: "test text", + }, + { + description: "should handle JSON response", + responseData: { key: "value" }, + expected: { key: "value" }, + }, + { + description: "should handle empty response", + responseData: "", + expected: undefined, + }, + { + description: "should handle non-JSON response", + responseData: "invalid json", + expected: { + ok: false, + error: { + reason: "non-json", + statusCode: 200, + rawBody: "invalid json", + }, + }, + }, + ]; + + simpleTestCases.forEach(({ description, responseData, responseType, expected, skipCondition }) => { + it(description, async () => { + if (skipCondition?.()) { + return; + } + + const mockResponse = new Response( + typeof responseData === "string" ? responseData : JSON.stringify(responseData), + ); + const result = await getResponseBody(mockResponse, responseType); + expect(result).toEqual(expected); + }); + }); + it("should handle blob response type", async () => { const mockBlob = new Blob(["test"], { type: "text/plain" }); const mockResponse = new Response(mockBlob); @@ -21,44 +74,24 @@ describe("Test getResponseBody", () => { }); it("should handle streaming response type", async () => { - if (RUNTIME.type === "node") { - const mockStream = new ReadableStream(); - const mockResponse = new Response(mockStream); - const result = await getResponseBody(mockResponse, "streaming"); - // need to reinstantiate string as a result of locked state in Readable Stream after registration with Response - expect(JSON.stringify(result)).toBe(JSON.stringify(await chooseStreamWrapper(new ReadableStream()))); - } - }); - - it("should handle text response type", async () => { - const mockResponse = new Response("test text"); - const result = await getResponseBody(mockResponse, "text"); - expect(result).toBe("test text"); - }); + const encoder = new TextEncoder(); + const testData = "test stream data"; + const mockStream = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(testData)); + controller.close(); + }, + }); - it("should handle JSON response", async () => { - const mockJson = { key: "value" }; - const mockResponse = new Response(JSON.stringify(mockJson)); - const result = await getResponseBody(mockResponse); - expect(result).toEqual(mockJson); - }); + const mockResponse = new Response(mockStream); + const result = (await getResponseBody(mockResponse, "streaming")) as ReadableStream; - it("should handle empty response", async () => { - const mockResponse = new Response(""); - const result = await getResponseBody(mockResponse); - expect(result).toBeUndefined(); - }); + expect(result).toBeInstanceOf(ReadableStream); - it("should handle non-JSON response", async () => { - const mockResponse = new Response("invalid json"); - const result = await getResponseBody(mockResponse); - expect(result).toEqual({ - ok: false, - error: { - reason: "non-json", - statusCode: 200, - rawBody: "invalid json", - }, - }); + const reader = result.getReader(); + const decoder = new TextDecoder(); + const { value } = await reader.read(); + const streamContent = decoder.decode(value); + expect(streamContent).toBe(testData); }); }); diff --git a/tests/unit/fetcher/logging.test.ts b/tests/unit/fetcher/logging.test.ts new file mode 100644 index 00000000..366c9b6c --- /dev/null +++ b/tests/unit/fetcher/logging.test.ts @@ -0,0 +1,517 @@ +import { fetcherImpl } from "../../../src/core/fetcher/Fetcher"; + +function createMockLogger() { + return { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; +} + +function mockSuccessResponse(data: unknown = { data: "test" }, status = 200, statusText = "OK") { + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify(data), { + status, + statusText, + }), + ); +} + +function mockErrorResponse(data: unknown = { error: "Error" }, status = 404, statusText = "Not Found") { + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify(data), { + status, + statusText, + }), + ); +} + +describe("Fetcher Logging Integration", () => { + describe("Request Logging", () => { + it("should log successful request at debug level", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "POST", + headers: { "Content-Type": "application/json" }, + body: { test: "data" }, + contentType: "application/json", + requestType: "json", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + method: "POST", + url: "https://example.com/api", + headers: expect.toContainHeaders({ + "Content-Type": "application/json", + }), + hasBody: true, + }), + ); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "HTTP request succeeded", + expect.objectContaining({ + method: "POST", + url: "https://example.com/api", + statusCode: 200, + }), + ); + }); + + it("should not log debug messages at info level for successful requests", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "info", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).not.toHaveBeenCalled(); + }); + + it("should log request with body flag", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "POST", + body: { data: "test" }, + contentType: "application/json", + requestType: "json", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + hasBody: true, + }), + ); + }); + + it("should log request without body flag", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + hasBody: false, + }), + ); + }); + + it("should not log when silent mode is enabled", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: true, + }, + }); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).not.toHaveBeenCalled(); + expect(mockLogger.warn).not.toHaveBeenCalled(); + expect(mockLogger.error).not.toHaveBeenCalled(); + }); + + it("should not log when no logging config is provided", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + }); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + }); + }); + + describe("Error Logging", () => { + it("should log 4xx errors at error level", async () => { + const mockLogger = createMockLogger(); + mockErrorResponse({ error: "Not found" }, 404, "Not Found"); + + const result = await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(result.ok).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request failed with error status", + expect.objectContaining({ + method: "GET", + url: "https://example.com/api", + statusCode: 404, + }), + ); + }); + + it("should log 5xx errors at error level", async () => { + const mockLogger = createMockLogger(); + mockErrorResponse({ error: "Internal error" }, 500, "Internal Server Error"); + + const result = await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(result.ok).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request failed with error status", + expect.objectContaining({ + method: "GET", + url: "https://example.com/api", + statusCode: 500, + }), + ); + }); + + it("should log aborted request errors", async () => { + const mockLogger = createMockLogger(); + + const abortController = new AbortController(); + abortController.abort(); + + global.fetch = vi.fn().mockRejectedValue(new Error("Aborted")); + + const result = await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + abortSignal: abortController.signal, + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(result.ok).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request was aborted", + expect.objectContaining({ + method: "GET", + url: "https://example.com/api", + }), + ); + }); + + it("should log timeout errors", async () => { + const mockLogger = createMockLogger(); + + const timeoutError = new Error("Request timeout"); + timeoutError.name = "AbortError"; + + global.fetch = vi.fn().mockRejectedValue(timeoutError); + + const result = await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(result.ok).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request timed out", + expect.objectContaining({ + method: "GET", + url: "https://example.com/api", + timeoutMs: undefined, + }), + ); + }); + + it("should log unknown errors", async () => { + const mockLogger = createMockLogger(); + + const unknownError = new Error("Unknown error"); + + global.fetch = vi.fn().mockRejectedValue(unknownError); + + const result = await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(result.ok).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request failed with error", + expect.objectContaining({ + method: "GET", + url: "https://example.com/api", + errorMessage: "Unknown error", + }), + ); + }); + }); + + describe("Logging with Redaction", () => { + it("should redact sensitive data in error logs", async () => { + const mockLogger = createMockLogger(); + mockErrorResponse({ error: "Unauthorized" }, 401, "Unauthorized"); + + await fetcherImpl({ + url: "https://example.com/api?api_key=secret", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request failed with error status", + expect.objectContaining({ + url: "https://example.com/api?api_key=[REDACTED]", + }), + ); + }); + }); + + describe("Different HTTP Methods", () => { + it("should log GET requests", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("should log POST requests", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse({ data: "test" }, 201, "Created"); + + await fetcherImpl({ + url: "https://example.com/api", + method: "POST", + body: { data: "test" }, + contentType: "application/json", + requestType: "json", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + method: "POST", + }), + ); + }); + + it("should log PUT requests", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "PUT", + body: { data: "test" }, + contentType: "application/json", + requestType: "json", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + method: "PUT", + }), + ); + }); + + it("should log DELETE requests", async () => { + const mockLogger = createMockLogger(); + global.fetch = vi.fn().mockResolvedValue( + new Response(null, { + status: 200, + statusText: "OK", + }), + ); + + await fetcherImpl({ + url: "https://example.com/api", + method: "DELETE", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + method: "DELETE", + }), + ); + }); + }); + + describe("Status Code Logging", () => { + it("should log 2xx success status codes", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse({ data: "test" }, 201, "Created"); + + await fetcherImpl({ + url: "https://example.com/api", + method: "POST", + body: { data: "test" }, + contentType: "application/json", + requestType: "json", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "HTTP request succeeded", + expect.objectContaining({ + statusCode: 201, + }), + ); + }); + + it("should log 3xx redirect status codes as success", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse({ data: "test" }, 301, "Moved Permanently"); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "HTTP request succeeded", + expect.objectContaining({ + statusCode: 301, + }), + ); + }); + }); +}); diff --git a/tests/unit/fetcher/makeRequest.test.ts b/tests/unit/fetcher/makeRequest.test.ts index 43ed9d11..ea49466a 100644 --- a/tests/unit/fetcher/makeRequest.test.ts +++ b/tests/unit/fetcher/makeRequest.test.ts @@ -1,3 +1,4 @@ +import type { Mock } from "vitest"; import { makeRequest } from "../../../src/core/fetcher/makeRequest"; describe("Test makeRequest", () => { @@ -6,10 +7,10 @@ describe("Test makeRequest", () => { const mockHeaders = { "Content-Type": "application/json" }; const mockBody = JSON.stringify({ key: "value" }); - let mockFetch: jest.Mock; + let mockFetch: Mock; beforeEach(() => { - mockFetch = jest.fn(); + mockFetch = vi.fn(); mockFetch.mockResolvedValue(new Response(JSON.stringify({ test: "successful" }), { status: 200 })); }); diff --git a/tests/unit/fetcher/redacting.test.ts b/tests/unit/fetcher/redacting.test.ts new file mode 100644 index 00000000..d599376b --- /dev/null +++ b/tests/unit/fetcher/redacting.test.ts @@ -0,0 +1,1115 @@ +import { fetcherImpl } from "../../../src/core/fetcher/Fetcher"; + +function createMockLogger() { + return { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; +} + +function mockSuccessResponse(data: unknown = { data: "test" }, status = 200, statusText = "OK") { + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify(data), { + status, + statusText, + }), + ); +} + +describe("Redacting Logic", () => { + describe("Header Redaction", () => { + it("should redact authorization header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { Authorization: "Bearer secret-token-12345" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + Authorization: "[REDACTED]", + }), + }), + ); + }); + + it("should redact api-key header (case-insensitive)", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "X-API-KEY": "secret-api-key" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "X-API-KEY": "[REDACTED]", + }), + }), + ); + }); + + it("should redact cookie header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { Cookie: "session=abc123; token=xyz789" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + Cookie: "[REDACTED]", + }), + }), + ); + }); + + it("should redact x-auth-token header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "x-auth-token": "auth-token-12345" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "x-auth-token": "[REDACTED]", + }), + }), + ); + }); + + it("should redact proxy-authorization header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "Proxy-Authorization": "Basic credentials" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "Proxy-Authorization": "[REDACTED]", + }), + }), + ); + }); + + it("should redact x-csrf-token header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "X-CSRF-Token": "csrf-token-abc" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "X-CSRF-Token": "[REDACTED]", + }), + }), + ); + }); + + it("should redact www-authenticate header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "WWW-Authenticate": "Bearer realm=example" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "WWW-Authenticate": "[REDACTED]", + }), + }), + ); + }); + + it("should redact x-session-token header", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { "X-Session-Token": "session-token-xyz" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "X-Session-Token": "[REDACTED]", + }), + }), + ); + }); + + it("should not redact non-sensitive headers", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { + "Content-Type": "application/json", + "User-Agent": "Test/1.0", + Accept: "application/json", + }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + "Content-Type": "application/json", + "User-Agent": "Test/1.0", + Accept: "application/json", + }), + }), + ); + }); + + it("should redact multiple sensitive headers at once", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + headers: { + Authorization: "Bearer token", + "X-API-Key": "api-key", + Cookie: "session=123", + "Content-Type": "application/json", + }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + headers: expect.toContainHeaders({ + Authorization: "[REDACTED]", + "X-API-Key": "[REDACTED]", + Cookie: "[REDACTED]", + "Content-Type": "application/json", + }), + }), + ); + }); + }); + + describe("Response Header Redaction", () => { + it("should redact Set-Cookie in response headers", async () => { + const mockLogger = createMockLogger(); + + const mockHeaders = new Headers(); + mockHeaders.set("Set-Cookie", "session=abc123; HttpOnly; Secure"); + mockHeaders.set("Content-Type", "application/json"); + + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + headers: mockHeaders, + }), + ); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "HTTP request succeeded", + expect.objectContaining({ + responseHeaders: expect.toContainHeaders({ + "set-cookie": "[REDACTED]", + "content-type": "application/json", + }), + }), + ); + }); + + it("should redact authorization in response headers", async () => { + const mockLogger = createMockLogger(); + + const mockHeaders = new Headers(); + mockHeaders.set("Authorization", "Bearer token-123"); + mockHeaders.set("Content-Type", "application/json"); + + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + headers: mockHeaders, + }), + ); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "HTTP request succeeded", + expect.objectContaining({ + responseHeaders: expect.toContainHeaders({ + authorization: "[REDACTED]", + "content-type": "application/json", + }), + }), + ); + }); + + it("should redact response headers in error responses", async () => { + const mockLogger = createMockLogger(); + + const mockHeaders = new Headers(); + mockHeaders.set("WWW-Authenticate", "Bearer realm=example"); + mockHeaders.set("Content-Type", "application/json"); + + global.fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ error: "Unauthorized" }), { + status: 401, + statusText: "Unauthorized", + headers: mockHeaders, + }), + ); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "error", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.error).toHaveBeenCalledWith( + "HTTP request failed with error status", + expect.objectContaining({ + responseHeaders: expect.toContainHeaders({ + "www-authenticate": "[REDACTED]", + "content-type": "application/json", + }), + }), + ); + }); + }); + + describe("Query Parameter Redaction", () => { + it("should redact api_key query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { api_key: "secret-key" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + api_key: "[REDACTED]", + }), + }), + ); + }); + + it("should redact token query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { token: "secret-token" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + token: "[REDACTED]", + }), + }), + ); + }); + + it("should redact access_token query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { access_token: "secret-access-token" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + access_token: "[REDACTED]", + }), + }), + ); + }); + + it("should redact password query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { password: "secret-password" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + password: "[REDACTED]", + }), + }), + ); + }); + + it("should redact secret query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { secret: "secret-value" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + secret: "[REDACTED]", + }), + }), + ); + }); + + it("should redact session_id query parameter", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { session_id: "session-123" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + session_id: "[REDACTED]", + }), + }), + ); + }); + + it("should not redact non-sensitive query parameters", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { + page: "1", + limit: "10", + sort: "name", + }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + page: "1", + limit: "10", + sort: "name", + }), + }), + ); + }); + + it("should not redact parameters containing 'auth' substring like 'author'", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { + author: "john", + authenticate: "false", + authorization_level: "user", + }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + author: "john", + authenticate: "false", + authorization_level: "user", + }), + }), + ); + }); + + it("should handle undefined query parameters", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: undefined, + }), + ); + }); + + it("should redact case-insensitive query parameters", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + queryParameters: { API_KEY: "secret-key", Token: "secret-token" }, + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + queryParameters: expect.objectContaining({ + API_KEY: "[REDACTED]", + Token: "[REDACTED]", + }), + }), + ); + }); + }); + + describe("URL Redaction", () => { + it("should redact credentials in URL", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://user:password@example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://[REDACTED]@example.com/api", + }), + ); + }); + + it("should redact api_key in query string", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?api_key=secret-key&page=1", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?api_key=[REDACTED]&page=1", + }), + ); + }); + + it("should redact token in query string", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?token=secret-token", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?token=[REDACTED]", + }), + ); + }); + + it("should redact password in query string", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?username=user&password=secret", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?username=user&password=[REDACTED]", + }), + ); + }); + + it("should not redact non-sensitive query strings", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?page=1&limit=10&sort=name", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?page=1&limit=10&sort=name", + }), + ); + }); + + it("should not redact URL parameters containing 'auth' substring like 'author'", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?author=john&authenticate=false&page=1", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?author=john&authenticate=false&page=1", + }), + ); + }); + + it("should handle URL with fragment", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?token=secret#section", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?token=[REDACTED]#section", + }), + ); + }); + + it("should redact URL-encoded query parameters", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?api%5Fkey=secret", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?api%5Fkey=[REDACTED]", + }), + ); + }); + + it("should handle URL without query string", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api", + }), + ); + }); + + it("should handle empty query string", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?", + }), + ); + }); + + it("should redact multiple sensitive parameters in URL", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?api_key=secret1&token=secret2&page=1", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?api_key=[REDACTED]&token=[REDACTED]&page=1", + }), + ); + }); + + it("should redact both credentials and query parameters", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://user:pass@example.com/api?token=secret", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://[REDACTED]@example.com/api?token=[REDACTED]", + }), + ); + }); + + it("should use fast path for URLs without sensitive keywords", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?page=1&limit=10&sort=name&filter=value", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?page=1&limit=10&sort=name&filter=value", + }), + ); + }); + + it("should handle query parameter without value", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?flag&token=secret", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?flag&token=[REDACTED]", + }), + ); + }); + + it("should handle URL with multiple @ symbols in credentials", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://user@example.com:pass@host.com/api", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://[REDACTED]@host.com/api", + }), + ); + }); + + it("should handle URL with @ in query parameter but not in credentials", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://example.com/api?email=user@example.com", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://example.com/api?email=user@example.com", + }), + ); + }); + + it("should handle URL with both credentials and @ in path", async () => { + const mockLogger = createMockLogger(); + mockSuccessResponse(); + + await fetcherImpl({ + url: "https://user:pass@example.com/users/@username", + method: "GET", + responseType: "json", + maxRetries: 0, + logging: { + level: "debug", + logger: mockLogger, + silent: false, + }, + }); + + expect(mockLogger.debug).toHaveBeenCalledWith( + "Making HTTP request", + expect.objectContaining({ + url: "https://[REDACTED]@example.com/users/@username", + }), + ); + }); + }); +}); diff --git a/tests/unit/fetcher/requestWithRetries.test.ts b/tests/unit/fetcher/requestWithRetries.test.ts index 3cdaa40a..d2266136 100644 --- a/tests/unit/fetcher/requestWithRetries.test.ts +++ b/tests/unit/fetcher/requestWithRetries.test.ts @@ -1,28 +1,43 @@ +import type { Mock, MockInstance } from "vitest"; import { requestWithRetries } from "../../../src/core/fetcher/requestWithRetries"; describe("requestWithRetries", () => { - let mockFetch: jest.Mock; + let mockFetch: Mock; let originalMathRandom: typeof Math.random; - let setTimeoutSpy: jest.SpyInstance; + let setTimeoutSpy: MockInstance; beforeEach(() => { - mockFetch = jest.fn(); + mockFetch = vi.fn(); originalMathRandom = Math.random; - // Mock Math.random for consistent jitter - Math.random = jest.fn(() => 0.5); - - jest.useFakeTimers({ doNotFake: ["nextTick"] }); + Math.random = vi.fn(() => 0.5); + + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "setImmediate", + "clearImmediate", + "Date", + "performance", + "requestAnimationFrame", + "cancelAnimationFrame", + "requestIdleCallback", + "cancelIdleCallback", + ], + }); }); afterEach(() => { Math.random = originalMathRandom; - jest.clearAllMocks(); - jest.clearAllTimers(); + vi.clearAllMocks(); + vi.clearAllTimers(); }); it("should retry on retryable status codes", async () => { - setTimeoutSpy = jest.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { process.nextTick(callback); return null as any; }); @@ -38,7 +53,7 @@ describe("requestWithRetries", () => { }); const responsePromise = requestWithRetries(() => mockFetch(), retryableStatuses.length); - await jest.runAllTimersAsync(); + await vi.runAllTimersAsync(); const response = await responsePromise; expect(mockFetch).toHaveBeenCalledTimes(retryableStatuses.length + 1); @@ -46,7 +61,7 @@ describe("requestWithRetries", () => { }); it("should respect maxRetries limit", async () => { - setTimeoutSpy = jest.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { process.nextTick(callback); return null as any; }); @@ -55,7 +70,7 @@ describe("requestWithRetries", () => { mockFetch.mockResolvedValue(new Response("", { status: 500 })); const responsePromise = requestWithRetries(() => mockFetch(), maxRetries); - await jest.runAllTimersAsync(); + await vi.runAllTimersAsync(); const response = await responsePromise; expect(mockFetch).toHaveBeenCalledTimes(maxRetries + 1); @@ -63,7 +78,7 @@ describe("requestWithRetries", () => { }); it("should not retry on success status codes", async () => { - setTimeoutSpy = jest.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { process.nextTick(callback); return null as any; }); @@ -76,7 +91,7 @@ describe("requestWithRetries", () => { mockFetch.mockResolvedValueOnce(new Response("", { status })); const responsePromise = requestWithRetries(() => mockFetch(), 3); - await jest.runAllTimersAsync(); + await vi.runAllTimersAsync(); await responsePromise; expect(mockFetch).toHaveBeenCalledTimes(1); @@ -84,8 +99,69 @@ describe("requestWithRetries", () => { } }); + interface RetryHeaderTestCase { + description: string; + headerName: string; + headerValue: string | (() => string); + expectedDelayMin: number; + expectedDelayMax: number; + } + + const retryHeaderTests: RetryHeaderTestCase[] = [ + { + description: "should respect retry-after header with seconds value", + headerName: "retry-after", + headerValue: "5", + expectedDelayMin: 4000, + expectedDelayMax: 6000, + }, + { + description: "should respect retry-after header with HTTP date value", + headerName: "retry-after", + headerValue: () => new Date(Date.now() + 3000).toUTCString(), + expectedDelayMin: 2000, + expectedDelayMax: 4000, + }, + { + description: "should respect x-ratelimit-reset header", + headerName: "x-ratelimit-reset", + headerValue: () => Math.floor((Date.now() + 4000) / 1000).toString(), + expectedDelayMin: 3000, + expectedDelayMax: 6000, + }, + ]; + + retryHeaderTests.forEach(({ description, headerName, headerValue, expectedDelayMin, expectedDelayMax }) => { + it(description, async () => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + process.nextTick(callback); + return null as any; + }); + + const value = typeof headerValue === "function" ? headerValue() : headerValue; + mockFetch + .mockResolvedValueOnce( + new Response("", { + status: 429, + headers: new Headers({ [headerName]: value }), + }), + ) + .mockResolvedValueOnce(new Response("", { status: 200 })); + + const responsePromise = requestWithRetries(() => mockFetch(), 1); + await vi.runAllTimersAsync(); + const response = await responsePromise; + + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), expect.any(Number)); + const actualDelay = setTimeoutSpy.mock.calls[0][1]; + expect(actualDelay).toBeGreaterThan(expectedDelayMin); + expect(actualDelay).toBeLessThan(expectedDelayMax); + expect(response.status).toBe(200); + }); + }); + it("should apply correct exponential backoff with jitter", async () => { - setTimeoutSpy = jest.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { process.nextTick(callback); return null as any; }); @@ -95,10 +171,9 @@ describe("requestWithRetries", () => { const expectedDelays = [1000, 2000, 4000]; const responsePromise = requestWithRetries(() => mockFetch(), maxRetries); - await jest.runAllTimersAsync(); + await vi.runAllTimersAsync(); await responsePromise; - // Verify setTimeout calls expect(setTimeoutSpy).toHaveBeenCalledTimes(expectedDelays.length); expectedDelays.forEach((delay, index) => { @@ -109,7 +184,7 @@ describe("requestWithRetries", () => { }); it("should handle concurrent retries independently", async () => { - setTimeoutSpy = jest.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { process.nextTick(callback); return null as any; }); @@ -123,10 +198,33 @@ describe("requestWithRetries", () => { const promise1 = requestWithRetries(() => mockFetch(), 1); const promise2 = requestWithRetries(() => mockFetch(), 1); - await jest.runAllTimersAsync(); + await vi.runAllTimersAsync(); const [response1, response2] = await Promise.all([promise1, promise2]); expect(response1.status).toBe(200); expect(response2.status).toBe(200); }); + + it("should cap delay at MAX_RETRY_DELAY for large header values", async () => { + setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => { + process.nextTick(callback); + return null as any; + }); + + mockFetch + .mockResolvedValueOnce( + new Response("", { + status: 429, + headers: new Headers({ "retry-after": "120" }), // 120 seconds = 120000ms > MAX_RETRY_DELAY (60000ms) + }), + ) + .mockResolvedValueOnce(new Response("", { status: 200 })); + + const responsePromise = requestWithRetries(() => mockFetch(), 1); + await vi.runAllTimersAsync(); + const response = await responsePromise; + + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 60000); + expect(response.status).toBe(200); + }); }); diff --git a/tests/unit/fetcher/signals.test.ts b/tests/unit/fetcher/signals.test.ts index 9cabfa07..d7b6d1e6 100644 --- a/tests/unit/fetcher/signals.test.ts +++ b/tests/unit/fetcher/signals.test.ts @@ -2,11 +2,11 @@ import { anySignal, getTimeoutSignal } from "../../../src/core/fetcher/signals"; describe("Test getTimeoutSignal", () => { beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); it("should return an object with signal and abortId", () => { @@ -24,10 +24,10 @@ describe("Test getTimeoutSignal", () => { expect(signal.aborted).toBe(false); - jest.advanceTimersByTime(timeoutMs - 1); + vi.advanceTimersByTime(timeoutMs - 1); expect(signal.aborted).toBe(false); - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); expect(signal.aborted).toBe(true); }); }); diff --git a/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts deleted file mode 100644 index 172c1c26..00000000 --- a/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { Node18UniversalStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper"; - -describe("Node18UniversalStreamWrapper", () => { - it("should set encoding to utf-8", async () => { - const rawStream = new ReadableStream(); - const stream = new Node18UniversalStreamWrapper(rawStream); - const setEncodingSpy = jest.spyOn(stream, "setEncoding"); - - stream.setEncoding("utf-8"); - - expect(setEncodingSpy).toHaveBeenCalledWith("utf-8"); - }); - - it("should register an event listener for readable", async () => { - const rawStream = new ReadableStream(); - const stream = new Node18UniversalStreamWrapper(rawStream); - const onSpy = jest.spyOn(stream, "on"); - - stream.on("readable", () => {}); - - expect(onSpy).toHaveBeenCalledWith("readable", expect.any(Function)); - }); - - it("should remove an event listener for data", async () => { - const rawStream = new ReadableStream(); - const stream = new Node18UniversalStreamWrapper(rawStream); - const offSpy = jest.spyOn(stream, "off"); - - const fn = () => {}; - stream.on("data", fn); - stream.off("data", fn); - - expect(offSpy).toHaveBeenCalledWith("data", expect.any(Function)); - }); - - it("should write to dest when calling pipe to writable stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - const dest = new WritableStream({ - write(chunk) { - expect(chunk).toEqual(new TextEncoder().encode("test")); - }, - }); - - stream.pipe(dest); - }); - - it("should write to dest when calling pipe to node writable stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - const dest = new (await import("readable-stream")).Writable({ - write(chunk, encoding, callback) { - expect(chunk.toString()).toEqual("test"); - callback(); - }, - }); - - stream.pipe(dest); - }); - - it("should write nothing when calling pipe and unpipe", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - const buffer: Uint8Array[] = []; - const dest = new WritableStream({ - write(chunk) { - buffer.push(chunk); - }, - }); - - stream.pipe(dest); - stream.unpipe(dest); - expect(buffer).toEqual([]); - }); - - it("should destroy the stream", async () => { - const rawStream = new ReadableStream(); - const stream = new Node18UniversalStreamWrapper(rawStream); - const destroySpy = jest.spyOn(stream, "destroy"); - - stream.destroy(); - - expect(destroySpy).toHaveBeenCalled(); - }); - - it("should pause and resume the stream", async () => { - const rawStream = new ReadableStream(); - const stream = new Node18UniversalStreamWrapper(rawStream); - const pauseSpy = jest.spyOn(stream, "pause"); - const resumeSpy = jest.spyOn(stream, "resume"); - - expect(stream.isPaused).toBe(false); - stream.pause(); - expect(stream.isPaused).toBe(true); - stream.resume(); - - expect(pauseSpy).toHaveBeenCalled(); - expect(resumeSpy).toHaveBeenCalled(); - }); - - it("should read the stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - - expect(await stream.read()).toEqual(new TextEncoder().encode("test")); - expect(await stream.read()).toEqual(new TextEncoder().encode("test")); - }); - - it("should read the stream as text", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - - const data = await stream.text(); - - expect(data).toEqual("testtest"); - }); - - it("should read the stream as json", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode(JSON.stringify({ test: "test" }))); - controller.close(); - }, - }); - const stream = new Node18UniversalStreamWrapper(rawStream); - - const data = await stream.json(); - - expect(data).toEqual({ test: "test" }); - }); - - it("should allow use with async iterable stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - let data = ""; - const stream = new Node18UniversalStreamWrapper(rawStream); - for await (const chunk of stream) { - data += new TextDecoder().decode(chunk); - } - - expect(data).toEqual("testtest"); - }); -}); diff --git a/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts deleted file mode 100644 index 19c26668..00000000 --- a/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { NodePre18StreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/NodePre18StreamWrapper"; - -describe("NodePre18StreamWrapper", () => { - it("should set encoding to utf-8", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const setEncodingSpy = jest.spyOn(stream, "setEncoding"); - - stream.setEncoding("utf-8"); - - expect(setEncodingSpy).toHaveBeenCalledWith("utf-8"); - }); - - it("should register an event listener for readable", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const onSpy = jest.spyOn(stream, "on"); - - stream.on("readable", () => {}); - - expect(onSpy).toHaveBeenCalledWith("readable", expect.any(Function)); - }); - - it("should remove an event listener for data", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const offSpy = jest.spyOn(stream, "off"); - - const fn = () => {}; - stream.on("data", fn); - stream.off("data", fn); - - expect(offSpy).toHaveBeenCalledWith("data", expect.any(Function)); - }); - - it("should write to dest when calling pipe to node writable stream", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const dest = new (await import("readable-stream")).Writable({ - write(chunk, encoding, callback) { - expect(chunk.toString()).toEqual("test"); - callback(); - }, - }); - - stream.pipe(dest); - }); - - it("should write nothing when calling pipe and unpipe", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const buffer: Uint8Array[] = []; - const dest = new (await import("readable-stream")).Writable({ - write(chunk, encoding, callback) { - buffer.push(chunk); - callback(); - }, - }); - stream.pipe(dest); - stream.unpipe(); - - expect(buffer).toEqual([]); - }); - - it("should destroy the stream", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const destroySpy = jest.spyOn(stream, "destroy"); - - stream.destroy(); - - expect(destroySpy).toHaveBeenCalledWith(); - }); - - it("should pause the stream and resume", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - const pauseSpy = jest.spyOn(stream, "pause"); - - stream.pause(); - expect(stream.isPaused).toBe(true); - stream.resume(); - expect(stream.isPaused).toBe(false); - - expect(pauseSpy).toHaveBeenCalledWith(); - }); - - it("should read the stream", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - - expect(await stream.read()).toEqual("test"); - expect(await stream.read()).toEqual("test"); - }); - - it("should read the stream as text", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - const stream = new NodePre18StreamWrapper(rawStream); - - const data = await stream.text(); - - expect(data).toEqual("testtest"); - }); - - it("should read the stream as json", async () => { - const rawStream = (await import("readable-stream")).Readable.from([JSON.stringify({ test: "test" })]); - const stream = new NodePre18StreamWrapper(rawStream); - - const data = await stream.json(); - - expect(data).toEqual({ test: "test" }); - }); - - it("should allow use with async iterable stream", async () => { - const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); - let data = ""; - const stream = new NodePre18StreamWrapper(rawStream); - for await (const chunk of stream) { - data += chunk; - } - - expect(data).toEqual("testtest"); - }); -}); diff --git a/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts deleted file mode 100644 index 0ea14835..00000000 --- a/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { UndiciStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/UndiciStreamWrapper"; - -describe("UndiciStreamWrapper", () => { - it("should set encoding to utf-8", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const setEncodingSpy = jest.spyOn(stream, "setEncoding"); - - stream.setEncoding("utf-8"); - - expect(setEncodingSpy).toHaveBeenCalledWith("utf-8"); - }); - - it("should register an event listener for readable", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const onSpy = jest.spyOn(stream, "on"); - - stream.on("readable", () => {}); - - expect(onSpy).toHaveBeenCalledWith("readable", expect.any(Function)); - }); - - it("should remove an event listener for data", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const offSpy = jest.spyOn(stream, "off"); - - const fn = () => {}; - stream.on("data", fn); - stream.off("data", fn); - - expect(offSpy).toHaveBeenCalledWith("data", expect.any(Function)); - }); - - it("should write to dest when calling pipe to writable stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new UndiciStreamWrapper(rawStream); - const dest = new WritableStream({ - write(chunk) { - expect(chunk).toEqual(new TextEncoder().encode("test")); - }, - }); - - stream.pipe(dest); - }); - - it("should write nothing when calling pipe and unpipe", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const buffer: Uint8Array[] = []; - const dest = new WritableStream({ - write(chunk) { - buffer.push(chunk); - }, - }); - stream.pipe(dest); - stream.unpipe(dest); - - expect(buffer).toEqual([]); - }); - - it("should destroy the stream", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const destroySpy = jest.spyOn(stream, "destroy"); - - stream.destroy(); - - expect(destroySpy).toHaveBeenCalled(); - }); - - it("should pause and resume the stream", async () => { - const rawStream = new ReadableStream(); - const stream = new UndiciStreamWrapper(rawStream); - const pauseSpy = jest.spyOn(stream, "pause"); - const resumeSpy = jest.spyOn(stream, "resume"); - - expect(stream.isPaused).toBe(false); - stream.pause(); - expect(stream.isPaused).toBe(true); - stream.resume(); - - expect(pauseSpy).toHaveBeenCalled(); - expect(resumeSpy).toHaveBeenCalled(); - }); - - it("should read the stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new UndiciStreamWrapper(rawStream); - - expect(await stream.read()).toEqual(new TextEncoder().encode("test")); - expect(await stream.read()).toEqual(new TextEncoder().encode("test")); - }); - - it("should read the stream as text", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - const stream = new UndiciStreamWrapper(rawStream); - - const data = await stream.text(); - - expect(data).toEqual("testtest"); - }); - - it("should read the stream as json", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode(JSON.stringify({ test: "test" }))); - controller.close(); - }, - }); - const stream = new UndiciStreamWrapper(rawStream); - - const data = await stream.json(); - - expect(data).toEqual({ test: "test" }); - }); - - it("should allow use with async iterable stream", async () => { - const rawStream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("test")); - controller.enqueue(new TextEncoder().encode("test")); - controller.close(); - }, - }); - let data = ""; - const stream = new UndiciStreamWrapper(rawStream); - for await (const chunk of stream) { - data += new TextDecoder().decode(chunk); - } - - expect(data).toEqual("testtest"); - }); -}); diff --git a/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts deleted file mode 100644 index 8004e9ab..00000000 --- a/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { RUNTIME } from "../../../../src/core/runtime"; -import { Node18UniversalStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper"; -import { NodePre18StreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/NodePre18StreamWrapper"; -import { UndiciStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/UndiciStreamWrapper"; -import { chooseStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/chooseStreamWrapper"; - -describe("chooseStreamWrapper", () => { - beforeEach(() => { - RUNTIME.type = "unknown"; - RUNTIME.parsedVersion = 0; - }); - - it('should return a Node18UniversalStreamWrapper when RUNTIME.type is "node" and RUNTIME.parsedVersion is not null and RUNTIME.parsedVersion is greater than or equal to 18', async () => { - const expected = new Node18UniversalStreamWrapper(new ReadableStream()); - RUNTIME.type = "node"; - RUNTIME.parsedVersion = 18; - - const result = await chooseStreamWrapper(new ReadableStream()); - - expect(JSON.stringify(result)).toBe(JSON.stringify(expected)); - }); - - it('should return a NodePre18StreamWrapper when RUNTIME.type is "node" and RUNTIME.parsedVersion is not null and RUNTIME.parsedVersion is less than 18', async () => { - const stream = await import("readable-stream"); - const expected = new NodePre18StreamWrapper(new stream.Readable()); - - RUNTIME.type = "node"; - RUNTIME.parsedVersion = 16; - - const result = await chooseStreamWrapper(new stream.Readable()); - - expect(JSON.stringify(result)).toEqual(JSON.stringify(expected)); - }); - - it('should return a Undici when RUNTIME.type is not "node"', async () => { - const expected = new UndiciStreamWrapper(new ReadableStream()); - RUNTIME.type = "browser"; - - const result = await chooseStreamWrapper(new ReadableStream()); - - expect(JSON.stringify(result)).toEqual(JSON.stringify(expected)); - }); -}); diff --git a/tests/unit/fetcher/stream-wrappers/webpack.test.ts b/tests/unit/fetcher/stream-wrappers/webpack.test.ts deleted file mode 100644 index f7537d3c..00000000 --- a/tests/unit/fetcher/stream-wrappers/webpack.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import webpack from "webpack"; - -describe("test env compatibility", () => { - test("webpack", () => { - return new Promise((resolve, reject) => { - webpack( - { - mode: "production", - entry: "./src/index.ts", - module: { - rules: [ - { - test: /\.tsx?$/, - use: "ts-loader", - exclude: /node_modules/, - }, - ], - }, - resolve: { - extensions: [".tsx", ".ts", ".jsx", ".js"], - extensionAlias: { - ".js": [".ts", ".js"], - ".jsx": [".tsx", ".jsx"], - }, - }, - }, - (err, stats) => { - try { - expect(err).toBe(null); - if (stats?.hasErrors()) { - console.log(stats?.toString()); - } - expect(stats?.hasErrors()).toBe(false); - resolve(); - } catch (error) { - reject(error); - } - }, - ); - }); - }, 180_000); -}); diff --git a/tests/unit/logging/logger.test.ts b/tests/unit/logging/logger.test.ts new file mode 100644 index 00000000..2e0b5fe5 --- /dev/null +++ b/tests/unit/logging/logger.test.ts @@ -0,0 +1,454 @@ +import { ConsoleLogger, createLogger, Logger, LogLevel } from "../../../src/core/logging/logger"; + +function createMockLogger() { + return { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; +} + +describe("Logger", () => { + describe("LogLevel", () => { + it("should have correct log levels", () => { + expect(LogLevel.Debug).toBe("debug"); + expect(LogLevel.Info).toBe("info"); + expect(LogLevel.Warn).toBe("warn"); + expect(LogLevel.Error).toBe("error"); + }); + }); + + describe("ConsoleLogger", () => { + let consoleLogger: ConsoleLogger; + let consoleSpy: { + debug: ReturnType; + info: ReturnType; + warn: ReturnType; + error: ReturnType; + }; + + beforeEach(() => { + consoleLogger = new ConsoleLogger(); + consoleSpy = { + debug: vi.spyOn(console, "debug").mockImplementation(() => {}), + info: vi.spyOn(console, "info").mockImplementation(() => {}), + warn: vi.spyOn(console, "warn").mockImplementation(() => {}), + error: vi.spyOn(console, "error").mockImplementation(() => {}), + }; + }); + + afterEach(() => { + consoleSpy.debug.mockRestore(); + consoleSpy.info.mockRestore(); + consoleSpy.warn.mockRestore(); + consoleSpy.error.mockRestore(); + }); + + it("should log debug messages", () => { + consoleLogger.debug("debug message", { data: "test" }); + expect(consoleSpy.debug).toHaveBeenCalledWith("debug message", { data: "test" }); + }); + + it("should log info messages", () => { + consoleLogger.info("info message", { data: "test" }); + expect(consoleSpy.info).toHaveBeenCalledWith("info message", { data: "test" }); + }); + + it("should log warn messages", () => { + consoleLogger.warn("warn message", { data: "test" }); + expect(consoleSpy.warn).toHaveBeenCalledWith("warn message", { data: "test" }); + }); + + it("should log error messages", () => { + consoleLogger.error("error message", { data: "test" }); + expect(consoleSpy.error).toHaveBeenCalledWith("error message", { data: "test" }); + }); + + it("should handle multiple arguments", () => { + consoleLogger.debug("message", "arg1", "arg2", { key: "value" }); + expect(consoleSpy.debug).toHaveBeenCalledWith("message", "arg1", "arg2", { key: "value" }); + }); + }); + + describe("Logger with level filtering", () => { + let mockLogger: { + debug: ReturnType; + info: ReturnType; + warn: ReturnType; + error: ReturnType; + }; + + beforeEach(() => { + mockLogger = createMockLogger(); + }); + + describe("Debug level", () => { + it("should log all levels when set to debug", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + logger.debug("debug"); + logger.info("info"); + logger.warn("warn"); + logger.error("error"); + + expect(mockLogger.debug).toHaveBeenCalledWith("debug"); + expect(mockLogger.info).toHaveBeenCalledWith("info"); + expect(mockLogger.warn).toHaveBeenCalledWith("warn"); + expect(mockLogger.error).toHaveBeenCalledWith("error"); + }); + + it("should report correct level checks", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + expect(logger.isDebug()).toBe(true); + expect(logger.isInfo()).toBe(true); + expect(logger.isWarn()).toBe(true); + expect(logger.isError()).toBe(true); + }); + }); + + describe("Info level", () => { + it("should log info, warn, and error when set to info", () => { + const logger = new Logger({ + level: LogLevel.Info, + logger: mockLogger, + silent: false, + }); + + logger.debug("debug"); + logger.info("info"); + logger.warn("warn"); + logger.error("error"); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).toHaveBeenCalledWith("info"); + expect(mockLogger.warn).toHaveBeenCalledWith("warn"); + expect(mockLogger.error).toHaveBeenCalledWith("error"); + }); + + it("should report correct level checks", () => { + const logger = new Logger({ + level: LogLevel.Info, + logger: mockLogger, + silent: false, + }); + + expect(logger.isDebug()).toBe(false); + expect(logger.isInfo()).toBe(true); + expect(logger.isWarn()).toBe(true); + expect(logger.isError()).toBe(true); + }); + }); + + describe("Warn level", () => { + it("should log warn and error when set to warn", () => { + const logger = new Logger({ + level: LogLevel.Warn, + logger: mockLogger, + silent: false, + }); + + logger.debug("debug"); + logger.info("info"); + logger.warn("warn"); + logger.error("error"); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).not.toHaveBeenCalled(); + expect(mockLogger.warn).toHaveBeenCalledWith("warn"); + expect(mockLogger.error).toHaveBeenCalledWith("error"); + }); + + it("should report correct level checks", () => { + const logger = new Logger({ + level: LogLevel.Warn, + logger: mockLogger, + silent: false, + }); + + expect(logger.isDebug()).toBe(false); + expect(logger.isInfo()).toBe(false); + expect(logger.isWarn()).toBe(true); + expect(logger.isError()).toBe(true); + }); + }); + + describe("Error level", () => { + it("should only log error when set to error", () => { + const logger = new Logger({ + level: LogLevel.Error, + logger: mockLogger, + silent: false, + }); + + logger.debug("debug"); + logger.info("info"); + logger.warn("warn"); + logger.error("error"); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).not.toHaveBeenCalled(); + expect(mockLogger.warn).not.toHaveBeenCalled(); + expect(mockLogger.error).toHaveBeenCalledWith("error"); + }); + + it("should report correct level checks", () => { + const logger = new Logger({ + level: LogLevel.Error, + logger: mockLogger, + silent: false, + }); + + expect(logger.isDebug()).toBe(false); + expect(logger.isInfo()).toBe(false); + expect(logger.isWarn()).toBe(false); + expect(logger.isError()).toBe(true); + }); + }); + + describe("Silent mode", () => { + it("should not log anything when silent is true", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: true, + }); + + logger.debug("debug"); + logger.info("info"); + logger.warn("warn"); + logger.error("error"); + + expect(mockLogger.debug).not.toHaveBeenCalled(); + expect(mockLogger.info).not.toHaveBeenCalled(); + expect(mockLogger.warn).not.toHaveBeenCalled(); + expect(mockLogger.error).not.toHaveBeenCalled(); + }); + + it("should report all level checks as false when silent", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: true, + }); + + expect(logger.isDebug()).toBe(false); + expect(logger.isInfo()).toBe(false); + expect(logger.isWarn()).toBe(false); + expect(logger.isError()).toBe(false); + }); + }); + + describe("shouldLog", () => { + it("should correctly determine if level should be logged", () => { + const logger = new Logger({ + level: LogLevel.Info, + logger: mockLogger, + silent: false, + }); + + expect(logger.shouldLog(LogLevel.Debug)).toBe(false); + expect(logger.shouldLog(LogLevel.Info)).toBe(true); + expect(logger.shouldLog(LogLevel.Warn)).toBe(true); + expect(logger.shouldLog(LogLevel.Error)).toBe(true); + }); + + it("should return false for all levels when silent", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: true, + }); + + expect(logger.shouldLog(LogLevel.Debug)).toBe(false); + expect(logger.shouldLog(LogLevel.Info)).toBe(false); + expect(logger.shouldLog(LogLevel.Warn)).toBe(false); + expect(logger.shouldLog(LogLevel.Error)).toBe(false); + }); + }); + + describe("Multiple arguments", () => { + it("should pass multiple arguments to logger", () => { + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + logger.debug("message", "arg1", { key: "value" }, 123); + expect(mockLogger.debug).toHaveBeenCalledWith("message", "arg1", { key: "value" }, 123); + }); + }); + }); + + describe("createLogger", () => { + it("should return default logger when no config provided", () => { + const logger = createLogger(); + expect(logger).toBeInstanceOf(Logger); + }); + + it("should return same logger instance when Logger is passed", () => { + const customLogger = new Logger({ + level: LogLevel.Debug, + logger: new ConsoleLogger(), + silent: false, + }); + + const result = createLogger(customLogger); + expect(result).toBe(customLogger); + }); + + it("should create logger with custom config", () => { + const mockLogger = createMockLogger(); + + const logger = createLogger({ + level: LogLevel.Warn, + logger: mockLogger, + silent: false, + }); + + expect(logger).toBeInstanceOf(Logger); + logger.warn("test"); + expect(mockLogger.warn).toHaveBeenCalledWith("test"); + }); + + it("should use default values for missing config", () => { + const logger = createLogger({}); + expect(logger).toBeInstanceOf(Logger); + }); + + it("should override default level", () => { + const mockLogger = createMockLogger(); + + const logger = createLogger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + logger.debug("test"); + expect(mockLogger.debug).toHaveBeenCalledWith("test"); + }); + + it("should override default silent mode", () => { + const mockLogger = createMockLogger(); + + const logger = createLogger({ + logger: mockLogger, + silent: false, + }); + + logger.info("test"); + expect(mockLogger.info).toHaveBeenCalledWith("test"); + }); + + it("should use provided logger implementation", () => { + const customLogger = createMockLogger(); + + const logger = createLogger({ + logger: customLogger, + level: LogLevel.Debug, + silent: false, + }); + + logger.debug("test"); + expect(customLogger.debug).toHaveBeenCalledWith("test"); + }); + + it("should default to silent: true", () => { + const mockLogger = createMockLogger(); + + const logger = createLogger({ + logger: mockLogger, + level: LogLevel.Debug, + }); + + logger.debug("test"); + expect(mockLogger.debug).not.toHaveBeenCalled(); + }); + }); + + describe("Default logger", () => { + it("should have silent: true by default", () => { + const logger = createLogger(); + expect(logger.shouldLog(LogLevel.Info)).toBe(false); + }); + + it("should not log when using default logger", () => { + const logger = createLogger(); + + logger.info("test"); + expect(logger.isInfo()).toBe(false); + }); + }); + + describe("Edge cases", () => { + it("should handle empty message", () => { + const mockLogger = createMockLogger(); + + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + logger.debug(""); + expect(mockLogger.debug).toHaveBeenCalledWith(""); + }); + + it("should handle no arguments", () => { + const mockLogger = createMockLogger(); + + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + logger.debug("message"); + expect(mockLogger.debug).toHaveBeenCalledWith("message"); + }); + + it("should handle complex objects", () => { + const mockLogger = createMockLogger(); + + const logger = new Logger({ + level: LogLevel.Debug, + logger: mockLogger, + silent: false, + }); + + const complexObject = { + nested: { key: "value" }, + array: [1, 2, 3], + fn: () => "test", + }; + + logger.debug("message", complexObject); + expect(mockLogger.debug).toHaveBeenCalledWith("message", complexObject); + }); + + it("should handle errors as arguments", () => { + const mockLogger = createMockLogger(); + + const logger = new Logger({ + level: LogLevel.Error, + logger: mockLogger, + silent: false, + }); + + const error = new Error("Test error"); + logger.error("Error occurred", error); + expect(mockLogger.error).toHaveBeenCalledWith("Error occurred", error); + }); + }); +}); diff --git a/tests/unit/url/join.test.ts b/tests/unit/url/join.test.ts new file mode 100644 index 00000000..123488f0 --- /dev/null +++ b/tests/unit/url/join.test.ts @@ -0,0 +1,284 @@ +import { join } from "../../../src/core/url/index"; + +describe("join", () => { + interface TestCase { + description: string; + base: string; + segments: string[]; + expected: string; + } + + describe("basic functionality", () => { + const basicTests: TestCase[] = [ + { description: "should return empty string for empty base", base: "", segments: [], expected: "" }, + { + description: "should return empty string for empty base with path", + base: "", + segments: ["path"], + expected: "", + }, + { + description: "should handle single segment", + base: "base", + segments: ["segment"], + expected: "base/segment", + }, + { + description: "should handle single segment with trailing slash on base", + base: "base/", + segments: ["segment"], + expected: "base/segment", + }, + { + description: "should handle single segment with leading slash", + base: "base", + segments: ["/segment"], + expected: "base/segment", + }, + { + description: "should handle single segment with both slashes", + base: "base/", + segments: ["/segment"], + expected: "base/segment", + }, + { + description: "should handle multiple segments", + base: "base", + segments: ["path1", "path2", "path3"], + expected: "base/path1/path2/path3", + }, + { + description: "should handle multiple segments with slashes", + base: "base/", + segments: ["/path1/", "/path2/", "/path3/"], + expected: "base/path1/path2/path3/", + }, + ]; + + basicTests.forEach(({ description, base, segments, expected }) => { + it(description, () => { + expect(join(base, ...segments)).toBe(expected); + }); + }); + }); + + describe("URL handling", () => { + const urlTests: TestCase[] = [ + { + description: "should handle absolute URLs", + base: "https://example.com", + segments: ["api", "v1"], + expected: "https://example.com/api/v1", + }, + { + description: "should handle absolute URLs with slashes", + base: "https://example.com/", + segments: ["/api/", "/v1/"], + expected: "https://example.com/api/v1/", + }, + { + description: "should handle absolute URLs with base path", + base: "https://example.com/base", + segments: ["api", "v1"], + expected: "https://example.com/base/api/v1", + }, + { + description: "should preserve URL query parameters", + base: "https://example.com?query=1", + segments: ["api"], + expected: "https://example.com/api?query=1", + }, + { + description: "should preserve URL fragments", + base: "https://example.com#fragment", + segments: ["api"], + expected: "https://example.com/api#fragment", + }, + { + description: "should preserve URL query and fragments", + base: "https://example.com?query=1#fragment", + segments: ["api"], + expected: "https://example.com/api?query=1#fragment", + }, + { + description: "should handle http protocol", + base: "http://example.com", + segments: ["api"], + expected: "http://example.com/api", + }, + { + description: "should handle ftp protocol", + base: "ftp://example.com", + segments: ["files"], + expected: "ftp://example.com/files", + }, + { + description: "should handle ws protocol", + base: "ws://example.com", + segments: ["socket"], + expected: "ws://example.com/socket", + }, + { + description: "should fallback to path joining for malformed URLs", + base: "not-a-url://", + segments: ["path"], + expected: "not-a-url:///path", + }, + ]; + + urlTests.forEach(({ description, base, segments, expected }) => { + it(description, () => { + expect(join(base, ...segments)).toBe(expected); + }); + }); + }); + + describe("edge cases", () => { + const edgeCaseTests: TestCase[] = [ + { + description: "should handle empty segments", + base: "base", + segments: ["", "path"], + expected: "base/path", + }, + { + description: "should handle null segments", + base: "base", + segments: [null as any, "path"], + expected: "base/path", + }, + { + description: "should handle undefined segments", + base: "base", + segments: [undefined as any, "path"], + expected: "base/path", + }, + { + description: "should handle segments with only single slash", + base: "base", + segments: ["/", "path"], + expected: "base/path", + }, + { + description: "should handle segments with only double slash", + base: "base", + segments: ["//", "path"], + expected: "base/path", + }, + { + description: "should handle base paths with trailing slashes", + base: "base/", + segments: ["path"], + expected: "base/path", + }, + { + description: "should handle complex nested paths", + base: "api/v1/", + segments: ["/users/", "/123/", "/profile"], + expected: "api/v1/users/123/profile", + }, + ]; + + edgeCaseTests.forEach(({ description, base, segments, expected }) => { + it(description, () => { + expect(join(base, ...segments)).toBe(expected); + }); + }); + }); + + describe("real-world scenarios", () => { + const realWorldTests: TestCase[] = [ + { + description: "should handle API endpoint construction", + base: "https://api.example.com/v1", + segments: ["users", "123", "posts"], + expected: "https://api.example.com/v1/users/123/posts", + }, + { + description: "should handle file path construction", + base: "/var/www", + segments: ["html", "assets", "images"], + expected: "/var/www/html/assets/images", + }, + { + description: "should handle relative path construction", + base: "../parent", + segments: ["child", "grandchild"], + expected: "../parent/child/grandchild", + }, + { + description: "should handle Windows-style paths", + base: "C:\\Users", + segments: ["Documents", "file.txt"], + expected: "C:\\Users/Documents/file.txt", + }, + ]; + + realWorldTests.forEach(({ description, base, segments, expected }) => { + it(description, () => { + expect(join(base, ...segments)).toBe(expected); + }); + }); + }); + + describe("performance scenarios", () => { + it("should handle many segments efficiently", () => { + const segments = Array(100).fill("segment"); + const result = join("base", ...segments); + expect(result).toBe(`base/${segments.join("/")}`); + }); + + it("should handle long URLs", () => { + const longPath = "a".repeat(1000); + expect(join("https://example.com", longPath)).toBe(`https://example.com/${longPath}`); + }); + }); + + describe("trailing slash preservation", () => { + const trailingSlashTests: TestCase[] = [ + { + description: + "should preserve trailing slash on final result when base has trailing slash and no segments", + base: "https://api.example.com/", + segments: [], + expected: "https://api.example.com/", + }, + { + description: "should preserve trailing slash on v1 path", + base: "https://api.example.com/v1/", + segments: [], + expected: "https://api.example.com/v1/", + }, + { + description: "should preserve trailing slash when last segment has trailing slash", + base: "https://api.example.com", + segments: ["users/"], + expected: "https://api.example.com/users/", + }, + { + description: "should preserve trailing slash with relative path", + base: "api/v1", + segments: ["users/"], + expected: "api/v1/users/", + }, + { + description: "should preserve trailing slash with multiple segments", + base: "https://api.example.com", + segments: ["v1", "collections/"], + expected: "https://api.example.com/v1/collections/", + }, + { + description: "should preserve trailing slash with base path", + base: "base", + segments: ["path1", "path2/"], + expected: "base/path1/path2/", + }, + ]; + + trailingSlashTests.forEach(({ description, base, segments, expected }) => { + it(description, () => { + expect(join(base, ...segments)).toBe(expected); + }); + }); + }); +}); diff --git a/tests/unit/url/qs.test.ts b/tests/unit/url/qs.test.ts new file mode 100644 index 00000000..42cdffb9 --- /dev/null +++ b/tests/unit/url/qs.test.ts @@ -0,0 +1,278 @@ +import { toQueryString } from "../../../src/core/url/index"; + +describe("Test qs toQueryString", () => { + interface BasicTestCase { + description: string; + input: any; + expected: string; + } + + describe("Basic functionality", () => { + const basicTests: BasicTestCase[] = [ + { description: "should return empty string for null", input: null, expected: "" }, + { description: "should return empty string for undefined", input: undefined, expected: "" }, + { description: "should return empty string for string primitive", input: "hello", expected: "" }, + { description: "should return empty string for number primitive", input: 42, expected: "" }, + { description: "should return empty string for true boolean", input: true, expected: "" }, + { description: "should return empty string for false boolean", input: false, expected: "" }, + { description: "should handle empty objects", input: {}, expected: "" }, + { + description: "should handle simple key-value pairs", + input: { name: "John", age: 30 }, + expected: "name=John&age=30", + }, + ]; + + basicTests.forEach(({ description, input, expected }) => { + it(description, () => { + expect(toQueryString(input)).toBe(expected); + }); + }); + }); + + describe("Array handling", () => { + interface ArrayTestCase { + description: string; + input: any; + options?: { arrayFormat?: "repeat" | "indices" }; + expected: string; + } + + const arrayTests: ArrayTestCase[] = [ + { + description: "should handle arrays with indices format (default)", + input: { items: ["a", "b", "c"] }, + expected: "items%5B0%5D=a&items%5B1%5D=b&items%5B2%5D=c", + }, + { + description: "should handle arrays with repeat format", + input: { items: ["a", "b", "c"] }, + options: { arrayFormat: "repeat" }, + expected: "items=a&items=b&items=c", + }, + { + description: "should handle empty arrays", + input: { items: [] }, + expected: "", + }, + { + description: "should handle arrays with mixed types", + input: { mixed: ["string", 42, true, false] }, + expected: "mixed%5B0%5D=string&mixed%5B1%5D=42&mixed%5B2%5D=true&mixed%5B3%5D=false", + }, + { + description: "should handle arrays with objects", + input: { users: [{ name: "John" }, { name: "Jane" }] }, + expected: "users%5B0%5D%5Bname%5D=John&users%5B1%5D%5Bname%5D=Jane", + }, + { + description: "should handle arrays with objects in repeat format", + input: { users: [{ name: "John" }, { name: "Jane" }] }, + options: { arrayFormat: "repeat" }, + expected: "users%5Bname%5D=John&users%5Bname%5D=Jane", + }, + ]; + + arrayTests.forEach(({ description, input, options, expected }) => { + it(description, () => { + expect(toQueryString(input, options)).toBe(expected); + }); + }); + }); + + describe("Nested objects", () => { + const nestedTests: BasicTestCase[] = [ + { + description: "should handle nested objects", + input: { user: { name: "John", age: 30 } }, + expected: "user%5Bname%5D=John&user%5Bage%5D=30", + }, + { + description: "should handle deeply nested objects", + input: { user: { profile: { name: "John", settings: { theme: "dark" } } } }, + expected: "user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark", + }, + { + description: "should handle empty nested objects", + input: { user: {} }, + expected: "", + }, + ]; + + nestedTests.forEach(({ description, input, expected }) => { + it(description, () => { + expect(toQueryString(input)).toBe(expected); + }); + }); + }); + + describe("Encoding", () => { + interface EncodingTestCase { + description: string; + input: any; + options?: { encode?: boolean }; + expected: string; + } + + const encodingTests: EncodingTestCase[] = [ + { + description: "should encode by default", + input: { name: "John Doe", email: "john@example.com" }, + expected: "name=John%20Doe&email=john%40example.com", + }, + { + description: "should not encode when encode is false", + input: { name: "John Doe", email: "john@example.com" }, + options: { encode: false }, + expected: "name=John Doe&email=john@example.com", + }, + { + description: "should encode special characters in keys", + input: { "user name": "John", "email[primary]": "john@example.com" }, + expected: "user%20name=John&email%5Bprimary%5D=john%40example.com", + }, + { + description: "should not encode special characters in keys when encode is false", + input: { "user name": "John", "email[primary]": "john@example.com" }, + options: { encode: false }, + expected: "user name=John&email[primary]=john@example.com", + }, + ]; + + encodingTests.forEach(({ description, input, options, expected }) => { + it(description, () => { + expect(toQueryString(input, options)).toBe(expected); + }); + }); + }); + + describe("Mixed scenarios", () => { + interface MixedTestCase { + description: string; + input: any; + options?: { arrayFormat?: "repeat" | "indices" }; + expected: string; + } + + const mixedTests: MixedTestCase[] = [ + { + description: "should handle complex nested structures", + input: { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }, + expected: + "filters%5Bstatus%5D%5B0%5D=active&filters%5Bstatus%5D%5B1%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D%5B0%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D%5B1%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + }, + { + description: "should handle complex nested structures with repeat format", + input: { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }, + options: { arrayFormat: "repeat" }, + expected: + "filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + }, + { + description: "should handle arrays with null/undefined values", + input: { items: ["a", null, "c", undefined, "e"] }, + expected: "items%5B0%5D=a&items%5B1%5D=&items%5B2%5D=c&items%5B4%5D=e", + }, + { + description: "should handle objects with null/undefined values", + input: { name: "John", age: null, email: undefined, active: true }, + expected: "name=John&age=&active=true", + }, + ]; + + mixedTests.forEach(({ description, input, options, expected }) => { + it(description, () => { + expect(toQueryString(input, options)).toBe(expected); + }); + }); + }); + + describe("Edge cases", () => { + const edgeCaseTests: BasicTestCase[] = [ + { + description: "should handle numeric keys", + input: { "0": "zero", "1": "one" }, + expected: "0=zero&1=one", + }, + { + description: "should handle boolean values in objects", + input: { enabled: true, disabled: false }, + expected: "enabled=true&disabled=false", + }, + { + description: "should handle empty strings", + input: { name: "", description: "test" }, + expected: "name=&description=test", + }, + { + description: "should handle zero values", + input: { count: 0, price: 0.0 }, + expected: "count=0&price=0", + }, + { + description: "should handle arrays with empty strings", + input: { items: ["a", "", "c"] }, + expected: "items%5B0%5D=a&items%5B1%5D=&items%5B2%5D=c", + }, + ]; + + edgeCaseTests.forEach(({ description, input, expected }) => { + it(description, () => { + expect(toQueryString(input)).toBe(expected); + }); + }); + }); + + describe("Options combinations", () => { + interface OptionsTestCase { + description: string; + input: any; + options?: { arrayFormat?: "repeat" | "indices"; encode?: boolean }; + expected: string; + } + + const optionsTests: OptionsTestCase[] = [ + { + description: "should respect both arrayFormat and encode options", + input: { items: ["a & b", "c & d"] }, + options: { arrayFormat: "repeat", encode: false }, + expected: "items=a & b&items=c & d", + }, + { + description: "should use default options when none provided", + input: { items: ["a", "b"] }, + expected: "items%5B0%5D=a&items%5B1%5D=b", + }, + { + description: "should merge provided options with defaults", + input: { items: ["a", "b"], name: "John Doe" }, + options: { encode: false }, + expected: "items[0]=a&items[1]=b&name=John Doe", + }, + ]; + + optionsTests.forEach(({ description, input, options, expected }) => { + it(description, () => { + expect(toQueryString(input, options)).toBe(expected); + }); + }); + }); +}); diff --git a/tests/unit/utils/setObjectProperty.test.ts b/tests/unit/utils/setObjectProperty.test.ts new file mode 100644 index 00000000..29f8e638 --- /dev/null +++ b/tests/unit/utils/setObjectProperty.test.ts @@ -0,0 +1,76 @@ +import { setObjectProperty } from "../../../src/core/utils/setObjectProperty"; + +interface TestCase { + description: string; + giveObject: object; + givePath: string; + giveValue: any; + wantObject: object; +} + +describe("Test setObjectProperty", () => { + const testCases: TestCase[] = [ + { + description: "empty", + giveObject: {}, + givePath: "", + giveValue: 0, + wantObject: { "": 0 }, + }, + { + description: "top-level primitive", + giveObject: {}, + givePath: "age", + giveValue: 42, + wantObject: { age: 42 }, + }, + { + description: "top-level object", + giveObject: {}, + givePath: "name", + giveValue: { first: "John", last: "Doe" }, + wantObject: { name: { first: "John", last: "Doe" } }, + }, + { + description: "top-level array", + giveObject: {}, + givePath: "values", + giveValue: [1, 2, 3], + wantObject: { values: [1, 2, 3] }, + }, + { + description: "nested object property", + giveObject: { + name: { + first: "John", + }, + }, + givePath: "name.last", + giveValue: "Doe", + wantObject: { name: { first: "John", last: "Doe" } }, + }, + { + description: "deeply nested object property", + giveObject: { + info: { + address: { + street: "123 Main St.", + }, + age: 42, + name: { + last: "Doe", + }, + }, + }, + givePath: "info.name.first", + giveValue: "John", + wantObject: { + info: { age: 42, address: { street: "123 Main St." }, name: { first: "John", last: "Doe" } }, + }, + }, + ]; + test.each(testCases)("$description", ({ giveObject, givePath, giveValue, wantObject }) => { + const result = setObjectProperty(giveObject, givePath, giveValue); + expect(result).toEqual(wantObject); + }); +}); diff --git a/tests/wire/.gitkeep b/tests/wire/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/wire/admins.test.ts b/tests/wire/admins.test.ts new file mode 100644 index 00000000..0f4be795 --- /dev/null +++ b/tests/wire/admins.test.ts @@ -0,0 +1,686 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("AdminsClient", () => { + test("identify", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin", + id: "991267459", + name: "Ciaran1 Lee", + email: "admin1@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/assets/default-avatars/admins/128.png", + }, + email_verified: true, + app: { + type: "app", + id_code: "this_is_an_id1_that_should_be_at_least_40", + name: "MyApp 1", + region: "US", + timezone: "America/Los_Angeles", + created_at: 1734537243, + identity_verification: false, + }, + }; + server.mockEndpoint().get("/me").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.admins.identify(); + expect(response).toEqual({ + type: "admin", + id: "991267459", + name: "Ciaran1 Lee", + email: "admin1@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/assets/default-avatars/admins/128.png", + }, + email_verified: true, + app: { + type: "app", + id_code: "this_is_an_id1_that_should_be_at_least_40", + name: "MyApp 1", + region: "US", + timezone: "America/Los_Angeles", + created_at: 1734537243, + identity_verification: false, + }, + }); + }); + + test("away (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true, away_status_reason_id: 12345 }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("away (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("away (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("away (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("away (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("away (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.admins.away({ + admin_id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAllActivityLogs (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "activity_log.list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 1, + }, + activity_logs: [ + { + id: "fca05814-4b72-4dce-ad4f-77a786a2c136", + performed_by: { type: "admin", id: "991267464", email: "admin5@email.com", ip: "127.0.0.1" }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "😌 On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + team_assignment_limit: 50, + enabled: true, + consent_id: 149673, + expired_at: "2025-12-04T09:31:57Z", + before: { key: "value" }, + after: { key: "value" }, + }, + created_at: 1734537253, + activity_type: "app_name_change", + activity_description: "Ciaran5 Lee changed your app name from before to after.", + }, + { + id: "f48c653b-0185-48ac-a276-23d11006bafb", + performed_by: { type: "admin", id: "991267464", email: "admin5@email.com", ip: "127.0.0.1" }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "😌 On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + team_assignment_limit: 50, + enabled: true, + consent_id: 149673, + expired_at: "2025-12-04T09:31:57Z", + before: { key: "value" }, + after: { key: "value" }, + }, + created_at: 1734537253, + activity_type: "message_state_change", + activity_description: + "Ciaran5 Lee changed your Initial message title message from Initial message title to Eventual message title.", + }, + ], + }; + server + .mockEndpoint() + .get("/admins/activity_logs") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.admins.listAllActivityLogs({ + created_at_after: "1677253093", + created_at_before: "1677861493", + }); + expect(response).toEqual({ + type: "activity_log.list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 1, + }, + activity_logs: [ + { + id: "fca05814-4b72-4dce-ad4f-77a786a2c136", + performed_by: { + type: "admin", + id: "991267464", + email: "admin5@email.com", + ip: "127.0.0.1", + }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "\uD83D\uDE0C On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + team_assignment_limit: 50, + enabled: true, + consent_id: 149673, + expired_at: "2025-12-04T09:31:57Z", + before: { + key: "value", + }, + after: { + key: "value", + }, + }, + created_at: 1734537253, + activity_type: "app_name_change", + activity_description: "Ciaran5 Lee changed your app name from before to after.", + }, + { + id: "f48c653b-0185-48ac-a276-23d11006bafb", + performed_by: { + type: "admin", + id: "991267464", + email: "admin5@email.com", + ip: "127.0.0.1", + }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "\uD83D\uDE0C On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + team_assignment_limit: 50, + enabled: true, + consent_id: 149673, + expired_at: "2025-12-04T09:31:57Z", + before: { + key: "value", + }, + after: { + key: "value", + }, + }, + created_at: 1734537253, + activity_type: "message_state_change", + activity_description: + "Ciaran5 Lee changed your Initial message title message from Initial message title to Eventual message title.", + }, + ], + }); + }); + + test("listAllActivityLogs (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/admins/activity_logs") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.admins.listAllActivityLogs({ + created_at_after: "created_at_after", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin.list", + admins: [ + { + type: "admin", + id: "991267466", + name: "Ciaran7 Lee", + email: "admin7@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + ], + }; + server.mockEndpoint().get("/admins").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.admins.list(); + expect(response).toEqual({ + type: "admin.list", + admins: [ + { + type: "admin", + id: "991267466", + name: "Ciaran7 Lee", + email: "admin7@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/admins").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.admins.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin", + id: "991267468", + name: "Ciaran9 Lee", + email: "admin9@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.admins.find({ + admin_id: 1, + }); + expect(response).toEqual({ + type: "admin", + id: "991267468", + name: "Ciaran9 Lee", + email: "admin9@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.admins.find({ + admin_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.admins.find({ + admin_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/aiContent.test.ts b/tests/wire/aiContent.test.ts new file mode 100644 index 00000000..fad0e33d --- /dev/null +++ b/tests/wire/aiContent.test.ts @@ -0,0 +1,878 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("AiContentClient", () => { + test("listContentImportSources (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + total_count: 3, + data: [ + { + type: "content_import_source", + id: 33, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/1", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 34, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/2", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 35, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/3", + created_at: 1734537259, + updated_at: 1734537259, + }, + ], + }; + server + .mockEndpoint() + .get("/ai/content_import_sources") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.listContentImportSources(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + total_count: 3, + data: [ + { + type: "content_import_source", + id: 33, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/1", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 34, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/2", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 35, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/3", + created_at: 1734537259, + updated_at: 1734537259, + }, + ], + }); + }); + + test("listContentImportSources (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/content_import_sources") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.listContentImportSources(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("createContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "https://www.example.com" }; + const rawResponseBody = { + type: "content_import_source", + id: 36, + last_synced_at: 1734537261, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537261, + updated_at: 1734537261, + }; + server + .mockEndpoint() + .post("/ai/content_import_sources") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.createContentImportSource({ + url: "https://www.example.com", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 36, + last_synced_at: 1734537261, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537261, + updated_at: 1734537261, + }); + }); + + test("createContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "url" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ai/content_import_sources") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.createContentImportSource({ + url: "url", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("getContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "content_import_source", + id: 38, + last_synced_at: 1734537265, + sync_behavior: "api", + status: "active", + url: "https://support.example.com/us/5", + created_at: 1734537265, + updated_at: 1734537265, + }; + server + .mockEndpoint() + .get("/ai/content_import_sources/source_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.getContentImportSource({ + source_id: "source_id", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 38, + last_synced_at: 1734537265, + sync_behavior: "api", + status: "active", + url: "https://support.example.com/us/5", + created_at: 1734537265, + updated_at: 1734537265, + }); + }); + + test("getContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/content_import_sources/source_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.getContentImportSource({ + source_id: "source_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("updateContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "https://www.example.com" }; + const rawResponseBody = { + type: "content_import_source", + id: 39, + last_synced_at: 1734537267, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537267, + updated_at: 1734537267, + }; + server + .mockEndpoint() + .put("/ai/content_import_sources/source_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.updateContentImportSource({ + source_id: "source_id", + sync_behavior: "api", + url: "https://www.example.com", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 39, + last_synced_at: 1734537267, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537267, + updated_at: 1734537267, + }); + }); + + test("updateContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "url" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ai/content_import_sources/source_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.updateContentImportSource({ + source_id: "source_id", + sync_behavior: "api", + url: "url", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().delete("/ai/content_import_sources/source_id").respondWith().statusCode(200).build(); + + const response = await client.aiContent.deleteContentImportSource({ + source_id: "source_id", + }); + expect(response).toEqual(undefined); + }); + + test("deleteContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/ai/content_import_sources/source_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.deleteContentImportSource({ + source_id: "source_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listExternalPages (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + total_count: 3, + data: [ + { + type: "external_page", + id: "19", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/3", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 42, + external_id: "3", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "18", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/2", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 41, + external_id: "2", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "17", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/1", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 40, + external_id: "1", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + ], + }; + server.mockEndpoint().get("/ai/external_pages").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.aiContent.listExternalPages(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + total_count: 3, + data: [ + { + type: "external_page", + id: "19", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/3", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 42, + external_id: "3", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "18", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/2", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 41, + external_id: "2", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "17", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/1", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 40, + external_id: "1", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + ], + }); + }); + + test("listExternalPages (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ai/external_pages").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.aiContent.listExternalPages(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("createExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Test", + html: "

Test

", + url: "https://www.example.com", + locale: "en", + source_id: 44, + external_id: "abc1234", + }; + const rawResponseBody = { + type: "external_page", + id: "21", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 44, + external_id: "abc1234", + created_at: 1734537273, + updated_at: 1734537274, + last_ingested_at: 1734537274, + }; + server + .mockEndpoint() + .post("/ai/external_pages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.createExternalPage({ + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 44, + external_id: "abc1234", + }); + expect(response).toEqual({ + type: "external_page", + id: "21", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 44, + external_id: "abc1234", + created_at: 1734537273, + updated_at: 1734537274, + last_ingested_at: 1734537274, + }); + }); + + test("createExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", html: "html", locale: "en", source_id: 1, external_id: "external_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ai/external_pages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.createExternalPage({ + title: "title", + html: "html", + source_id: 1, + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("getExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "external_page", + id: "23", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/6", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 46, + external_id: "5", + created_at: 1734537278, + updated_at: 1734537278, + last_ingested_at: 1734537278, + }; + server + .mockEndpoint() + .get("/ai/external_pages/page_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.getExternalPage({ + page_id: "page_id", + }); + expect(response).toEqual({ + type: "external_page", + id: "23", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/6", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 46, + external_id: "5", + created_at: 1734537278, + updated_at: 1734537278, + last_ingested_at: 1734537278, + }); + }); + + test("getExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/external_pages/page_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.getExternalPage({ + page_id: "page_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("updateExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Test", + html: "

Test

", + url: "https://www.example.com", + locale: "en", + source_id: 47, + external_id: "5678", + }; + const rawResponseBody = { + type: "external_page", + id: "24", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 47, + external_id: "5678", + created_at: 1734537280, + updated_at: 1734537281, + last_ingested_at: 1734537281, + }; + server + .mockEndpoint() + .put("/ai/external_pages/page_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.updateExternalPage({ + page_id: "page_id", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 47, + external_id: "5678", + }); + expect(response).toEqual({ + type: "external_page", + id: "24", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 47, + external_id: "5678", + created_at: 1734537280, + updated_at: 1734537281, + last_ingested_at: 1734537281, + }); + }); + + test("updateExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", html: "html", url: "url", locale: "en", source_id: 1 }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ai/external_pages/page_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.updateExternalPage({ + page_id: "page_id", + title: "title", + html: "html", + url: "url", + source_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "external_page", + id: "22", + title: "My External Content", + html: "", + url: "https://support.example.com/us/5", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 45, + external_id: "4", + created_at: 1734537276, + updated_at: 1734537276, + last_ingested_at: 1734537276, + }; + server + .mockEndpoint() + .delete("/ai/external_pages/page_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.aiContent.deleteExternalPage({ + page_id: "page_id", + }); + expect(response).toEqual({ + type: "external_page", + id: "22", + title: "My External Content", + html: "", + url: "https://support.example.com/us/5", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 45, + external_id: "4", + created_at: 1734537276, + updated_at: 1734537276, + last_ingested_at: 1734537276, + }); + }); + + test("deleteExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/ai/external_pages/page_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.aiContent.deleteExternalPage({ + page_id: "page_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/articles.test.ts b/tests/wire/articles.test.ts new file mode 100644 index 00000000..35387d31 --- /dev/null +++ b/tests/wire/articles.test.ts @@ -0,0 +1,6584 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("ArticlesClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { key: "value" }, + total_count: 1, + data: [ + { + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }, + { + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }, + ], + }; + server + .mockEndpoint({ once: false }) + .get("/articles") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + pages: { + key: "value", + }, + total_count: 1, + data: [ + { + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }, + { + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }, + ], + }; + const page = await client.articles.list(); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/articles") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.articles.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + description: "Description of the Article", + body: "Body of the Article", + author_id: 991267497, + state: "published", + parent_id: 145, + parent_type: "collection", + translated_content: { + fr: { + title: "Merci pour tout", + description: "Description de l'article", + body: "Corps de l'article", + author_id: 991267497, + state: "published", + }, + }, + }; + const rawResponseBody = { + type: "article", + id: "42", + workspace_id: "this_is_an_id68_that_should_be_at_least_4", + title: "Thanks for everything", + description: "Description of the Article", + body: '

Body of the Article

', + author_id: 991267497, + state: "published", + created_at: 1734537288, + updated_at: 1734537288, + url: "http://help-center.test/myapp-68/en/articles/42-thanks-for-everything", + parent_id: 145, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server + .mockEndpoint() + .post("/articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.articles.create({ + title: "Thanks for everything", + description: "Description of the Article", + body: "Body of the Article", + author_id: 991267497, + state: "published", + parent_id: 145, + parent_type: "collection", + translated_content: { + fr: { + title: "Merci pour tout", + description: "Description de l'article", + body: "Corps de l'article", + author_id: 991267497, + state: "published", + }, + }, + }); + expect(response).toEqual({ + type: "article", + id: "42", + workspace_id: "this_is_an_id68_that_should_be_at_least_4", + title: "Thanks for everything", + description: "Description of the Article", + body: '

Body of the Article

', + author_id: 991267497, + state: "published", + created_at: 1734537288, + updated_at: 1734537288, + url: "http://help-center.test/myapp-68/en/articles/42-thanks-for-everything", + parent_id: 145, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + description: "Description of the Article", + body: "Body of the Article", + author_id: 1295, + state: "published", + }; + const rawResponseBody = { + type: "article", + id: "42", + workspace_id: "this_is_an_id68_that_should_be_at_least_4", + title: "Thanks for everything", + description: "Description of the Article", + body: '

Body of the Article

', + author_id: 991267497, + state: "published", + created_at: 1734537288, + updated_at: 1734537288, + url: "http://help-center.test/myapp-68/en/articles/42-thanks-for-everything", + parent_id: 145, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server + .mockEndpoint() + .post("/articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.articles.create({ + title: "Thanks for everything", + description: "Description of the Article", + body: "Body of the Article", + author_id: 1295, + state: "published", + }); + expect(response).toEqual({ + type: "article", + id: "42", + workspace_id: "this_is_an_id68_that_should_be_at_least_4", + title: "Thanks for everything", + description: "Description of the Article", + body: '

Body of the Article

', + author_id: 991267497, + state: "published", + created_at: 1734537288, + updated_at: 1734537288, + url: "http://help-center.test/myapp-68/en/articles/42-thanks-for-everything", + parent_id: 145, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/articles").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.create(undefined); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/articles").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.create(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "article", + id: "45", + workspace_id: "this_is_an_id74_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267502, + state: "published", + created_at: 1734537292, + updated_at: 1734537292, + url: "http://help-center.test/myapp-74/en/articles/45-this-is-the-article-title", + parent_id: 148, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.articles.find({ + article_id: 1, + }); + expect(response).toEqual({ + type: "article", + id: "45", + workspace_id: "this_is_an_id74_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267502, + state: "published", + created_at: 1734537292, + updated_at: 1734537292, + url: "http://help-center.test/myapp-74/en/articles/45-this-is-the-article-title", + parent_id: 148, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.find({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.find({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "article", + id: "48", + workspace_id: "this_is_an_id80_that_should_be_at_least_4", + title: "Christmas is here!", + description: "", + body: '

New gifts in store for the jolly season

', + author_id: 991267508, + state: "published", + created_at: 1734537297, + updated_at: 1734537298, + url: "http://help-center.test/myapp-80/en/articles/48-christmas-is-here", + parent_id: 151, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server + .mockEndpoint() + .put("/articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.articles.update({ + article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "article", + id: "48", + workspace_id: "this_is_an_id80_that_should_be_at_least_4", + title: "Christmas is here!", + description: "", + body: '

New gifts in store for the jolly season

', + author_id: 991267508, + state: "published", + created_at: 1734537297, + updated_at: 1734537298, + url: "http://help-center.test/myapp-80/en/articles/48-christmas-is-here", + parent_id: 151, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "article", + id: "48", + workspace_id: "this_is_an_id80_that_should_be_at_least_4", + title: "Christmas is here!", + description: "", + body: '

New gifts in store for the jolly season

', + author_id: 991267508, + state: "published", + created_at: 1734537297, + updated_at: 1734537298, + url: "http://help-center.test/myapp-80/en/articles/48-christmas-is-here", + parent_id: 151, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server + .mockEndpoint() + .put("/articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.articles.update({ + article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "article", + id: "48", + workspace_id: "this_is_an_id80_that_should_be_at_least_4", + title: "Christmas is here!", + description: "", + body: '

New gifts in store for the jolly season

', + author_id: 991267508, + state: "published", + created_at: 1734537297, + updated_at: 1734537298, + url: "http://help-center.test/myapp-80/en/articles/48-christmas-is-here", + parent_id: 151, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.articles.update({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.articles.update({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "51", object: "article", deleted: true }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.articles.delete({ + article_id: 1, + }); + expect(response).toEqual({ + id: "51", + object: "article", + deleted: true, + }); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.delete({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.delete({ + article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("search (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + total_count: 1, + data: { + articles: [ + { + type: "article", + id: "55", + workspace_id: "this_is_an_id92_that_should_be_at_least_4", + title: "Title 1", + description: "", + body: "", + author_id: 991267521, + state: "draft", + created_at: 1734537306, + updated_at: 1734537306, + url: "http://intercom.test/help/en/articles/3-default-language", + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + highlights: [{ article_id: "123" }], + }, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + }; + server.mockEndpoint().get("/articles/search").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.articles.search({ + phrase: "Getting started", + state: "published", + help_center_id: 1, + highlight: true, + }); + expect(response).toEqual({ + type: "list", + total_count: 1, + data: { + articles: [ + { + type: "article", + id: "55", + workspace_id: "this_is_an_id92_that_should_be_at_least_4", + title: "Title 1", + description: "", + body: "", + author_id: 991267521, + state: "draft", + created_at: 1734537306, + updated_at: 1734537306, + url: "http://intercom.test/help/en/articles/3-default-language", + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + highlights: [ + { + article_id: "123", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + }); + }); + + test("search (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/articles/search").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.articles.search(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/awayStatusReasons.test.ts b/tests/wire/awayStatusReasons.test.ts new file mode 100644 index 00000000..f89aa99c --- /dev/null +++ b/tests/wire/awayStatusReasons.test.ts @@ -0,0 +1,74 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("AwayStatusReasonsClient", () => { + test("listAwayStatusReasons (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = [ + { + type: "away_status_reason", + id: "id", + label: "On a break", + emoji: "☕", + order: 1, + deleted: false, + created_at: 1734537243, + updated_at: 1734537243, + }, + ]; + server + .mockEndpoint() + .get("/away_status_reasons") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.awayStatusReasons.listAwayStatusReasons(); + expect(response).toEqual([ + { + type: "away_status_reason", + id: "id", + label: "On a break", + emoji: "\u2615", + order: 1, + deleted: false, + created_at: 1734537243, + updated_at: 1734537243, + }, + ]); + }); + + test("listAwayStatusReasons (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/away_status_reasons") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.awayStatusReasons.listAwayStatusReasons(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/calls.test.ts b/tests/wire/calls.test.ts new file mode 100644 index 00000000..5fc5aaec --- /dev/null +++ b/tests/wire/calls.test.ts @@ -0,0 +1,410 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("CallsClient", () => { + test("listCalls (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 25, + total_pages: 0, + }, + }; + server.mockEndpoint().get("/calls").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.calls.listCalls({ + page: 1, + per_page: 1, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 25, + total_pages: 0, + }, + }); + }); + + test("listCalls (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/calls").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.calls.listCalls(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("showCall (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: 1734537437, + answered_at: 1734537440, + ended_at: 1734537530, + created_at: 1734537437, + updated_at: 1734537531, + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "answered", + phone: "+15551234567", + fin_recording_url: "https://api.intercom.io/calls/124/recording", + fin_transcription_url: "https://api.intercom.io/calls/124/transcript", + }; + server.mockEndpoint().get("/calls/call_id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.calls.showCall({ + call_id: "call_id", + }); + expect(response).toEqual({ + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: 1734537437, + answered_at: 1734537440, + ended_at: 1734537530, + created_at: 1734537437, + updated_at: 1734537531, + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "answered", + phone: "+15551234567", + fin_recording_url: "https://api.intercom.io/calls/124/recording", + fin_transcription_url: "https://api.intercom.io/calls/124/transcript", + }); + }); + + test("showCall (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/calls/call_id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.calls.showCall({ + call_id: "call_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("showCall (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/calls/call_id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.calls.showCall({ + call_id: "call_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("showCallRecording (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().get("/calls/call_id/recording").respondWith().statusCode(200).build(); + + const response = await client.calls.showCallRecording({ + call_id: "call_id", + }); + expect(response).toEqual(undefined); + }); + + test("showCallRecording (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/calls/call_id/recording") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.calls.showCallRecording({ + call_id: "call_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("showCallRecording (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/calls/call_id/recording") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.calls.showCallRecording({ + call_id: "call_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listCallsWithTranscripts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["64619700005694", "64619700005695"] }; + const rawResponseBody = { + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "64619700005694", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + transcript: [{ key: "value" }], + transcript_status: "completed", + }, + ], + }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.calls.listCallsWithTranscripts({ + conversation_ids: ["64619700005694", "64619700005695"], + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "64619700005694", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + transcript: [ + { + key: "value", + }, + ], + transcript_status: "completed", + }, + ], + }); + }); + + test("listCallsWithTranscripts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["conversation_ids", "conversation_ids"] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.calls.listCallsWithTranscripts({ + conversation_ids: ["conversation_ids", "conversation_ids"], + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("listCallsWithTranscripts (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["conversation_ids", "conversation_ids"] }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.calls.listCallsWithTranscripts({ + conversation_ids: ["conversation_ids", "conversation_ids"], + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/companies.test.ts b/tests/wire/companies.test.ts new file mode 100644 index 00000000..90524081 --- /dev/null +++ b/tests/wire/companies.test.ts @@ -0,0 +1,1987 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("CompaniesClient", () => { + test("retrieve (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "offset_pages", page: 1, next: "next", per_page: 2, total_pages: 13 }, + total_count: 100, + data: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { paid_subscriber: true, monthly_spend: 155.5, team_mates: 9 }, + }, + ], + }; + server.mockEndpoint().get("/companies").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.companies.retrieve({ + name: "my company", + company_id: "12345", + tag_id: "678910", + segment_id: "98765", + page: 1, + per_page: 1, + }); + expect(response).toEqual({ + type: "list", + pages: { + type: "offset_pages", + page: 1, + next: "next", + per_page: 2, + total_pages: 13, + }, + total_count: 100, + data: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: true, + monthly_spend: 155.5, + team_mates: 9, + }, + }, + ], + }); + }); + + test("retrieve (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/companies").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.companies.retrieve(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("retrieve (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/companies").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.companies.retrieve(); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("createOrUpdate (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "my company", company_id: "company_remote_id", remote_created_at: 1374138000 }; + const rawResponseBody = { + type: "company", + id: "6762f0761bb69f9f2193bae2", + name: "my company", + app_id: "this_is_an_id147_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "company_remote_id", + remote_created_at: 1374138000, + created_at: 1734537334, + updated_at: 1734537334, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { creation_source: "api" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .post("/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.createOrUpdate({ + name: "my company", + company_id: "company_remote_id", + remote_created_at: 1374138000, + }); + expect(response).toEqual({ + type: "company", + id: "6762f0761bb69f9f2193bae2", + name: "my company", + app_id: "this_is_an_id147_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "company_remote_id", + remote_created_at: 1374138000, + created_at: 1734537334, + updated_at: 1734537334, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { + creation_source: "api", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("createOrUpdate (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f0761bb69f9f2193bae2", + name: "my company", + app_id: "this_is_an_id147_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "company_remote_id", + remote_created_at: 1374138000, + created_at: 1734537334, + updated_at: 1734537334, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { creation_source: "api" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server.mockEndpoint().post("/companies").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.companies.createOrUpdate(); + expect(response).toEqual({ + type: "company", + id: "6762f0761bb69f9f2193bae2", + name: "my company", + app_id: "this_is_an_id147_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "company_remote_id", + remote_created_at: 1374138000, + created_at: 1734537334, + updated_at: 1734537334, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { + creation_source: "api", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("createOrUpdate (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/companies").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.companies.createOrUpdate(undefined); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("createOrUpdate (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/companies").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.companies.createOrUpdate(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f07f1bb69f9f2193baf5", + name: "company1", + app_id: "this_is_an_id159_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537343, + created_at: 1734537343, + updated_at: 1734537343, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.find({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "company", + id: "6762f07f1bb69f9f2193baf5", + name: "company1", + app_id: "this_is_an_id159_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537343, + created_at: 1734537343, + updated_at: 1734537343, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/companies/company_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.find({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/company_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.find({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "my company", website: "http://www.mycompany.com/" }; + const rawResponseBody = { + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .put("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.update({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + body: { + name: "my company", + website: "http://www.mycompany.com/", + }, + }); + expect(response).toEqual({ + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .put("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.update({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + body: {}, + }); + expect(response).toEqual({ + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/companies/company_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.update({ + company_id: "company_id", + body: undefined, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/companies/company_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.update({ + company_id: "company_id", + body: undefined, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "6762f0881bb69f9f2193bb09", object: "company", deleted: true }; + server + .mockEndpoint() + .delete("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.delete({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + id: "6762f0881bb69f9f2193bb09", + object: "company", + deleted: true, + }); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/companies/company_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.delete({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/companies/company_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.delete({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAttachedContacts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", total_count: 100, has_more: true }, + notes: { url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", total_count: 100, has_more: true }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 50, + total_pages: 0, + }, + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632/contacts") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.listAttachedContacts({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", + total_count: 100, + has_more: true, + }, + notes: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + total_count: 100, + has_more: true, + }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 50, + total_pages: 0, + }, + }); + }); + + test("listAttachedContacts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/companies/company_id/contacts") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.listAttachedContacts({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedContacts (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/company_id/contacts") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.listAttachedContacts({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAttachedSegments (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "segment", + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + person_type: "contact", + count: 3, + }, + ], + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632/segments") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.listAttachedSegments({ + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "segment", + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + person_type: "contact", + count: 3, + }, + ], + }); + }); + + test("listAttachedSegments (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/companies/company_id/segments") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.listAttachedSegments({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedSegments (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/company_id/segments") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.listAttachedSegments({ + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "offset_pages", page: 1, next: "next", per_page: 15, total_pages: 1 }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f0941bb69f9f2193bb25", + name: "IntercomQATest1", + app_id: "this_is_an_id189_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537364, + created_at: 1734537364, + updated_at: 1734537364, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { key: "value" }, + tags: { type: "tag.list" }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }, + ], + }; + server + .mockEndpoint({ once: false }) + .post("/companies/list") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + pages: { + type: "offset_pages", + page: 1, + next: "next", + per_page: 15, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f0941bb69f9f2193bb25", + name: "IntercomQATest1", + app_id: "this_is_an_id189_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537364, + created_at: 1734537364, + updated_at: 1734537364, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }, + ], + }; + const page = await client.companies.list({ + page: 1, + per_page: 1, + order: "desc", + }); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .post("/companies/list") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("scroll (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "company", + id: "6762f0971bb69f9f2193bb2b", + name: "IntercomQATest1", + app_id: "this_is_an_id193_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537367, + created_at: 1734537367, + updated_at: 1734537367, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { key: "value" }, + tags: { type: "tag.list" }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }, + ], + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 2, + total_pages: 13, + }, + total_count: 100, + scroll_param: "69352cd2-ab5b-42ac-b004-a13d4e55e9b0", + }; + server + .mockEndpoint({ once: false }) + .get("/companies/scroll") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + data: [ + { + type: "company", + id: "6762f0971bb69f9f2193bb2b", + name: "IntercomQATest1", + app_id: "this_is_an_id193_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537367, + created_at: 1734537367, + updated_at: 1734537367, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }, + ], + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 2, + total_pages: 13, + }, + total_count: 100, + scroll_param: "69352cd2-ab5b-42ac-b004-a13d4e55e9b0", + }; + const page = await client.companies.scroll({ + scroll_param: "scroll_param", + }); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("scroll (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/companies/scroll") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.scroll(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("attachContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "6762f09a1bb69f9f2193bb34" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.attachContact({ + contact_id: "contact_id", + id: "6762f09a1bb69f9f2193bb34", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("attachContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "58a430d35458202d41b1e65b" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.attachContact({ + contact_id: "contact_id", + id: "58a430d35458202d41b1e65b", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("attachContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "123" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.attachContact({ + contact_id: "contact_id", + id: "123", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("attachContact (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.attachContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("attachContact (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.attachContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("attachContact (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.attachContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("detachContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f0a01bb69f9f2193bb44", + name: "company8", + app_id: "this_is_an_id205_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537376, + created_at: 1734537376, + updated_at: 1734537377, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }; + server + .mockEndpoint() + .delete("/contacts/58a430d35458202d41b1e65b/companies/58a430d35458202d41b1e65b") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.companies.detachContact({ + contact_id: "58a430d35458202d41b1e65b", + company_id: "58a430d35458202d41b1e65b", + }); + expect(response).toEqual({ + type: "company", + id: "6762f0a01bb69f9f2193bb44", + name: "company8", + app_id: "this_is_an_id205_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537376, + created_at: 1734537376, + updated_at: 1734537377, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + }); + }); + + test("detachContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/companies/company_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.detachContact({ + contact_id: "contact_id", + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("detachContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/companies/company_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.companies.detachContact({ + contact_id: "contact_id", + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/contacts.test.ts b/tests/wire/contacts.test.ts new file mode 100644 index 00000000..2f74a99a --- /dev/null +++ b/tests/wire/contacts.test.ts @@ -0,0 +1,2871 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("ContactsClient", () => { + test("listAttachedCompanies (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + companies: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { paid_subscriber: true, monthly_spend: 155.5, team_mates: 9 }, + }, + ], + total_count: 1, + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + }; + server + .mockEndpoint({ once: false }) + .get("/contacts/63a07ddf05a32042dffac965/companies") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + companies: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: true, + monthly_spend: 155.5, + team_mates: 9, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + }; + const page = await client.contacts.listAttachedCompanies({ + contact_id: "63a07ddf05a32042dffac965", + page: 1, + per_page: 1, + }); + + expect(expected.companies).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.companies).toEqual(nextPage.data); + }); + + test("listAttachedCompanies (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/contacts/contact_id/companies") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedCompanies({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedCompanies (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint({ once: false }) + .get("/contacts/contact_id/companies") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedCompanies({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAttachedSegments (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "segment", + id: "6762f0b21bb69f9f2193bb65", + name: "segment", + created_at: 1734537394, + updated_at: 1734537394, + person_type: "user", + count: 3, + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/segments") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.listAttachedSegments({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "segment", + id: "6762f0b21bb69f9f2193bb65", + name: "segment", + created_at: 1734537394, + updated_at: 1734537394, + person_type: "user", + count: 3, + }, + ], + }); + }); + + test("listAttachedSegments (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/segments") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedSegments({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedSegments (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/segments") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedSegments({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAttachedSubscriptions (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "subscription", + id: "91", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_out", + content_types: ["email"], + }, + { + type: "subscription", + id: "93", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/subscriptions") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.listAttachedSubscriptions({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "subscription", + id: "91", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_out", + content_types: ["email"], + }, + { + type: "subscription", + id: "93", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }, + ], + }); + }); + + test("listAttachedSubscriptions (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/subscriptions") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedSubscriptions({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedSubscriptions (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/subscriptions") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedSubscriptions({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("attachSubscription (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "37846", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.attachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscription (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "37846", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.attachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscription (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "invalid_id", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.attachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + id: "invalid_id", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscription (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", consent_type: "consent_type" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/contact_id/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.attachSubscription({ + contact_id: "contact_id", + id: "id", + consent_type: "consent_type", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("attachSubscription (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", consent_type: "consent_type" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.attachSubscription({ + contact_id: "contact_id", + id: "id", + consent_type: "consent_type", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("detachSubscription (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "subscription", + id: "122", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .delete("/contacts/63a07ddf05a32042dffac965/subscriptions/37846") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.detachSubscription({ + contact_id: "63a07ddf05a32042dffac965", + subscription_id: "37846", + }); + expect(response).toEqual({ + type: "subscription", + id: "122", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("detachSubscription (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/subscriptions/subscription_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.detachSubscription({ + contact_id: "contact_id", + subscription_id: "subscription_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("detachSubscription (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/subscriptions/subscription_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.detachSubscription({ + contact_id: "contact_id", + subscription_id: "subscription_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("listAttachedTags (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "tag", + id: "80", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/tags") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.listAttachedTags({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "tag", + id: "80", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }); + }); + + test("listAttachedTags (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/tags") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedTags({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("listAttachedTags (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/tags") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.listAttachedTags({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "contact", + id: "6762f0d01bb69f9f2193bb7d", + external_id: "70", + workspace_id: "this_is_an_id283_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537424, + updated_at: 1734537424, + signed_up_at: 1734537424, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.find({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0d01bb69f9f2193bb7d", + external_id: "70", + workspace_id: "this_is_an_id283_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537424, + updated_at: 1734537424, + signed_up_at: 1734537424, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.find({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { email: "joebloggs@intercom.io", name: "joe bloggs" }; + const rawResponseBody = { + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .put("/contacts/63a07ddf05a32042dffac965") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.update({ + contact_id: "63a07ddf05a32042dffac965", + email: "joebloggs@intercom.io", + name: "joe bloggs", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { custom_attributes: { order: ["21"] } }; + const rawResponseBody = { + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { order_number: "ORDER-12345", total_amount: 99.99 }, + type: "Order", + }, + ], + }, + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .put("/contacts/63a07ddf05a32042dffac965") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.update({ + contact_id: "63a07ddf05a32042dffac965", + custom_attributes: { + order: ["21"], + }, + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { + order_number: "ORDER-12345", + total_amount: 99.99, + }, + type: "Order", + }, + ], + }, + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/contacts/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.update({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", deleted: true }; + server + .mockEndpoint() + .delete("/contacts/contact_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.delete({ + contact_id: "contact_id", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + deleted: true, + }); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.delete({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("mergeLeadInUser (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: "6762f0d51bb69f9f2193bb7f", into: "6762f0d51bb69f9f2193bb80" }; + const rawResponseBody = { + type: "contact", + id: "6762f0d51bb69f9f2193bb80", + external_id: "70", + workspace_id: "this_is_an_id291_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537429, + updated_at: 1734537430, + signed_up_at: 1734537429, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .post("/contacts/merge") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.mergeLeadInUser({ + from: "6762f0d51bb69f9f2193bb7f", + into: "6762f0d51bb69f9f2193bb80", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0d51bb69f9f2193bb80", + external_id: "70", + workspace_id: "this_is_an_id291_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537429, + updated_at: 1734537430, + signed_up_at: 1734537429, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("mergeLeadInUser (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/merge") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.mergeLeadInUser(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("search (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", total_count: 100, has_more: true }, + notes: { url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", total_count: 100, has_more: true }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 0, + }, + }; + server + .mockEndpoint({ once: false }) + .post("/contacts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", + total_count: 100, + has_more: true, + }, + notes: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + total_count: 100, + has_more: true, + }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 0, + }, + }; + const page = await client.contacts.search({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("search (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { query: {} }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .post("/contacts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.search({ + query: {}, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "id", + external_id: "external_id", + workspace_id: "workspace_id", + role: "role", + email: "email", + email_domain: "email_domain", + phone: "phone", + name: "name", + owner_id: 1, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1, + updated_at: 1, + signed_up_at: 1, + last_seen_at: 1, + last_replied_at: 1, + last_contacted_at: 1, + last_email_opened_at: 1, + last_email_clicked_at: 1, + language_override: "language_override", + browser: "browser", + browser_version: "browser_version", + browser_language: "browser_language", + os: "os", + android_app_name: "android_app_name", + android_app_version: "android_app_version", + android_device: "android_device", + android_os_version: "android_os_version", + android_sdk_version: "android_sdk_version", + android_last_seen_at: 1, + ios_app_name: "ios_app_name", + ios_app_version: "ios_app_version", + ios_device: "ios_device", + ios_os_version: "ios_os_version", + ios_sdk_version: "ios_sdk_version", + ios_last_seen_at: 1, + custom_attributes: { custom_attributes: { key: "value" } }, + avatar: "avatar", + tags: { + data: [ + { type: "type", id: "id", url: "url" }, + { type: "type", id: "id", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + notes: { + data: [ + { type: "type", id: "id", url: "url" }, + { type: "type", id: "id", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + companies: { + data: [ + { id: "id", type: "company", url: "url" }, + { id: "id", type: "company", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + location: { type: "type", country: "country", region: "region", city: "city" }, + social_profiles: { + data: [ + { type: "social_profile", name: "name", url: "url" }, + { type: "social_profile", name: "name", url: "url" }, + ], + }, + }, + { + type: "contact", + id: "id", + external_id: "external_id", + workspace_id: "workspace_id", + role: "role", + email: "email", + email_domain: "email_domain", + phone: "phone", + name: "name", + owner_id: 1, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1, + updated_at: 1, + signed_up_at: 1, + last_seen_at: 1, + last_replied_at: 1, + last_contacted_at: 1, + last_email_opened_at: 1, + last_email_clicked_at: 1, + language_override: "language_override", + browser: "browser", + browser_version: "browser_version", + browser_language: "browser_language", + os: "os", + android_app_name: "android_app_name", + android_app_version: "android_app_version", + android_device: "android_device", + android_os_version: "android_os_version", + android_sdk_version: "android_sdk_version", + android_last_seen_at: 1, + ios_app_name: "ios_app_name", + ios_app_version: "ios_app_version", + ios_device: "ios_device", + ios_os_version: "ios_os_version", + ios_sdk_version: "ios_sdk_version", + ios_last_seen_at: 1, + custom_attributes: { custom_attributes: { key: "value" } }, + avatar: "avatar", + tags: { + data: [ + { type: "type", id: "id", url: "url" }, + { type: "type", id: "id", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + notes: { + data: [ + { type: "type", id: "id", url: "url" }, + { type: "type", id: "id", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + companies: { + data: [ + { id: "id", type: "company", url: "url" }, + { id: "id", type: "company", url: "url" }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + location: { type: "type", country: "country", region: "region", city: "city" }, + social_profiles: { + data: [ + { type: "social_profile", name: "name", url: "url" }, + { type: "social_profile", name: "name", url: "url" }, + ], + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 1, starting_after: "starting_after" }, + per_page: 1, + total_pages: 1, + }, + }; + server + .mockEndpoint({ once: false }) + .get("/contacts") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + data: [ + { + type: "contact", + id: "id", + external_id: "external_id", + workspace_id: "workspace_id", + role: "role", + email: "email", + email_domain: "email_domain", + phone: "phone", + name: "name", + owner_id: 1, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1, + updated_at: 1, + signed_up_at: 1, + last_seen_at: 1, + last_replied_at: 1, + last_contacted_at: 1, + last_email_opened_at: 1, + last_email_clicked_at: 1, + language_override: "language_override", + browser: "browser", + browser_version: "browser_version", + browser_language: "browser_language", + os: "os", + android_app_name: "android_app_name", + android_app_version: "android_app_version", + android_device: "android_device", + android_os_version: "android_os_version", + android_sdk_version: "android_sdk_version", + android_last_seen_at: 1, + ios_app_name: "ios_app_name", + ios_app_version: "ios_app_version", + ios_device: "ios_device", + ios_os_version: "ios_os_version", + ios_sdk_version: "ios_sdk_version", + ios_last_seen_at: 1, + custom_attributes: { + custom_attributes: { + key: "value", + }, + }, + avatar: "avatar", + tags: { + data: [ + { + type: "type", + id: "id", + url: "url", + }, + { + type: "type", + id: "id", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + notes: { + data: [ + { + type: "type", + id: "id", + url: "url", + }, + { + type: "type", + id: "id", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + companies: { + data: [ + { + id: "id", + type: "company", + url: "url", + }, + { + id: "id", + type: "company", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + location: { + type: "type", + country: "country", + region: "region", + city: "city", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "name", + url: "url", + }, + { + type: "social_profile", + name: "name", + url: "url", + }, + ], + }, + }, + { + type: "contact", + id: "id", + external_id: "external_id", + workspace_id: "workspace_id", + role: "role", + email: "email", + email_domain: "email_domain", + phone: "phone", + name: "name", + owner_id: 1, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1, + updated_at: 1, + signed_up_at: 1, + last_seen_at: 1, + last_replied_at: 1, + last_contacted_at: 1, + last_email_opened_at: 1, + last_email_clicked_at: 1, + language_override: "language_override", + browser: "browser", + browser_version: "browser_version", + browser_language: "browser_language", + os: "os", + android_app_name: "android_app_name", + android_app_version: "android_app_version", + android_device: "android_device", + android_os_version: "android_os_version", + android_sdk_version: "android_sdk_version", + android_last_seen_at: 1, + ios_app_name: "ios_app_name", + ios_app_version: "ios_app_version", + ios_device: "ios_device", + ios_os_version: "ios_os_version", + ios_sdk_version: "ios_sdk_version", + ios_last_seen_at: 1, + custom_attributes: { + custom_attributes: { + key: "value", + }, + }, + avatar: "avatar", + tags: { + data: [ + { + type: "type", + id: "id", + url: "url", + }, + { + type: "type", + id: "id", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + notes: { + data: [ + { + type: "type", + id: "id", + url: "url", + }, + { + type: "type", + id: "id", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + companies: { + data: [ + { + id: "id", + type: "company", + url: "url", + }, + { + id: "id", + type: "company", + url: "url", + }, + ], + url: "url", + total_count: 1, + has_more: true, + }, + location: { + type: "type", + country: "country", + region: "region", + city: "city", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "name", + url: "url", + }, + { + type: "social_profile", + name: "name", + url: "url", + }, + ], + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 1, + starting_after: "starting_after", + }, + per_page: 1, + total_pages: 1, + }, + }; + const page = await client.contacts.list(); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/contacts") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { email: "joebloggs@intercom.io" }; + const rawResponseBody = { + type: "contact", + id: "6762f0dd1bb69f9f2193bb83", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id303_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537437, + updated_at: 1734537437, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .post("/contacts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.create({ + email: "joebloggs@intercom.io", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0dd1bb69f9f2193bb83", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id303_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537437, + updated_at: 1734537437, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { email: "email" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.create({ + email: "email", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("ShowContactByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "contact", + id: "6762f0df1bb69f9f2193bb84", + external_id: "70", + workspace_id: "this_is_an_id307_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537439, + updated_at: 1734537439, + signed_up_at: 1734537439, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .get("/contacts/find_by_external_id/cdd29344-5e0c-4ef0-ac56-f9ba2979bc27") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.showContactByExternalId({ + external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0df1bb69f9f2193bb84", + external_id: "70", + workspace_id: "this_is_an_id307_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537439, + updated_at: 1734537439, + signed_up_at: 1734537439, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("ShowContactByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/find_by_external_id/external_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.contacts.showContactByExternalId({ + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("archive", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", archived: true }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/archive") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.archive({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + archived: true, + }); + }); + + test("unarchive", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", archived: false }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/unarchive") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.unarchive({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + archived: false, + }); + }); + + test("BlockContact", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", blocked: true }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/block") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.contacts.blockContact({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + blocked: true, + }); + }); +}); diff --git a/tests/wire/conversations.test.ts b/tests/wire/conversations.test.ts new file mode 100644 index 00000000..77dab803 --- /dev/null +++ b/tests/wire/conversations.test.ts @@ -0,0 +1,12610 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("ConversationsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "471", + title: "Conversation Title", + created_at: 1734537460, + updated_at: 1734537460, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }], + }, + conversation_rating: { rating: 5, remark: "", created_at: 1671028894, updated_at: 1671028894 }, + source: { + type: "conversation", + id: "403918320", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267628", + name: "Ciaran166 Lee", + email: "admin166@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f0f31bb69f9f2193bb8b", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { total_count: 1 }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 1, + }, + }; + server + .mockEndpoint({ once: false }) + .get("/conversations") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "471", + title: "Conversation Title", + created_at: 1734537460, + updated_at: 1734537460, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + }, + source: { + type: "conversation", + id: "403918320", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267628", + name: "Ciaran166 Lee", + email: "admin166@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f0f31bb69f9f2193bb8b", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 1, + }, + }; + const page = await client.conversations.list({ + per_page: 1, + starting_after: "starting_after", + }); + + expect(expected.conversations).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.conversations).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/conversations") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("list (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/conversations") + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.list(); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "user", id: "6762f11b1bb69f9f2193bba3" }, body: "Hello there" }; + const rawResponseBody = { + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.create({ + from: { + type: "user", + id: "6762f11b1bb69f9f2193bba3", + }, + body: "Hello there", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "user", id: "123_doesnt_exist" }, body: "Hello there" }; + const rawResponseBody = { + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.create({ + from: { + type: "user", + id: "123_doesnt_exist", + }, + body: "Hello there", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.create({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.create({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("create (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.create({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "conversation", + id: "503", + title: "Conversation Title", + created_at: 1734537511, + updated_at: 1734537511, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918334", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267645", + name: "Ciaran176 Lee", + email: "admin176@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1261bb69f9f2193bba7", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + assigned_to: { type: "contact", id: "1a2b3c" }, + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_started", + body: "

Okay!

", + created_at: 1740141842, + updated_at: 1740141842, + notified_at: 1740141842, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { action: { name: "Jira Create Issue" } }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1740141851, + updated_at: 1740141851, + notified_at: 1740141851, + author: { + type: "bot", + id: "278", + name: "Fin", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { attribute: { name: "jira_issue_key" }, value: { name: "PROJ-007" } }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_finished", + body: "

Okay!

", + created_at: 1740141857, + updated_at: 1740141857, + notified_at: 1740141857, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "closed", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { action: { name: "Jira Create Issue", result: "success" } }, + app_package_code: "test-integration", + }, + ], + total_count: 4, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server.mockEndpoint().get("/conversations/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.conversations.find({ + conversation_id: "123", + display_as: "plaintext", + include_translations: true, + }); + expect(response).toEqual({ + type: "conversation", + id: "503", + title: "Conversation Title", + created_at: 1734537511, + updated_at: 1734537511, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918334", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267645", + name: "Ciaran176 Lee", + email: "admin176@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1261bb69f9f2193bba7", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + assigned_to: { + type: "contact", + id: "1a2b3c", + }, + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_started", + body: "

Okay!

", + created_at: 1740141842, + updated_at: 1740141842, + notified_at: 1740141842, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + action: { + name: "Jira Create Issue", + }, + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1740141851, + updated_at: 1740141851, + notified_at: 1740141851, + author: { + type: "bot", + id: "278", + name: "Fin", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + attribute: { + name: "jira_issue_key", + }, + value: { + name: "PROJ-007", + }, + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_finished", + body: "

Okay!

", + created_at: 1740141857, + updated_at: 1740141857, + notified_at: 1740141857, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "closed", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + action: { + name: "Jira Create Issue", + result: "success", + }, + }, + app_package_code: "test-integration", + }, + ], + total_count: 4, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/conversations/conversation_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.find({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/conversations/conversation_id") + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.find({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("find (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/conversations/conversation_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.find({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + read: true, + title: "new conversation title", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1301bb69f9f2193bbab", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { issue_type: "Billing", priority: "High" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.update({ + conversation_id: "conversation_id", + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1301bb69f9f2193bbab", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { custom_attributes: { order: {} } }; + const rawResponseBody = { + type: "conversation", + id: "508", + title: "Conversation Title", + created_at: 1734537525, + updated_at: 1734537525, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918339", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267659", + name: "Ciaran185 Lee", + email: "admin185@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1341bb69f9f2193bbac", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1671028894, + updated_at: 1671028894, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }, + ], + }, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 0, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.update({ + conversation_id: "conversation_id", + display_as: "plaintext", + custom_attributes: { + order: {}, + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "508", + title: "Conversation Title", + created_at: 1734537525, + updated_at: 1734537525, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918339", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267659", + name: "Ciaran185 Lee", + email: "admin185@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1341bb69f9f2193bbac", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1671028894, + updated_at: 1671028894, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }, + ], + }, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 0, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + read: true, + title: "new conversation title", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1301bb69f9f2193bbab", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { issue_type: "Billing", priority: "High" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.update({ + conversation_id: "conversation_id", + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1301bb69f9f2193bbab", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.update({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.update({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("update (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/conversations/conversation_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.update({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("deleteConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "512", object: "conversation", deleted: true }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.deleteConversation({ + conversation_id: 1, + }); + expect(response).toEqual({ + id: "512", + object: "conversation", + deleted: true, + }); + }); + + test("deleteConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.deleteConversation({ + conversation_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.deleteConversation({ + conversation_id: 1, + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "515", + title: "Conversation Title", + created_at: 1734537546, + updated_at: 1734537546, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }], + }, + conversation_rating: { rating: 5, remark: "", created_at: 1671028894, updated_at: 1671028894 }, + source: { + type: "conversation", + id: "403918346", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267691", + name: "Ciaran210 Lee", + email: "admin210@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f14a1bb69f9f2193bbb3", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { total_count: 1 }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 1, + }, + }; + server + .mockEndpoint({ once: false }) + .post("/conversations/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "515", + title: "Conversation Title", + created_at: 1734537546, + updated_at: 1734537546, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + }, + source: { + type: "conversation", + id: "403918346", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267691", + name: "Ciaran210 Lee", + email: "admin210@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f14a1bb69f9f2193bbb3", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 1, + }, + }; + const page = await client.conversations.search({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + + expect(expected.conversations).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.conversations).toEqual(nextPage.data); + }); + + test("reply (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { text: "Yes", uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" }, + { text: "No", uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6" }, + ], + }; + const rawResponseBody = { + type: "conversation", + id: "526", + title: "Conversation Title", + created_at: 1734537567, + updated_at: 1734537568, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918351", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f15e1bb69f9f2193bbbd", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "134", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537568, + updated_at: 1734537568, + notified_at: 1734537568, + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { + text: "Yes", + uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb", + }, + { + text: "No", + uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6", + }, + ], + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "526", + title: "Conversation Title", + created_at: 1734537567, + updated_at: 1734537568, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918351", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f15e1bb69f9f2193bbbd", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "134", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537568, + updated_at: 1734537568, + notified_at: 1734537568, + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "body", + reply_options: [{ text: "Yes", uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" }], + intercom_user_id: "6762f1621bb69f9f2193bbbe", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "body", + reply_options: [ + { + text: "Yes", + uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb", + }, + ], + intercom_user_id: "6762f1621bb69f9f2193bbbe", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1661bb69f9f2193bbbf", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1661bb69f9f2193bbbf", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }; + const rawResponseBody = { + type: "conversation", + id: "525", + title: "Conversation Title", + created_at: 1734537563, + updated_at: 1734537565, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918350", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f15b1bb69f9f2193bbbc", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "133", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537565, + updated_at: 1734537565, + notified_at: 1734537565, + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "525", + title: "Conversation Title", + created_at: 1734537563, + updated_at: 1734537565, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918350", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f15b1bb69f9f2193bbbc", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "133", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537565, + updated_at: 1734537565, + notified_at: 1734537565, + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }; + const rawResponseBody = { + type: "conversation", + id: "527", + title: "Conversation Title", + created_at: 1734537571, + updated_at: 1734537572, + waiting_since: 1734537572, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918352", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267700", + name: "Ciaran215 Lee", + email: "admin215@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1621bb69f9f2193bbbe", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537572, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "135", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537572, + updated_at: 1734537572, + notified_at: 1734537572, + author: { + type: "user", + id: "6762f1621bb69f9f2193bbbe", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.reply({ + conversation_id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "527", + title: "Conversation Title", + created_at: 1734537571, + updated_at: 1734537572, + waiting_since: 1734537572, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918352", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267700", + name: "Ciaran215 Lee", + email: "admin215@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1621bb69f9f2193bbbe", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537572, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "135", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537572, + updated_at: 1734537572, + notified_at: 1734537572, + author: { + type: "user", + id: "6762f1621bb69f9f2193bbbe", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("reply (9)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.reply({ + conversation_id: "conversation_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("reply (10)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.reply({ + conversation_id: "conversation_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("reply (11)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.reply({ + conversation_id: "conversation_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("manage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "12345" }; + const rawResponseBody = { + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f16e1bb69f9f2193bbc2", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f16e1bb69f9f2193bbc2", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "snoozed", admin_id: "5017691", snoozed_until: 1673609604 }; + const rawResponseBody = { + type: "conversation", + id: "532", + title: "Conversation Title", + created_at: 1734537586, + updated_at: 1734537587, + waiting_since: 1663597260, + snoozed_until: 1734541187, + open: true, + state: "snoozed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918357", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1711bb69f9f2193bbc3", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "137", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537587, + updated_at: 1734537587, + notified_at: 1734537587, + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "snoozed", + admin_id: "5017691", + snoozed_until: 1673609604, + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "532", + title: "Conversation Title", + created_at: 1734537586, + updated_at: 1734537587, + waiting_since: 1663597260, + snoozed_until: 1734541187, + open: true, + state: "snoozed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918357", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1711bb69f9f2193bbc3", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "137", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537587, + updated_at: 1734537587, + notified_at: 1734537587, + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manage (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "open", admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "537", + title: "", + created_at: 1734537587, + updated_at: 1734537601, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918358", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1781bb69f9f2193bbc8", external_id: "74" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "139", + part_type: "open", + body: "

Okay!

", + created_at: 1734537601, + updated_at: 1734537601, + notified_at: 1734537601, + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "open", + admin_id: "5017690", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "537", + title: "", + created_at: 1734537587, + updated_at: 1734537601, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918358", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1781bb69f9f2193bbc8", + external_id: "74", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "139", + part_type: "open", + body: "

Okay!

", + created_at: 1734537601, + updated_at: 1734537601, + notified_at: 1734537601, + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manage (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "assignment", type: "admin", admin_id: "12345", assignee_id: "4324241" }; + const rawResponseBody = { + type: "conversation", + id: "542", + title: "Conversation Title", + created_at: 1734537603, + updated_at: 1734537605, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 991267715, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918361", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1831bb69f9f2193bbcc", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "140", + part_type: "assign_and_reopen", + body: "

Okay!

", + created_at: 1734537605, + updated_at: 1734537605, + notified_at: 1734537605, + assigned_to: { type: "admin", id: "991267715" }, + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "assignment", + type: "admin", + admin_id: "12345", + assignee_id: "4324241", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "542", + title: "Conversation Title", + created_at: 1734537603, + updated_at: 1734537605, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 991267715, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918361", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1831bb69f9f2193bbcc", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "140", + part_type: "assign_and_reopen", + body: "

Okay!

", + created_at: 1734537605, + updated_at: 1734537605, + notified_at: 1734537605, + assigned_to: { + type: "admin", + id: "991267715", + }, + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manage (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "12345" }; + const rawResponseBody = { + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f16e1bb69f9f2193bbc2", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.manage({ + conversation_id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f16e1bb69f9f2193bbc2", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manage (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.manage({ + conversation_id: "conversation_id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("manage (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.manage({ + conversation_id: "conversation_id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("manage (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.manage({ + conversation_id: "conversation_id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("attachContactAsAdmin (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "12345", customer: { intercom_user_id: "6762f19b1bb69f9f2193bbd4" } }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.attachContactAsAdmin({ + conversation_id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19b1bb69f9f2193bbd4", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("attachContactAsAdmin (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "12345", customer: { intercom_user_id: "6762f19e1bb69f9f2193bbd5" } }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.attachContactAsAdmin({ + conversation_id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19e1bb69f9f2193bbd5", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("attachContactAsAdmin (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.attachContactAsAdmin({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("attachContactAsAdmin (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.attachContactAsAdmin({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("attachContactAsAdmin (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.attachContactAsAdmin({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("detachContactAsAdmin (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.detachContactAsAdmin({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactAsAdmin (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.detachContactAsAdmin({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactAsAdmin (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.detachContactAsAdmin({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactAsAdmin (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.detachContactAsAdmin({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactAsAdmin (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.detachContactAsAdmin({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("detachContactAsAdmin (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.detachContactAsAdmin({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("detachContactAsAdmin (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.detachContactAsAdmin({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("detachContactAsAdmin (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.detachContactAsAdmin({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); + + test("redactConversationPart (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428", + }; + const rawResponseBody = { + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1f81bb69f9f2193bc09", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.redactConversationPart({ + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428", + }); + expect(response).toEqual({ + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1f81bb69f9f2193bc09", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("redactConversationPart (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "really_123_doesnt_exist", + conversation_part_id: "really_123_doesnt_exist", + }; + const rawResponseBody = { + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1f81bb69f9f2193bc09", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.redactConversationPart({ + type: "conversation_part", + conversation_id: "really_123_doesnt_exist", + conversation_part_id: "really_123_doesnt_exist", + }); + expect(response).toEqual({ + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1f81bb69f9f2193bc09", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("redactConversationPart (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.redactConversationPart({ + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("redactConversationPart (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.redactConversationPart({ + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("convertToTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "53" }; + const rawResponseBody = { + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { key: "value" }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f2041bb69f9f2193bc0c", external_id: "70" }], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.convertToTicket({ + conversation_id: 1, + ticket_type_id: "53", + }); + expect(response).toEqual({ + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { + key: "value", + }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2041bb69f9f2193bc0c", + external_id: "70", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }); + }); + + test("convertToTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "54" }; + const rawResponseBody = { + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { key: "value" }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f2041bb69f9f2193bc0c", external_id: "70" }], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.convertToTicket({ + conversation_id: 1, + ticket_type_id: "54", + }); + expect(response).toEqual({ + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { + key: "value", + }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2041bb69f9f2193bc0c", + external_id: "70", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }); + }); + + test("convertToTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.convertToTicket({ + conversation_id: 1, + ticket_type_id: "ticket_type_id", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("runAssignmentRules (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "conversation", + id: "409", + title: "Conversation Title", + created_at: 1719492880, + updated_at: 1719492881, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918285", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267623", + name: "Ciaran197 Lee", + email: "admin197@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "667d61108a68186f43bafe09", external_id: "70" }], + }, + teammates: { type: "admin.list", admins: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "107", + part_type: "default_assignment", + body: "

Okay!

", + created_at: 1719492881, + updated_at: 1719492881, + notified_at: 1719492881, + assigned_to: { type: "nobody_admin", id: "1a2b3c" }, + author: { + type: "bot", + id: "991267624", + name: "Operator", + email: "operator+this_is_an_id364_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/run_assignment_rules") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.conversations.runAssignmentRules({ + conversation_id: "123", + }); + expect(response).toEqual({ + type: "conversation", + id: "409", + title: "Conversation Title", + created_at: 1719492880, + updated_at: 1719492881, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918285", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267623", + name: "Ciaran197 Lee", + email: "admin197@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "667d61108a68186f43bafe09", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + admins: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "107", + part_type: "default_assignment", + body: "

Okay!

", + created_at: 1719492881, + updated_at: 1719492881, + notified_at: 1719492881, + assigned_to: { + type: "nobody_admin", + id: "1a2b3c", + }, + author: { + type: "bot", + id: "991267624", + name: "Operator", + email: "operator+this_is_an_id364_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("runAssignmentRules (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/run_assignment_rules") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.runAssignmentRules({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("runAssignmentRules (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/run_assignment_rules") + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.runAssignmentRules({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("runAssignmentRules (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/run_assignment_rules") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.conversations.runAssignmentRules({ + conversation_id: "conversation_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/customChannelEvents.test.ts b/tests/wire/customChannelEvents.test.ts new file mode 100644 index 00000000..f259cba1 --- /dev/null +++ b/tests/wire/customChannelEvents.test.ts @@ -0,0 +1,790 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("CustomChannelEventsClient", () => { + test("notifyNewConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + expect(response).toEqual({ + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }); + }); + + test("notifyNewConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("notifyNewConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("notifyNewConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("notifyNewConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); + + test("notifyNewMessage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + expect(response).toEqual({ + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }); + }); + + test("notifyNewMessage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("notifyNewMessage (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("notifyNewMessage (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("notifyNewMessage (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); + + test("notifyQuickReplySelected (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { type: "user", external_id: "user_003", name: "Alice Example", email: "alice@example.com" }, + quick_reply_option_id: "1234", + }; + const rawResponseBody = { + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customChannelEvents.notifyQuickReplySelected({ + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { + type: "user", + external_id: "user_003", + name: "Alice Example", + email: "alice@example.com", + }, + quick_reply_option_id: "1234", + }); + expect(response).toEqual({ + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }); + }); + + test("notifyQuickReplySelected (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("notifyQuickReplySelected (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("notifyQuickReplySelected (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("notifyQuickReplySelected (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); + + test("notifyAttributeCollected (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + expect(response).toEqual({ + external_conversation_id: "external_conversation_id", + conversation_id: "conversation_id", + external_contact_id: "external_contact_id", + contact_id: "contact_id", + }); + }); + + test("notifyAttributeCollected (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("notifyAttributeCollected (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("notifyAttributeCollected (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("notifyAttributeCollected (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/customObjectInstances.test.ts b/tests/wire/customObjectInstances.test.ts new file mode 100644 index 00000000..8d12db82 --- /dev/null +++ b/tests/wire/customObjectInstances.test.ts @@ -0,0 +1,475 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("CustomObjectInstancesClient", () => { + test("getCustomObjectInstancesByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "24", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537748, + updated_at: 1734537748, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .get("/custom_object_instances/Order") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + external_id: "external_id", + }); + expect(response).toEqual({ + id: "24", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537748, + updated_at: 1734537748, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("getCustomObjectInstancesByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("getCustomObjectInstancesByExternalId (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("createCustomObjectInstances (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + const rawResponseBody = { + id: "22", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1734537745, + updated_at: 1734537745, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .post("/custom_object_instances/Order") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "Order", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + expect(response).toEqual({ + id: "22", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1734537745, + updated_at: 1734537745, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("createCustomObjectInstances (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_object_instances/custom_object_type_identifier") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "custom_object_type_identifier", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("createCustomObjectInstances (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_object_instances/custom_object_type_identifier") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "custom_object_type_identifier", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("deleteCustomObjectInstancesById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { object: "Order", id: "26", deleted: true }; + server + .mockEndpoint() + .delete("/custom_object_instances/Order") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + external_id: "external_id", + }); + expect(response).toEqual({ + object: "Order", + id: "26", + deleted: true, + }); + }); + + test("deleteCustomObjectInstancesById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteCustomObjectInstancesById (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("getCustomObjectInstancesById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "25", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537750, + updated_at: 1734537750, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .get("/custom_object_instances/Order/custom_object_instance_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + custom_object_instance_id: "custom_object_instance_id", + }); + expect(response).toEqual({ + id: "25", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537750, + updated_at: 1734537750, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("getCustomObjectInstancesById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier/custom_object_instance_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + custom_object_instance_id: "custom_object_instance_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("getCustomObjectInstancesById (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier/custom_object_instance_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + custom_object_instance_id: "custom_object_instance_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("deleteCustomObjectInstancesByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { object: "Order", id: "26", deleted: true }; + server + .mockEndpoint() + .delete("/custom_object_instances/Order/custom_object_instance_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + custom_object_instance_id: "custom_object_instance_id", + }); + expect(response).toEqual({ + object: "Order", + id: "26", + deleted: true, + }); + }); + + test("deleteCustomObjectInstancesByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier/custom_object_instance_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + custom_object_instance_id: "custom_object_instance_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteCustomObjectInstancesByExternalId (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier/custom_object_instance_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + custom_object_instance_id: "custom_object_instance_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/dataAttributes.test.ts b/tests/wire/dataAttributes.test.ts new file mode 100644 index 00000000..b5b723af --- /dev/null +++ b/tests/wire/dataAttributes.test.ts @@ -0,0 +1,1515 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("DataAttributesClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "name", + label: "Company name", + description: "The name of a company", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "company_id", + full_name: "company_id", + label: "Company ID", + description: "A number identifying a company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "last_request_at", + full_name: "last_request_at", + label: "Company last seen", + description: "The last day anyone from a company visited your site or app", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "remote_created_at", + full_name: "remote_created_at", + label: "Company created at", + description: "The day a company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "user_count", + full_name: "user_count", + label: "People", + description: "The number of people in a company", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "session_count", + full_name: "session_count", + label: "Company web sessions", + description: "All visits from anyone in a company to your product's site or app", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "plan.name", + label: "Plan", + description: "A specific plan or level within your product that companies have signed up to", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "monthly_spend", + full_name: "monthly_spend", + label: "Monthly Spend", + description: "The monthly revenue you receive from a company", + data_type: "float", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "size", + full_name: "size", + label: "Company size", + description: "The number of people employed in this company, expressed as a single number", + data_type: "integer", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "industry", + full_name: "industry", + label: "Company industry", + description: "The category or domain this company belongs to e.g. 'ecommerce' or 'SaaS'", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "website", + full_name: "website", + label: "Company website", + description: "The web address for the company's primary marketing site", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 34, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: + "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537753, + updated_at: 1734537753, + admin_id: "991267784", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "id", + label: "ID", + description: "The Intercom defined id representing the company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "created_at", + full_name: "created_at", + label: "Created at", + description: "The time the company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "updated_at", + full_name: "updated_at", + label: "Updated at", + description: "The last time the company was updated", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "plan.id", + label: "Plan ID", + description: "The Intercom defined id representing the plan", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "app_id", + full_name: "app_id", + label: "App ID", + description: "The Intercom defined id representing the app", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + ], + }; + server.mockEndpoint().get("/data_attributes").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.dataAttributes.list({ + model: "contact", + include_archived: true, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "name", + label: "Company name", + description: "The name of a company", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "company_id", + full_name: "company_id", + label: "Company ID", + description: "A number identifying a company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "last_request_at", + full_name: "last_request_at", + label: "Company last seen", + description: "The last day anyone from a company visited your site or app", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "remote_created_at", + full_name: "remote_created_at", + label: "Company created at", + description: "The day a company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "user_count", + full_name: "user_count", + label: "People", + description: "The number of people in a company", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "session_count", + full_name: "session_count", + label: "Company web sessions", + description: "All visits from anyone in a company to your product's site or app", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "plan.name", + label: "Plan", + description: "A specific plan or level within your product that companies have signed up to", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "monthly_spend", + full_name: "monthly_spend", + label: "Monthly Spend", + description: "The monthly revenue you receive from a company", + data_type: "float", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "size", + full_name: "size", + label: "Company size", + description: "The number of people employed in this company, expressed as a single number", + data_type: "integer", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "industry", + full_name: "industry", + label: "Company industry", + description: "The category or domain this company belongs to e.g. 'ecommerce' or 'SaaS'", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "website", + full_name: "website", + label: "Company website", + description: "The web address for the company's primary marketing site", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 34, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: + "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537753, + updated_at: 1734537753, + admin_id: "991267784", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "id", + label: "ID", + description: "The Intercom defined id representing the company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "created_at", + full_name: "created_at", + label: "Created at", + description: "The time the company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "updated_at", + full_name: "updated_at", + label: "Updated at", + description: "The last time the company was updated", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "plan.id", + label: "Plan ID", + description: "The Intercom defined id representing the plan", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "app_id", + full_name: "app_id", + label: "App ID", + description: "The Intercom defined id representing the app", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/data_attributes").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.dataAttributes.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { data_type: "string" }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + data_type: "string", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { data_type: "integer" }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + data_type: "integer", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { data_type: "string" }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + data_type: "string", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { data_type: "string" }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + data_type: "string", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { data_type: "string" }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + data_type: "string", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{ value: "1-10" }] }; + const rawResponseBody = { + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.create({ + options: [ + { + value: "1-10", + }, + ], + }); + expect(response).toEqual({ + type: "data_attribute", + id: 37, + model: "company", + name: "Mithril Shirt", + full_name: "custom_attributes.Mithril Shirt", + label: "Mithril Shirt", + description: "Whether the user is a paid subscriber.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: false, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537756, + updated_at: 1734537756, + admin_id: "991267786", + }); + }); + + test("create (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.create({ + options: [{}, {}], + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.create({ + options: [{}, {}], + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{ value: "1-10" }, { value: "11-20" }] }; + const rawResponseBody = { + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [ + { + value: "1-10", + }, + { + value: "11-20", + }, + ], + }, + }); + expect(response).toEqual({ + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{ value: "1-10" }, { value: "11-50" }] }; + const rawResponseBody = { + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [ + { + value: "1-10", + }, + { + value: "11-50", + }, + ], + }, + }); + expect(response).toEqual({ + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{ value: "1-10" }, { value: "11-20" }] }; + const rawResponseBody = { + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [ + { + value: "1-10", + }, + { + value: "11-20", + }, + ], + }, + }); + expect(response).toEqual({ + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { description: "Trying to archieve", archived: true }; + const rawResponseBody = { + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + description: "Trying to archieve", + archived: true, + }, + }); + expect(response).toEqual({ + type: "data_attribute", + id: 44, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: "Just a plain old ring", + data_type: "string", + options: ["1-10", "11-20"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537762, + updated_at: 1734537763, + admin_id: "991267793", + }); + }); + + test("update (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [{}, {}], + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("update (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [{}, {}], + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [{}, {}], + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { options: [{}, {}] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataAttributes.update({ + data_attribute_id: 1, + body: { + options: [{}, {}], + }, + }); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/dataExport.test.ts b/tests/wire/dataExport.test.ts new file mode 100644 index 00000000..a141d93e --- /dev/null +++ b/tests/wire/dataExport.test.ts @@ -0,0 +1,273 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("DataExportClient", () => { + test("exportReportingData (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + job_identifier: "job1", + status: "complete", + download_url: "", + download_expires_at: "", + }; + server + .mockEndpoint() + .get("/export/reporting_data/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataExport.exportReportingData({ + job_identifier: "job_identifier", + app_id: "app_id", + client_id: "client_id", + }); + expect(response).toEqual({ + job_identifier: "job1", + status: "complete", + download_url: "", + download_expires_at: "", + }); + }); + + test("exportReportingData (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { job_identifier: "job1", status: "failed", download_url: "", download_expires_at: "" }; + server + .mockEndpoint() + .get("/export/reporting_data/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataExport.exportReportingData({ + job_identifier: "job_identifier", + app_id: "app_id", + client_id: "client_id", + }); + expect(response).toEqual({ + job_identifier: "job1", + status: "failed", + download_url: "", + download_expires_at: "", + }); + }); + + test("exportReportingData (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/export/reporting_data/job_identifier") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataExport.exportReportingData({ + job_identifier: "job_identifier", + app_id: "app_id", + client_id: "client_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("downloadReportingDataExport (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server + .mockEndpoint() + .get("/download/reporting_data/job_identifier") + .header("Accept", "application/octet-stream") + .respondWith() + .statusCode(200) + .build(); + + const response = await client.dataExport.downloadReportingDataExport({ + job_identifier: "job_identifier", + app_id: "app_id", + }); + expect(response).toEqual(undefined); + }); + + test("downloadReportingDataExport (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/download/reporting_data/job_identifier") + .header("Accept", "application/octet-stream") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.dataExport.downloadReportingDataExport({ + job_identifier: "job_identifier", + app_id: "app_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { created_at_after: 1734519776, created_at_before: 1734537776 }; + const rawResponseBody = { + job_identifier: "al9w983lwu88w1fd", + status: "pending", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .post("/export/content/data") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataExport.create({ + created_at_after: 1734519776, + created_at_before: 1734537776, + }); + expect(response).toEqual({ + job_identifier: "al9w983lwu88w1fd", + status: "pending", + download_expires_at: "", + download_url: "", + }); + }); + + test("find", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + job_identifier: "braxwk3j039t6txy", + status: "pending", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .get("/export/content/data/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataExport.find({ + job_identifier: "job_identifier", + }); + expect(response).toEqual({ + job_identifier: "braxwk3j039t6txy", + status: "pending", + download_expires_at: "", + download_url: "", + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + job_identifier: "v134nyc2bku9hj91", + status: "canceled", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .post("/export/cancel/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.dataExport.cancel({ + job_identifier: "job_identifier", + }); + expect(response).toEqual({ + job_identifier: "v134nyc2bku9hj91", + status: "canceled", + download_expires_at: "", + download_url: "", + }); + }); + + test("download", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().get("/download/content/data/job_identifier").respondWith().statusCode(200).build(); + + const response = await client.dataExport.download({ + job_identifier: "job_identifier", + }); + expect(response).toEqual(undefined); + }); +}); diff --git a/tests/wire/events.test.ts b/tests/wire/events.test.ts new file mode 100644 index 00000000..b6b4756a --- /dev/null +++ b/tests/wire/events.test.ts @@ -0,0 +1,169 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("EventsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "event.summary", + email: "user26@email.com", + intercom_user_id: "6762f22b1bb69f9f2193bc12", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + events: [ + { + name: "placed-order", + first: "2014-01-16T23:12:21.000+00:00", + last: "2014-01-16T23:12:21.000+00:00 ", + count: 1, + description: "A user placed an order", + }, + ], + }; + server.mockEndpoint().get("/events").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.events.list({ + user_id: "user_id", + intercom_user_id: "intercom_user_id", + email: "email", + type: "type", + summary: true, + per_page: 1, + }); + expect(response).toEqual({ + type: "event.summary", + email: "user26@email.com", + intercom_user_id: "6762f22b1bb69f9f2193bc12", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + events: [ + { + name: "placed-order", + first: "2014-01-16T23:12:21.000+00:00", + last: "2014-01-16T23:12:21.000+00:00 ", + count: 1, + description: "A user placed an order", + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/events").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.events.list({ + type: "type", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", + event_name: "invited-friend", + created_at: 1671028894, + }; + + server.mockEndpoint().post("/events").jsonBody(rawRequestBody).respondWith().statusCode(200).build(); + + const response = await client.events.create({ + id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", + event_name: "invited-friend", + created_at: 1671028894, + }); + expect(response).toEqual(undefined); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", event_name: "event_name", created_at: 1 }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/events") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.events.create({ + id: "id", + event_name: "event_name", + created_at: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("summaries (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + + server.mockEndpoint().post("/events/summaries").jsonBody(rawRequestBody).respondWith().statusCode(200).build(); + + const response = await client.events.summaries(); + expect(response).toEqual(undefined); + }); + + test("summaries (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/events/summaries") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.events.summaries(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/export.test.ts b/tests/wire/export.test.ts new file mode 100644 index 00000000..c7ff75eb --- /dev/null +++ b/tests/wire/export.test.ts @@ -0,0 +1,201 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("ExportClient", () => { + test("enqueueANewReportingDataExportJob (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000, + }; + const rawResponseBody = { + job_identifier: "job1", + status: "pending", + download_url: "download_url", + download_expires_at: "download_expires_at", + }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.export.enqueueANewReportingDataExportJob({ + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000, + }); + expect(response).toEqual({ + job_identifier: "job1", + status: "pending", + download_url: "download_url", + download_expires_at: "download_expires_at", + }); + }); + + test("enqueueANewReportingDataExportJob (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("enqueueANewReportingDataExportJob (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("enqueueANewReportingDataExportJob (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(429) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.TooManyRequestsError); + }); + + test("listAvailableDatasetsAndAttributes", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + id: "conversation", + name: "Conversation", + description: "Conversation-level details: status, channel, assignee.", + default_time_attribute_id: "conversation_started_at", + attributes: [{ id: "conversation_id", name: "Conversation ID" }], + }, + ], + }; + server + .mockEndpoint() + .get("/export/reporting_data/get_datasets") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.export.listAvailableDatasetsAndAttributes(); + expect(response).toEqual({ + type: "list", + data: [ + { + id: "conversation", + name: "Conversation", + description: "Conversation-level details: status, channel, assignee.", + default_time_attribute_id: "conversation_started_at", + attributes: [ + { + id: "conversation_id", + name: "Conversation ID", + }, + ], + }, + ], + }); + }); +}); diff --git a/tests/wire/helpCenters.test.ts b/tests/wire/helpCenters.test.ts new file mode 100644 index 00000000..6376c589 --- /dev/null +++ b/tests/wire/helpCenters.test.ts @@ -0,0 +1,203 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("HelpCentersClient", () => { + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "93", + workspace_id: "this_is_an_id124_that_should_be_at_least_", + created_at: 1734537325, + updated_at: 1734537325, + identifier: "help-center-1", + website_turned_on: false, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.find({ + help_center_id: 1, + }); + expect(response).toEqual({ + id: "93", + workspace_id: "this_is_an_id124_that_should_be_at_least_", + created_at: 1734537325, + updated_at: 1734537325, + identifier: "help-center-1", + website_turned_on: false, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.find({ + help_center_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.find({ + help_center_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + id: "id", + workspace_id: "workspace_id", + created_at: 1, + updated_at: 1, + identifier: "identifier", + website_turned_on: true, + display_name: "display_name", + url: "url", + custom_domain: "custom_domain", + }, + { + id: "id", + workspace_id: "workspace_id", + created_at: 1, + updated_at: 1, + identifier: "identifier", + website_turned_on: true, + display_name: "display_name", + url: "url", + custom_domain: "custom_domain", + }, + ], + }; + server + .mockEndpoint({ once: false }) + .get("/help_center/help_centers") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + data: [ + { + id: "id", + workspace_id: "workspace_id", + created_at: 1, + updated_at: 1, + identifier: "identifier", + website_turned_on: true, + display_name: "display_name", + url: "url", + custom_domain: "custom_domain", + }, + { + id: "id", + workspace_id: "workspace_id", + created_at: 1, + updated_at: 1, + identifier: "identifier", + website_turned_on: true, + display_name: "display_name", + url: "url", + custom_domain: "custom_domain", + }, + ], + }; + const page = await client.helpCenters.list(); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/help_center/help_centers") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/helpCenters/collections.test.ts b/tests/wire/helpCenters/collections.test.ts new file mode 100644 index 00000000..c32574f1 --- /dev/null +++ b/tests/wire/helpCenters/collections.test.ts @@ -0,0 +1,2216 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("CollectionsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "offset_pages", page: 1, next: "next", per_page: 1, total_pages: 1 }, + total_count: 1, + data: [ + { + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + created_at: 1, + updated_at: 1, + url: "url", + icon: "icon", + order: 1, + default_locale: "default_locale", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "name", description: "description" }, + bg: { type: "group_content", name: "name", description: "description" }, + bs: { type: "group_content", name: "name", description: "description" }, + ca: { type: "group_content", name: "name", description: "description" }, + cs: { type: "group_content", name: "name", description: "description" }, + da: { type: "group_content", name: "name", description: "description" }, + de: { type: "group_content", name: "name", description: "description" }, + el: { type: "group_content", name: "name", description: "description" }, + en: { type: "group_content", name: "name", description: "description" }, + es: { type: "group_content", name: "name", description: "description" }, + et: { type: "group_content", name: "name", description: "description" }, + fi: { type: "group_content", name: "name", description: "description" }, + fr: { type: "group_content", name: "name", description: "description" }, + he: { type: "group_content", name: "name", description: "description" }, + hr: { type: "group_content", name: "name", description: "description" }, + hu: { type: "group_content", name: "name", description: "description" }, + id: { type: "group_content", name: "name", description: "description" }, + it: { type: "group_content", name: "name", description: "description" }, + ja: { type: "group_content", name: "name", description: "description" }, + ko: { type: "group_content", name: "name", description: "description" }, + lt: { type: "group_content", name: "name", description: "description" }, + lv: { type: "group_content", name: "name", description: "description" }, + mn: { type: "group_content", name: "name", description: "description" }, + nb: { type: "group_content", name: "name", description: "description" }, + nl: { type: "group_content", name: "name", description: "description" }, + pl: { type: "group_content", name: "name", description: "description" }, + pt: { type: "group_content", name: "name", description: "description" }, + ro: { type: "group_content", name: "name", description: "description" }, + ru: { type: "group_content", name: "name", description: "description" }, + sl: { type: "group_content", name: "name", description: "description" }, + sr: { type: "group_content", name: "name", description: "description" }, + sv: { type: "group_content", name: "name", description: "description" }, + tr: { type: "group_content", name: "name", description: "description" }, + vi: { type: "group_content", name: "name", description: "description" }, + "pt-BR": { type: "group_content", name: "name", description: "description" }, + "zh-CN": { type: "group_content", name: "name", description: "description" }, + "zh-TW": { type: "group_content", name: "name", description: "description" }, + }, + parent_id: "parent_id", + help_center_id: 1, + }, + { + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + created_at: 1, + updated_at: 1, + url: "url", + icon: "icon", + order: 1, + default_locale: "default_locale", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "name", description: "description" }, + bg: { type: "group_content", name: "name", description: "description" }, + bs: { type: "group_content", name: "name", description: "description" }, + ca: { type: "group_content", name: "name", description: "description" }, + cs: { type: "group_content", name: "name", description: "description" }, + da: { type: "group_content", name: "name", description: "description" }, + de: { type: "group_content", name: "name", description: "description" }, + el: { type: "group_content", name: "name", description: "description" }, + en: { type: "group_content", name: "name", description: "description" }, + es: { type: "group_content", name: "name", description: "description" }, + et: { type: "group_content", name: "name", description: "description" }, + fi: { type: "group_content", name: "name", description: "description" }, + fr: { type: "group_content", name: "name", description: "description" }, + he: { type: "group_content", name: "name", description: "description" }, + hr: { type: "group_content", name: "name", description: "description" }, + hu: { type: "group_content", name: "name", description: "description" }, + id: { type: "group_content", name: "name", description: "description" }, + it: { type: "group_content", name: "name", description: "description" }, + ja: { type: "group_content", name: "name", description: "description" }, + ko: { type: "group_content", name: "name", description: "description" }, + lt: { type: "group_content", name: "name", description: "description" }, + lv: { type: "group_content", name: "name", description: "description" }, + mn: { type: "group_content", name: "name", description: "description" }, + nb: { type: "group_content", name: "name", description: "description" }, + nl: { type: "group_content", name: "name", description: "description" }, + pl: { type: "group_content", name: "name", description: "description" }, + pt: { type: "group_content", name: "name", description: "description" }, + ro: { type: "group_content", name: "name", description: "description" }, + ru: { type: "group_content", name: "name", description: "description" }, + sl: { type: "group_content", name: "name", description: "description" }, + sr: { type: "group_content", name: "name", description: "description" }, + sv: { type: "group_content", name: "name", description: "description" }, + tr: { type: "group_content", name: "name", description: "description" }, + vi: { type: "group_content", name: "name", description: "description" }, + "pt-BR": { type: "group_content", name: "name", description: "description" }, + "zh-CN": { type: "group_content", name: "name", description: "description" }, + "zh-TW": { type: "group_content", name: "name", description: "description" }, + }, + parent_id: "parent_id", + help_center_id: 1, + }, + ], + }; + server + .mockEndpoint({ once: false }) + .get("/help_center/collections") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "list", + pages: { + type: "offset_pages", + page: 1, + next: "next", + per_page: 1, + total_pages: 1, + }, + total_count: 1, + data: [ + { + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + created_at: 1, + updated_at: 1, + url: "url", + icon: "icon", + order: 1, + default_locale: "default_locale", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "name", + description: "description", + }, + bg: { + type: "group_content", + name: "name", + description: "description", + }, + bs: { + type: "group_content", + name: "name", + description: "description", + }, + ca: { + type: "group_content", + name: "name", + description: "description", + }, + cs: { + type: "group_content", + name: "name", + description: "description", + }, + da: { + type: "group_content", + name: "name", + description: "description", + }, + de: { + type: "group_content", + name: "name", + description: "description", + }, + el: { + type: "group_content", + name: "name", + description: "description", + }, + en: { + type: "group_content", + name: "name", + description: "description", + }, + es: { + type: "group_content", + name: "name", + description: "description", + }, + et: { + type: "group_content", + name: "name", + description: "description", + }, + fi: { + type: "group_content", + name: "name", + description: "description", + }, + fr: { + type: "group_content", + name: "name", + description: "description", + }, + he: { + type: "group_content", + name: "name", + description: "description", + }, + hr: { + type: "group_content", + name: "name", + description: "description", + }, + hu: { + type: "group_content", + name: "name", + description: "description", + }, + id: { + type: "group_content", + name: "name", + description: "description", + }, + it: { + type: "group_content", + name: "name", + description: "description", + }, + ja: { + type: "group_content", + name: "name", + description: "description", + }, + ko: { + type: "group_content", + name: "name", + description: "description", + }, + lt: { + type: "group_content", + name: "name", + description: "description", + }, + lv: { + type: "group_content", + name: "name", + description: "description", + }, + mn: { + type: "group_content", + name: "name", + description: "description", + }, + nb: { + type: "group_content", + name: "name", + description: "description", + }, + nl: { + type: "group_content", + name: "name", + description: "description", + }, + pl: { + type: "group_content", + name: "name", + description: "description", + }, + pt: { + type: "group_content", + name: "name", + description: "description", + }, + ro: { + type: "group_content", + name: "name", + description: "description", + }, + ru: { + type: "group_content", + name: "name", + description: "description", + }, + sl: { + type: "group_content", + name: "name", + description: "description", + }, + sr: { + type: "group_content", + name: "name", + description: "description", + }, + sv: { + type: "group_content", + name: "name", + description: "description", + }, + tr: { + type: "group_content", + name: "name", + description: "description", + }, + vi: { + type: "group_content", + name: "name", + description: "description", + }, + "pt-BR": { + type: "group_content", + name: "name", + description: "description", + }, + "zh-CN": { + type: "group_content", + name: "name", + description: "description", + }, + "zh-TW": { + type: "group_content", + name: "name", + description: "description", + }, + }, + parent_id: "parent_id", + help_center_id: 1, + }, + { + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + created_at: 1, + updated_at: 1, + url: "url", + icon: "icon", + order: 1, + default_locale: "default_locale", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "name", + description: "description", + }, + bg: { + type: "group_content", + name: "name", + description: "description", + }, + bs: { + type: "group_content", + name: "name", + description: "description", + }, + ca: { + type: "group_content", + name: "name", + description: "description", + }, + cs: { + type: "group_content", + name: "name", + description: "description", + }, + da: { + type: "group_content", + name: "name", + description: "description", + }, + de: { + type: "group_content", + name: "name", + description: "description", + }, + el: { + type: "group_content", + name: "name", + description: "description", + }, + en: { + type: "group_content", + name: "name", + description: "description", + }, + es: { + type: "group_content", + name: "name", + description: "description", + }, + et: { + type: "group_content", + name: "name", + description: "description", + }, + fi: { + type: "group_content", + name: "name", + description: "description", + }, + fr: { + type: "group_content", + name: "name", + description: "description", + }, + he: { + type: "group_content", + name: "name", + description: "description", + }, + hr: { + type: "group_content", + name: "name", + description: "description", + }, + hu: { + type: "group_content", + name: "name", + description: "description", + }, + id: { + type: "group_content", + name: "name", + description: "description", + }, + it: { + type: "group_content", + name: "name", + description: "description", + }, + ja: { + type: "group_content", + name: "name", + description: "description", + }, + ko: { + type: "group_content", + name: "name", + description: "description", + }, + lt: { + type: "group_content", + name: "name", + description: "description", + }, + lv: { + type: "group_content", + name: "name", + description: "description", + }, + mn: { + type: "group_content", + name: "name", + description: "description", + }, + nb: { + type: "group_content", + name: "name", + description: "description", + }, + nl: { + type: "group_content", + name: "name", + description: "description", + }, + pl: { + type: "group_content", + name: "name", + description: "description", + }, + pt: { + type: "group_content", + name: "name", + description: "description", + }, + ro: { + type: "group_content", + name: "name", + description: "description", + }, + ru: { + type: "group_content", + name: "name", + description: "description", + }, + sl: { + type: "group_content", + name: "name", + description: "description", + }, + sr: { + type: "group_content", + name: "name", + description: "description", + }, + sv: { + type: "group_content", + name: "name", + description: "description", + }, + tr: { + type: "group_content", + name: "name", + description: "description", + }, + vi: { + type: "group_content", + name: "name", + description: "description", + }, + "pt-BR": { + type: "group_content", + name: "name", + description: "description", + }, + "zh-CN": { + type: "group_content", + name: "name", + description: "description", + }, + "zh-TW": { + type: "group_content", + name: "name", + description: "description", + }, + }, + parent_id: "parent_id", + help_center_id: 1, + }, + ], + }; + const page = await client.helpCenters.collections.list(); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint({ once: false }) + .get("/help_center/collections") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Thanks for everything" }; + const rawResponseBody = { + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 81, + }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.create({ + name: "Thanks for everything", + }); + expect(response).toEqual({ + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 81, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "collection 51", description: "Missing required parameter" }; + const rawResponseBody = { + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 81, + }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.create({ + name: "collection 51", + description: "Missing required parameter", + }); + expect(response).toEqual({ + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 81, + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.create({ + name: "name", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.create({ + name: "name", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "170", + workspace_id: "this_is_an_id106_that_should_be_at_least_", + name: "English collection title", + description: "english collection description", + created_at: 1734537315, + updated_at: 1734537315, + url: "http://help-center.test/myapp-106/collection-22", + icon: "bookmark", + order: 22, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 84, + }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.find({ + collection_id: 1, + }); + expect(response).toEqual({ + id: "170", + workspace_id: "this_is_an_id106_that_should_be_at_least_", + name: "English collection title", + description: "english collection description", + created_at: 1734537315, + updated_at: 1734537315, + url: "http://help-center.test/myapp-106/collection-22", + icon: "bookmark", + order: 22, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 84, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.find({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.find({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Update collection name" }; + const rawResponseBody = { + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 87, + }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.update({ + collection_id: 1, + name: "Update collection name", + }); + expect(response).toEqual({ + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 87, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Update collection name" }; + const rawResponseBody = { + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 87, + }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.update({ + collection_id: 1, + name: "Update collection name", + }); + expect(response).toEqual({ + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 87, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.update({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.update({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "182", object: "collection", deleted: true }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.helpCenters.collections.delete({ + collection_id: 1, + }); + expect(response).toEqual({ + id: "182", + object: "collection", + deleted: true, + }); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.delete({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.helpCenters.collections.delete({ + collection_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/internalArticles.test.ts b/tests/wire/internalArticles.test.ts new file mode 100644 index 00000000..3ef231a2 --- /dev/null +++ b/tests/wire/internalArticles.test.ts @@ -0,0 +1,655 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("InternalArticlesClient", () => { + test("listInternalArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "internal_article", + id: "39", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }; + server.mockEndpoint().get("/internal_articles").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.internalArticles.listInternalArticles(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "internal_article", + id: "39", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }); + }); + + test("listInternalArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/internal_articles").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.internalArticles.listInternalArticles(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("createInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252, + }; + const rawResponseBody = { + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .post("/internal_articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252, + }); + expect(response).toEqual({ + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("createInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + body: "Body of the Internal Article", + author_id: 1295, + owner_id: 1295, + }; + const rawResponseBody = { + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .post("/internal_articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Internal Article", + author_id: 1295, + owner_id: 1295, + }); + expect(response).toEqual({ + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("createInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/internal_articles") + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.createInternalArticle(undefined); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("createInternalArticle (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/internal_articles") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.createInternalArticle(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("retrieveInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "internal_article", + id: "45", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.retrieveInternalArticle({ + internal_article_id: 1, + }); + expect(response).toEqual({ + type: "internal_article", + id: "45", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("retrieveInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.retrieveInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("retrieveInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.retrieveInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("updateInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.updateInternalArticle({ + internal_article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("updateInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.updateInternalArticle({ + internal_article_id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("updateInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.updateInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("updateInternalArticle (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.updateInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("deleteInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "51", object: "internal_article", deleted: true }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.deleteInternalArticle({ + internal_article_id: 1, + }); + expect(response).toEqual({ + id: "51", + object: "internal_article", + deleted: true, + }); + }); + + test("deleteInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.deleteInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.deleteInternalArticle({ + internal_article_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("searchInternalArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + total_count: 1, + data: { + internal_articles: [ + { + id: "55", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + }; + server + .mockEndpoint() + .get("/internal_articles/search") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.internalArticles.searchInternalArticles({ + folder_id: "folder_id", + }); + expect(response).toEqual({ + type: "list", + total_count: 1, + data: { + internal_articles: [ + { + id: "55", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + }); + }); + + test("searchInternalArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/internal_articles/search") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.internalArticles.searchInternalArticles(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/jobs.test.ts b/tests/wire/jobs.test.ts new file mode 100644 index 00000000..ed487a93 --- /dev/null +++ b/tests/wire/jobs.test.ts @@ -0,0 +1,97 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("JobsClient", () => { + test("status (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "job", + id: "2", + url: "https://api.intercom.io/jobs/status/20", + status: "success", + resource_type: "ticket", + resource_id: "20", + resource_url: "https://api.intercom.io/tickets/20", + }; + server + .mockEndpoint() + .get("/jobs/status/job_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.jobs.status({ + job_id: "job_id", + }); + expect(response).toEqual({ + type: "job", + id: "2", + url: "https://api.intercom.io/jobs/status/20", + status: "success", + resource_type: "ticket", + resource_id: "20", + resource_url: "https://api.intercom.io/tickets/20", + }); + }); + + test("status (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/jobs/status/job_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.jobs.status({ + job_id: "job_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("status (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/jobs/status/job_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.jobs.status({ + job_id: "job_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/messages.test.ts b/tests/wire/messages.test.ts new file mode 100644 index 00000000..4c5270c9 --- /dev/null +++ b/tests/wire/messages.test.ts @@ -0,0 +1,618 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("MessagesClient", () => { + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "inapp", + subject: "heyy", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "6762f23b1bb69f9f2193bc1a" }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "inapp", + subject: "heyy", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "6762f23b1bb69f9f2193bc1a", + }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "hey there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "hey there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "heyy", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "6762f23d1bb69f9f2193bc1c" }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "heyy", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "6762f23d1bb69f9f2193bc1c", + }, + created_at: 1590000000, + create_conversation_without_contact_reply: true, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("create (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "user_message", + id: "403918397", + created_at: 1734537783, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "614", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "user_message", + id: "403918397", + created_at: 1734537783, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "614", + }); + }); + + test("create (9)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { type: "admin", id: 394051 }, + to: { type: "user", id: "536e564f316c83104c000020" }, + }; + const rawResponseBody = { + type: "admin_message", + id: "19", + created_at: 1734537786, + subject: "heyy", + body: "heyy", + message_type: "inapp", + conversation_id: "64619700005570", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.messages.create({ + message_type: "email", + subject: "Thanks for everything", + body: "Hello there", + template: "plain", + from: { + type: "admin", + id: 394051, + }, + to: { + type: "user", + id: "536e564f316c83104c000020", + }, + }); + expect(response).toEqual({ + type: "admin_message", + id: "19", + created_at: 1734537786, + subject: "heyy", + body: "heyy", + message_type: "inapp", + conversation_id: "64619700005570", + }); + }); + + test("create (10)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/messages").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.messages.create(undefined); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (11)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/messages").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.messages.create(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (12)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/messages").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.messages.create(undefined); + }).rejects.toThrow(Intercom.ForbiddenError); + }); + + test("create (13)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/messages").respondWith().statusCode(422).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.messages.create(undefined); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/news/feeds.test.ts b/tests/wire/news/feeds.test.ts new file mode 100644 index 00000000..67e2d4e5 --- /dev/null +++ b/tests/wire/news/feeds.test.ts @@ -0,0 +1,257 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("FeedsClient", () => { + test("listItems (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 0, + }, + total_count: 0, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }; + server + .mockEndpoint() + .get("/news/newsfeeds/123/items") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.feeds.listItems({ + newsfeed_id: "123", + }); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 0, + }, + total_count: 0, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }); + }); + + test("listItems (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/news/newsfeeds/newsfeed_id/items") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.feeds.listItems({ + newsfeed_id: "newsfeed_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { type: "newsfeed", id: "12312", name: "My Newsfeed", created_at: 1674917488, updated_at: 1674917488 }, + { type: "newsfeed", id: "12312", name: "My Newsfeed", created_at: 1674917488, updated_at: 1674917488 }, + ], + }; + server.mockEndpoint().get("/news/newsfeeds").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.news.feeds.list(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + id: "12312", + type: "newsfeed", + name: "My Newsfeed", + created_at: 1674917488, + updated_at: 1674917488, + }, + { + id: "12312", + type: "newsfeed", + name: "My Newsfeed", + created_at: 1674917488, + updated_at: 1674917488, + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/newsfeeds").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.news.feeds.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "72", + type: "newsfeed", + name: "Visitor Feed", + created_at: 1734537815, + updated_at: 1734537815, + }; + server + .mockEndpoint() + .get("/news/newsfeeds/123") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.feeds.find({ + newsfeed_id: "123", + }); + expect(response).toEqual({ + id: "72", + type: "newsfeed", + name: "Visitor Feed", + created_at: 1734537815, + updated_at: 1734537815, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/news/newsfeeds/newsfeed_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.feeds.find({ + newsfeed_id: "newsfeed_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/news/items.test.ts b/tests/wire/news/items.test.ts new file mode 100644 index 00000000..e95bc74e --- /dev/null +++ b/tests/wire/news/items.test.ts @@ -0,0 +1,620 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("ItemsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }; + server.mockEndpoint().get("/news/news_items").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.news.items.list(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/news_items").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.news.items.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["😆", "😅"], + newsfeed_assignments: [{ newsfeed_id: 53, published_at: 1664638214 }], + }; + const rawResponseBody = { + type: "news-item", + id: "33", + workspace_id: "this_is_an_id534_that_should_be_at_least_", + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 53, published_at: 1664638214 }], + labels: ["New", "Product", "Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😆", "😅"], + deliver_silently: true, + created_at: 1734537797, + updated_at: 1734537797, + }; + server + .mockEndpoint() + .post("/news/news_items") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.items.create({ + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + newsfeed_assignments: [ + { + newsfeed_id: 53, + published_at: 1664638214, + }, + ], + }); + expect(response).toEqual({ + type: "news-item", + id: "33", + workspace_id: "this_is_an_id534_that_should_be_at_least_", + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 53, + published_at: 1664638214, + }, + ], + labels: ["New", "Product", "Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + deliver_silently: true, + created_at: 1734537797, + updated_at: 1734537797, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/news/news_items") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.items.create({ + title: "title", + sender_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "news-item", + id: "34", + workspace_id: "this_is_an_id538_that_should_be_at_least_", + title: "We have news", + body: "

Hello there,

", + sender_id: 991267837, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 55, published_at: 1734537800 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍", "👍", "👍", "👍"], + deliver_silently: false, + created_at: 1734537800, + updated_at: 1734537800, + }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.news.items.find({ + news_item_id: 1, + }); + expect(response).toEqual({ + type: "news-item", + id: "34", + workspace_id: "this_is_an_id538_that_should_be_at_least_", + title: "We have news", + body: "

Hello there,

", + sender_id: 991267837, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 55, + published_at: 1734537800, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D", "\uD83D\uDC4D", "\uD83D\uDC4D", "\uD83D\uDC4D"], + deliver_silently: false, + created_at: 1734537800, + updated_at: 1734537800, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.news.items.find({ + news_item_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.news.items.find({ + news_item_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["😝", "😂"], + }; + const rawResponseBody = { + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😝", "😂"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.items.update({ + news_item_id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + }, + }); + expect(response).toEqual({ + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267848, + reactions: ["😝", "😂"], + }; + const rawResponseBody = { + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😝", "😂"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.items.update({ + news_item_id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267848, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + }, + }); + expect(response).toEqual({ + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.items.update({ + news_item_id: 1, + body: { + title: "title", + sender_id: 1, + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.items.update({ + news_item_id: 1, + body: { + title: "title", + sender_id: 1, + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "40", object: "news-item", deleted: true }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.news.items.delete({ + news_item_id: 1, + }); + expect(response).toEqual({ + id: "40", + object: "news-item", + deleted: true, + }); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.items.delete({ + news_item_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.news.items.delete({ + news_item_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/notes.test.ts b/tests/wire/notes.test.ts new file mode 100644 index 00000000..6082e324 --- /dev/null +++ b/tests/wire/notes.test.ts @@ -0,0 +1,527 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("NotesClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "type", + data: [ + { + type: "type", + id: "id", + created_at: 1, + contact: { type: "type", id: "id" }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: { image_url: "image_url" }, + team_priority_level: { primary_team_ids: [1, 1], secondary_team_ids: [1, 1] }, + }, + body: "body", + }, + { + type: "type", + id: "id", + created_at: 1, + contact: { type: "type", id: "id" }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: { image_url: "image_url" }, + team_priority_level: { primary_team_ids: [1, 1], secondary_team_ids: [1, 1] }, + }, + body: "body", + }, + ], + total_count: 1, + }; + server + .mockEndpoint({ once: false }) + .get("/contacts/contact_id/notes") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "type", + data: [ + { + type: "type", + id: "id", + created_at: 1, + contact: { + type: "type", + id: "id", + }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: { + image_url: "image_url", + }, + team_priority_level: { + primary_team_ids: [1, 1], + secondary_team_ids: [1, 1], + }, + }, + body: "body", + }, + { + type: "type", + id: "id", + created_at: 1, + contact: { + type: "type", + id: "id", + }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: { + image_url: "image_url", + }, + team_priority_level: { + primary_team_ids: [1, 1], + secondary_team_ids: [1, 1], + }, + }, + body: "body", + }, + ], + total_count: 1, + }; + const page = await client.notes.list({ + contact_id: "contact_id", + }); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint({ once: false }) + .get("/contacts/contact_id/notes") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.notes.list({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/123/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.notes.create({ + contact_id: "123", + body: "Hello", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/123/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.notes.create({ + contact_id: "123", + body: "Hello", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/123/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.notes.create({ + contact_id: "123", + body: "Hello", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "body" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.notes.create({ + contact_id: "contact_id", + body: "body", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "note", + id: "34", + created_at: 1733846617, + contact: { type: "contact", id: "6762f2591bb69f9f2193bc1f" }, + author: { + type: "admin", + id: "991267864", + name: "Ciaran346 Lee", + email: "admin346@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { image_url: "https://example.org/128Wash.jpg" }, + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

This is a note.

", + }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.notes.find({ + note_id: 1, + }); + expect(response).toEqual({ + type: "note", + id: "34", + created_at: 1733846617, + contact: { + type: "contact", + id: "6762f2591bb69f9f2193bc1f", + }, + author: { + type: "admin", + id: "991267864", + name: "Ciaran346 Lee", + email: "admin346@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + image_url: "https://example.org/128Wash.jpg", + }, + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

This is a note.

", + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.notes.find({ + note_id: 1, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.notes.find({ + note_id: 1, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/phoneCallRedirects.test.ts b/tests/wire/phoneCallRedirects.test.ts new file mode 100644 index 00000000..a81d3a78 --- /dev/null +++ b/tests/wire/phoneCallRedirects.test.ts @@ -0,0 +1,216 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("PhoneCallRedirectsClient", () => { + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + phone: "+353832345678", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { type: "phone_call_redirect", phone: "+1 1234567890" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.phoneCallRedirects.create({ + phone: "+353832345678", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "phone_call_redirect", + phone: "+1 1234567890", + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + phone: "+353832345678", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { type: "phone_call_redirect", phone: "+1 1234567890" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.phoneCallRedirects.create({ + phone: "+353832345678", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "phone_call_redirect", + phone: "+1 1234567890", + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + phone: "+353832345678", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { type: "phone_call_redirect", phone: "+1 1234567890" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.phoneCallRedirects.create({ + phone: "+353832345678", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "phone_call_redirect", + phone: "+1 1234567890", + }); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + phone: "+40241100100", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { type: "phone_call_redirect", phone: "+1 1234567890" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.phoneCallRedirects.create({ + phone: "+40241100100", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "phone_call_redirect", + phone: "+1 1234567890", + }); + }); + + test("create (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.phoneCallRedirects.create(undefined); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.phoneCallRedirects.create(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.phoneCallRedirects.create(undefined); + }).rejects.toThrow(Intercom.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/segments.test.ts b/tests/wire/segments.test.ts new file mode 100644 index 00000000..0639194d --- /dev/null +++ b/tests/wire/segments.test.ts @@ -0,0 +1,174 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("SegmentsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "segment.list", + segments: [ + { + type: "segment", + id: "6762f25c1bb69f9f2193bc22", + name: "John segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + { + type: "segment", + id: "6762f25c1bb69f9f2193bc23", + name: "Jane segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + ], + pages: { key: "value" }, + }; + server.mockEndpoint().get("/segments").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.segments.list({ + include_count: true, + }); + expect(response).toEqual({ + type: "segment.list", + segments: [ + { + type: "segment", + id: "6762f25c1bb69f9f2193bc22", + name: "John segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + { + type: "segment", + id: "6762f25c1bb69f9f2193bc23", + name: "Jane segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + ], + pages: { + key: "value", + }, + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/segments").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.segments.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "segment", + id: "6762f25f1bb69f9f2193bc26", + name: "John segment", + created_at: 1734537823, + updated_at: 1734537823, + person_type: "user", + count: 3, + }; + server.mockEndpoint().get("/segments/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.segments.find({ + segment_id: "123", + }); + expect(response).toEqual({ + type: "segment", + id: "6762f25f1bb69f9f2193bc26", + name: "John segment", + created_at: 1734537823, + updated_at: 1734537823, + person_type: "user", + count: 3, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/segments/segment_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.segments.find({ + segment_id: "segment_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/segments/segment_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.segments.find({ + segment_id: "segment_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/subscriptionTypes.test.ts b/tests/wire/subscriptionTypes.test.ts new file mode 100644 index 00000000..dc2a94b1 --- /dev/null +++ b/tests/wire/subscriptionTypes.test.ts @@ -0,0 +1,92 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("SubscriptionTypesClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "subscription", + id: "135", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_out", + content_types: ["email"], + }, + ], + }; + server + .mockEndpoint() + .get("/subscription_types") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptionTypes.list(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "subscription", + id: "135", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_out", + content_types: ["email"], + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/subscription_types") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.subscriptionTypes.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/tags.test.ts b/tests/wire/tags.test.ts new file mode 100644 index 00000000..b31a212b --- /dev/null +++ b/tests/wire/tags.test.ts @@ -0,0 +1,1371 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("TagsClient", () => { + test("tagContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "123" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagContact (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/contact_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("tagContact (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("untagContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "tag", + id: "84", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/contacts/63a07ddf05a32042dffac965/tags/7522907") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagContact({ + contact_id: "63a07ddf05a32042dffac965", + tag_id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "84", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/tags/tag_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagContact({ + contact_id: "contact_id", + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("untagContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/tags/tag_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagContact({ + contact_id: "contact_id", + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("tagConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/conversations/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/conversations/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("tagConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("untagConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagConversation({ + conversation_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagConversation({ + conversation_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagConversation({ + conversation_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/tags/tag_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagConversation({ + conversation_id: "conversation_id", + tag_id: "tag_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("untagConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/tags/tag_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagConversation({ + conversation_id: "conversation_id", + tag_id: "tag_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "tag", + id: "102", + name: "Manual tag 1", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }; + server.mockEndpoint().get("/tags").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.tags.list(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "tag", + id: "102", + name: "Manual tag 1", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tags").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test" }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.create({ + name: "test", + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Independent" }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.create({ + name: "Independent", + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("create (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test", companies: [{ company_id: "123" }] }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.create({ + name: "test", + companies: [ + { + company_id: "123", + }, + ], + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("create (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test", users: [{ id: "123" }] }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.create({ + name: "test", + users: [ + { + id: "123", + }, + ], + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("create (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.create({ + name: "name", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("create (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.create({ + name: "name", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.create({ + name: "name", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "tag", + id: "113", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server.mockEndpoint().get("/tags/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.tags.find({ + tag_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "113", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tags/tag_id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.find({ + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/tags/tag_id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.find({ + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("delete (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().delete("/tags/123").respondWith().statusCode(200).build(); + + const response = await client.tags.delete({ + tag_id: "123", + }); + expect(response).toEqual(undefined); + }); + + test("delete (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/tags/tag_id").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.delete({ + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("delete (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/tags/tag_id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.delete({ + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("delete (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/tags/tag_id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tags.delete({ + tag_id: "tag_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("tagTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tickets/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tickets/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.tagTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("tagTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/ticket_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("tagTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/ticket_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.tagTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("untagTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagTicket({ + ticket_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagTicket({ + ticket_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tags.untagTicket({ + ticket_id: "64619700005694", + tag_id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("untagTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/tickets/ticket_id/tags/tag_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagTicket({ + ticket_id: "ticket_id", + tag_id: "tag_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("untagTicket (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/tickets/ticket_id/tags/tag_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tags.untagTicket({ + ticket_id: "ticket_id", + tag_id: "tag_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/teams.test.ts b/tests/wire/teams.test.ts new file mode 100644 index 00000000..d9706101 --- /dev/null +++ b/tests/wire/teams.test.ts @@ -0,0 +1,144 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("TeamsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "team.list", + teams: [ + { + type: "team", + id: "814865", + name: "Example Team", + admin_ids: [493881], + admin_priority_level: { primary_admin_ids: [493881], secondary_admin_ids: [814865] }, + assignment_limit: 10, + distribution_method: "round_robin", + }, + ], + }; + server.mockEndpoint().get("/teams").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.teams.list(); + expect(response).toEqual({ + type: "team.list", + teams: [ + { + type: "team", + id: "814865", + name: "Example Team", + admin_ids: [493881], + admin_priority_level: { + primary_admin_ids: [493881], + secondary_admin_ids: [814865], + }, + assignment_limit: 10, + distribution_method: "round_robin", + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/teams").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.teams.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "team", + id: "991267902", + name: "team 1", + admin_ids: [493881], + admin_priority_level: { primary_admin_ids: [493881], secondary_admin_ids: [814865] }, + assignment_limit: 10, + distribution_method: "round_robin", + }; + server.mockEndpoint().get("/teams/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.teams.find({ + team_id: "123", + }); + expect(response).toEqual({ + type: "team", + id: "991267902", + name: "team 1", + admin_ids: [493881], + admin_priority_level: { + primary_admin_ids: [493881], + secondary_admin_ids: [814865], + }, + assignment_limit: 10, + distribution_method: "round_robin", + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/teams/team_id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.teams.find({ + team_id: "team_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/teams/team_id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.teams.find({ + team_id: "team_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); +}); diff --git a/tests/wire/ticketStates.test.ts b/tests/wire/ticketStates.test.ts new file mode 100644 index 00000000..a510ca68 --- /dev/null +++ b/tests/wire/ticketStates.test.ts @@ -0,0 +1,504 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("TicketStatesClient", () => { + test("listTicketStates (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "ticket_state", + id: "8269", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8270", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8271", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8272", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8273", + category: "submitted", + internal_label: "Admin label 1", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8274", + category: "submitted", + internal_label: "Admin label 2", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + ], + }; + server.mockEndpoint().get("/ticket_states").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.ticketStates.listTicketStates(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "ticket_state", + id: "8269", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8270", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8271", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8272", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8273", + category: "submitted", + internal_label: "Admin label 1", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8274", + category: "submitted", + internal_label: "Admin label 2", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + ], + }); + }); + + test("listTicketStates (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ticket_states").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.ticketStates.listTicketStates(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/ticketTypes.test.ts b/tests/wire/ticketTypes.test.ts new file mode 100644 index 00000000..f1ec5429 --- /dev/null +++ b/tests/wire/ticketTypes.test.ts @@ -0,0 +1,689 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("TicketTypesClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "ticket_type", + id: "67", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id648_that_should_be_at_least_", + ticket_type_attributes: { type: "list" }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8321", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8322", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8323", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8324", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537866, + updated_at: 1734537866, + }, + ], + }; + server.mockEndpoint().get("/ticket_types").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.ticketTypes.list(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "ticket_type", + id: "67", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id648_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8321", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8322", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8323", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8324", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537866, + updated_at: 1734537866, + }, + ], + }); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ticket_types").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.ticketTypes.list(); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + name: "Customer Issue", + description: "Customer Report Template", + category: "Customer", + icon: "🎟️", + }; + const rawResponseBody = { + type: "ticket_type", + id: "70", + category: "Customer", + name: "Customer Issue", + description: "Customer Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id652_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { key: "value" }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8337", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8338", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8339", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8340", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537869, + updated_at: 1734537869, + }; + server + .mockEndpoint() + .post("/ticket_types") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.ticketTypes.create({ + name: "Customer Issue", + description: "Customer Report Template", + category: "Customer", + icon: "\uD83C\uDF9F\uFE0F", + }); + expect(response).toEqual({ + type: "ticket_type", + id: "70", + category: "Customer", + name: "Customer Issue", + description: "Customer Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id652_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { + key: "value", + }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8337", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8338", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8339", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8340", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537869, + updated_at: 1734537869, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/ticket_types").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.ticketTypes.create(undefined); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("get (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "ticket_type", + id: "72", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id656_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { key: "value" }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8353", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8354", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8355", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8356", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537870, + updated_at: 1734537870, + }; + server + .mockEndpoint() + .get("/ticket_types/ticket_type_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.ticketTypes.get({ + ticket_type_id: "ticket_type_id", + }); + expect(response).toEqual({ + type: "ticket_type", + id: "72", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id656_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { + key: "value", + }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8353", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8354", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8355", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8356", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537870, + updated_at: 1734537870, + }); + }); + + test("get (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ticket_types/ticket_type_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.ticketTypes.get({ + ticket_type_id: "ticket_type_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Bug Report 2" }; + const rawResponseBody = { + type: "ticket_type", + id: "74", + category: "Customer", + name: "Bug Report 2", + description: "Bug Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id660_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { key: "value" }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8369", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8370", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8371", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8372", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537873, + updated_at: 1734537874, + }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.ticketTypes.update({ + ticket_type_id: "ticket_type_id", + name: "Bug Report 2", + }); + expect(response).toEqual({ + type: "ticket_type", + id: "74", + category: "Customer", + name: "Bug Report 2", + description: "Bug Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id660_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + input_options: { + key: "value", + }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8369", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8370", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8371", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8372", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537873, + updated_at: 1734537874, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.ticketTypes.update({ + ticket_type_id: "ticket_type_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/ticketTypes/attributes.test.ts b/tests/wire/ticketTypes/attributes.test.ts new file mode 100644 index 00000000..0bd0e735 --- /dev/null +++ b/tests/wire/ticketTypes/attributes.test.ts @@ -0,0 +1,200 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("AttributesClient", () => { + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false, + }; + const rawResponseBody = { + type: "ticket_type_attribute", + id: "157", + workspace_id: "this_is_an_id640_that_should_be_at_least_", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + input_options: { multiline: false }, + order: 2, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: true, + visible_to_contacts: true, + default: false, + ticket_type_id: 63, + archived: false, + created_at: 1734537862, + updated_at: 1734537862, + }; + server + .mockEndpoint() + .post("/ticket_types/ticket_type_id/attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.ticketTypes.attributes.create({ + ticket_type_id: "ticket_type_id", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false, + }); + expect(response).toEqual({ + type: "ticket_type_attribute", + id: "157", + workspace_id: "this_is_an_id640_that_should_be_at_least_", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + input_options: { + multiline: false, + }, + order: 2, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: true, + visible_to_contacts: true, + default: false, + ticket_type_id: 63, + archived: false, + created_at: 1734537862, + updated_at: 1734537862, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name", description: "description", data_type: "string" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ticket_types/ticket_type_id/attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.ticketTypes.attributes.create({ + ticket_type_id: "ticket_type_id", + name: "name", + description: "description", + data_type: "string", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { description: "New Attribute Description" }; + const rawResponseBody = { + type: "ticket_type_attribute", + id: "162", + workspace_id: "this_is_an_id644_that_should_be_at_least_", + name: "name", + description: "New Attribute Description", + data_type: "string", + input_options: { key: "value" }, + order: 0, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: false, + ticket_type_id: 65, + archived: false, + created_at: 1734537864, + updated_at: 1734537864, + }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id/attributes/attribute_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.ticketTypes.attributes.update({ + ticket_type_id: "ticket_type_id", + attribute_id: "attribute_id", + description: "New Attribute Description", + }); + expect(response).toEqual({ + type: "ticket_type_attribute", + id: "162", + workspace_id: "this_is_an_id644_that_should_be_at_least_", + name: "name", + description: "New Attribute Description", + data_type: "string", + input_options: { + key: "value", + }, + order: 0, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: false, + ticket_type_id: 65, + archived: false, + created_at: 1734537864, + updated_at: 1734537864, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id/attributes/attribute_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.ticketTypes.attributes.update({ + ticket_type_id: "ticket_type_id", + attribute_id: "attribute_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tests/wire/tickets.test.ts b/tests/wire/tickets.test.ts new file mode 100644 index 00000000..928f3523 --- /dev/null +++ b/tests/wire/tickets.test.ts @@ -0,0 +1,3690 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("TicketsClient", () => { + test("reply (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { text: "Yes", uuid: "0df48b85-9a93-4c66-a167-753eff0baaec" }, + { text: "No", uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938" }, + ], + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { + text: "Yes", + uuid: "0df48b85-9a93-4c66-a167-753eff0baaec", + }, + { + text: "No", + uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938", + }, + ], + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2a41bb69f9f2193bc4c", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2a41bb69f9f2193bc4c", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }; + const rawResponseBody = { + type: "ticket_part", + id: "158", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537890, + updated_at: 1734537890, + author: { type: "admin", id: "991267948", name: "Ciaran423 Lee", email: "admin423@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.reply({ + ticket_id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "158", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537890, + updated_at: 1734537890, + author: { + type: "admin", + id: "991267948", + name: "Ciaran423 Lee", + email: "admin423@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("reply (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/ticket_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.reply({ + ticket_id: "ticket_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("reply (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/ticket_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.reply({ + ticket_id: "ticket_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("reply (9)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/ticket_id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.reply({ + ticket_id: "ticket_id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("create (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "1234", contacts: [{ id: "6762f2d81bb69f9f2193bc54" }] }; + const rawResponseBody = { + type: "ticket", + id: "626", + ticket_id: "33", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8481", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "88", + category: "Back-office", + name: "my-ticket-type-23", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id688_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537943, + updated_at: 1734537943, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f2d81bb69f9f2193bc54", external_id: "70" }], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537944, + updated_at: 1734537946, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "175", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537945, + updated_at: 1734537945, + author: { + type: "bot", + id: "991267999", + name: "Fin", + email: "operator+this_is_an_id688_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }; + server + .mockEndpoint() + .post("/tickets") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.create({ + ticket_type_id: "1234", + contacts: [ + { + id: "6762f2d81bb69f9f2193bc54", + }, + ], + }); + expect(response).toEqual({ + type: "ticket", + id: "626", + ticket_id: "33", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8481", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "88", + category: "Back-office", + name: "my-ticket-type-23", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id688_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537943, + updated_at: 1734537943, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2d81bb69f9f2193bc54", + external_id: "70", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537944, + updated_at: 1734537946, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "175", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537945, + updated_at: 1734537945, + author: { + type: "bot", + id: "991267999", + name: "Fin", + email: "operator+this_is_an_id688_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }); + }); + + test("create (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id", contacts: [{ id: "id" }, { id: "id" }] }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.create({ + ticket_type_id: "ticket_type_id", + contacts: [ + { + id: "id", + }, + { + id: "id", + }, + ], + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("enqueueCreateTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "1234", contacts: [{ id: "6762f2d81bb69f9f2193bc54" }] }; + const rawResponseBody = { + type: "job", + id: "20", + url: "https://api.intercom.io/jobs/status/20", + status: "pending", + resource_type: "ticket", + resource_id: "resource_id", + resource_url: "http://api.intercom.io/tickets/123", + }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.enqueueCreateTicket({ + ticket_type_id: "1234", + contacts: [ + { + id: "6762f2d81bb69f9f2193bc54", + }, + ], + }); + expect(response).toEqual({ + type: "job", + id: "20", + url: "https://api.intercom.io/jobs/status/20", + status: "pending", + resource_type: "ticket", + resource_id: "resource_id", + resource_url: "http://api.intercom.io/tickets/123", + }); + }); + + test("enqueueCreateTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id", contacts: [{ id: "id" }, { id: "id" }] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.enqueueCreateTicket({ + ticket_type_id: "ticket_type_id", + contacts: [ + { + id: "id", + }, + { + id: "id", + }, + ], + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("enqueueCreateTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id", contacts: [{ id: "id" }, { id: "id" }] }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.enqueueCreateTicket({ + ticket_type_id: "ticket_type_id", + contacts: [ + { + id: "id", + }, + { + id: "id", + }, + ], + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("get (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "ticket", + id: "631", + ticket_id: "38", + category: "Back-office", + ticket_attributes: { _default_title_: "attribute_value", _default_description_: { key: "value" } }, + ticket_state: { + type: "ticket_state", + id: "8537", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "95", + category: "Back-office", + name: "my-ticket-type-30", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id702_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537973, + updated_at: 1734537973, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2f61bb69f9f2193bc59", + external_id: "b16afa36-2637-4880-adee-a46d145bc27f", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537974, + updated_at: 1734537976, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "185", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537975, + updated_at: 1734537975, + author: { type: "admin", id: "991268047", name: "Ciaran509 Lee", email: "admin509@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }; + server.mockEndpoint().get("/tickets/ticket_id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.tickets.get({ + ticket_id: "ticket_id", + }); + expect(response).toEqual({ + type: "ticket", + id: "631", + ticket_id: "38", + category: "Back-office", + ticket_attributes: { + _default_title_: "attribute_value", + _default_description_: { + key: "value", + }, + }, + ticket_state: { + type: "ticket_state", + id: "8537", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "95", + category: "Back-office", + name: "my-ticket-type-30", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id702_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537973, + updated_at: 1734537973, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2f61bb69f9f2193bc59", + external_id: "b16afa36-2637-4880-adee-a46d145bc27f", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537974, + updated_at: 1734537976, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "185", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537975, + updated_at: 1734537975, + author: { + type: "admin", + id: "991268047", + name: "Ciaran509 Lee", + email: "admin509@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }); + }); + + test("get (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tickets/ticket_id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.tickets.get({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.update({ + ticket_id: "ticket_id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.update({ + ticket_id: "ticket_id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.update({ + ticket_id: "ticket_id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_state_id: "123" }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.update({ + ticket_id: "ticket_id", + ticket_state_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("update (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.update({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.BadRequestError); + }); + + test("update (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.update({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/tickets/ticket_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.update({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("deleteTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "632", object: "ticket", deleted: true }; + server + .mockEndpoint() + .delete("/tickets/ticket_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.tickets.deleteTicket({ + ticket_id: "ticket_id", + }); + expect(response).toEqual({ + id: "632", + object: "ticket", + deleted: true, + }); + }); + + test("deleteTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/tickets/ticket_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.deleteTicket({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("deleteTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/tickets/ticket_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.tickets.deleteTicket({ + ticket_id: "ticket_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "ticket.list", + tickets: [ + { + type: "ticket", + id: "633", + ticket_id: "40", + category: "Back-office", + ticket_attributes: { _default_title_: "attribute_value" }, + ticket_state: { + type: "ticket_state", + id: "8577", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "100", + category: "Back-office", + name: "my-ticket-type-35", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id712_that_should_be_at_least_", + ticket_type_attributes: { type: "list" }, + archived: false, + created_at: 1734537989, + updated_at: 1734537989, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f3061bb69f9f2193bc5b", + external_id: "9b913927-c084-4391-b1db-098341b5ffe3", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537990, + updated_at: 1734537992, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "188", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537991, + updated_at: 1734537991, + author: { + type: "admin", + id: "991268079", + name: "Ciaran539 Lee", + email: "admin539@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 1, + }, + }; + server + .mockEndpoint({ once: false }) + .post("/tickets/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + type: "ticket.list", + tickets: [ + { + type: "ticket", + id: "633", + ticket_id: "40", + category: "Back-office", + ticket_attributes: { + _default_title_: "attribute_value", + }, + ticket_state: { + type: "ticket_state", + id: "8577", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "100", + category: "Back-office", + name: "my-ticket-type-35", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id712_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + }, + archived: false, + created_at: 1734537989, + updated_at: 1734537989, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f3061bb69f9f2193bc5b", + external_id: "9b913927-c084-4391-b1db-098341b5ffe3", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537990, + updated_at: 1734537992, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "188", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537991, + updated_at: 1734537991, + author: { + type: "admin", + id: "991268079", + name: "Ciaran539 Lee", + email: "admin539@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 1, + }, + }; + const page = await client.tickets.search({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + + expect(expected.tickets).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.tickets).toEqual(nextPage.data); + }); +}); diff --git a/tests/wire/unstable/admins.test.ts b/tests/wire/unstable/admins.test.ts new file mode 100644 index 00000000..15a2ae87 --- /dev/null +++ b/tests/wire/unstable/admins.test.ts @@ -0,0 +1,644 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("AdminsClient", () => { + test("identifyAdmin", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin", + id: "991267459", + name: "Ciaran1 Lee", + email: "admin1@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/assets/default-avatars/admins/128.png", + }, + email_verified: true, + app: { + type: "app", + id_code: "this_is_an_id1_that_should_be_at_least_40", + name: "MyApp 1", + region: "US", + timezone: "America/Los_Angeles", + created_at: 1734537243, + identity_verification: false, + }, + }; + server.mockEndpoint().get("/me").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.admins.identifyAdmin(); + expect(response).toEqual({ + type: "admin", + id: "991267459", + name: "Ciaran1 Lee", + email: "admin1@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + has_inbox_seat: true, + team_ids: [814865], + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/assets/default-avatars/admins/128.png", + }, + email_verified: true, + app: { + type: "app", + id_code: "this_is_an_id1_that_should_be_at_least_40", + name: "MyApp 1", + region: "US", + timezone: "America/Los_Angeles", + created_at: 1734537243, + identity_verification: false, + }, + }); + }); + + test("setAwayAdmin (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true, away_status_reason_id: 12345 }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("setAwayAdmin (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("setAwayAdmin (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + expect(response).toEqual({ + type: "admin", + id: "991267460", + name: "Ciaran2 Lee", + email: "admin2@email.com", + job_title: "Associate", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("setAwayAdmin (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("setAwayAdmin (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("setAwayAdmin (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { away_mode_enabled: true, away_mode_reassign: true }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/admins/1/away") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.admins.setAwayAdmin({ + id: 1, + away_mode_enabled: true, + away_mode_reassign: true, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listActivityLogs (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "activity_log.list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 1, + }, + activity_logs: [ + { + id: "fca05814-4b72-4dce-ad4f-77a786a2c136", + performed_by: { type: "admin", id: "991267464", email: "admin5@email.com", ip: "127.0.0.1" }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "😌 On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + }, + created_at: 1734537253, + activity_type: "app_name_change", + activity_description: "Ciaran5 Lee changed your app name from before to after.", + }, + { + id: "f48c653b-0185-48ac-a276-23d11006bafb", + performed_by: { type: "admin", id: "991267464", email: "admin5@email.com", ip: "127.0.0.1" }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "😌 On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + }, + created_at: 1734537253, + activity_type: "message_state_change", + activity_description: + "Ciaran5 Lee changed your Initial message title message from Initial message title to Eventual message title.", + }, + ], + }; + server + .mockEndpoint() + .get("/admins/activity_logs") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.admins.listActivityLogs({ + created_at_after: "1677253093", + created_at_before: "1677861493", + }); + expect(response).toEqual({ + type: "activity_log.list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 1, + }, + activity_logs: [ + { + id: "fca05814-4b72-4dce-ad4f-77a786a2c136", + performed_by: { + type: "admin", + id: "991267464", + email: "admin5@email.com", + ip: "127.0.0.1", + }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "\uD83D\uDE0C On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + }, + created_at: 1734537253, + activity_type: "app_name_change", + activity_description: "Ciaran5 Lee changed your app name from before to after.", + }, + { + id: "f48c653b-0185-48ac-a276-23d11006bafb", + performed_by: { + type: "admin", + id: "991267464", + email: "admin5@email.com", + ip: "127.0.0.1", + }, + metadata: { + sign_in_method: "email_password", + external_id: "f3b87a2e09d514c6c2e79b9a", + away_mode: true, + away_status_reason: "\uD83D\uDE0C On a break", + reassign_conversations: false, + source: "admin update from web - Admin id: 93", + update_by: 93, + update_by_name: "Joe Example", + conversation_assignment_limit: 15, + ticket_assignment_limit: 20, + }, + created_at: 1734537253, + activity_type: "message_state_change", + activity_description: + "Ciaran5 Lee changed your Initial message title message from Initial message title to Eventual message title.", + }, + ], + }); + }); + + test("listActivityLogs (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/admins/activity_logs") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.admins.listActivityLogs({ + created_at_after: "created_at_after", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listAdmins (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin.list", + admins: [ + { + type: "admin", + id: "991267466", + name: "Ciaran7 Lee", + email: "admin7@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + ], + }; + server.mockEndpoint().get("/admins").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.admins.listAdmins(); + expect(response).toEqual({ + type: "admin.list", + admins: [ + { + type: "admin", + id: "991267466", + name: "Ciaran7 Lee", + email: "admin7@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + ], + }); + }); + + test("listAdmins (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/admins").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.admins.listAdmins(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveAdmin (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "admin", + id: "991267468", + name: "Ciaran9 Lee", + email: "admin9@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.admins.retrieveAdmin({ + id: 1, + }); + expect(response).toEqual({ + type: "admin", + id: "991267468", + name: "Ciaran9 Lee", + email: "admin9@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }); + }); + + test("retrieveAdmin (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.admins.retrieveAdmin({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveAdmin (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/admins/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.admins.retrieveAdmin({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/aiContent.test.ts b/tests/wire/unstable/aiContent.test.ts new file mode 100644 index 00000000..4c0c8a22 --- /dev/null +++ b/tests/wire/unstable/aiContent.test.ts @@ -0,0 +1,878 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("AiContentClient", () => { + test("listContentImportSources (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + total_count: 3, + data: [ + { + type: "content_import_source", + id: 33, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/1", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 34, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/2", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 35, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/3", + created_at: 1734537259, + updated_at: 1734537259, + }, + ], + }; + server + .mockEndpoint() + .get("/ai/content_import_sources") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.listContentImportSources(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + total_count: 3, + data: [ + { + type: "content_import_source", + id: 33, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/1", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 34, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/2", + created_at: 1734537259, + updated_at: 1734537259, + }, + { + type: "content_import_source", + id: 35, + last_synced_at: 1734537259, + sync_behavior: "automatic", + status: "active", + url: "https://support.example.com/us/3", + created_at: 1734537259, + updated_at: 1734537259, + }, + ], + }); + }); + + test("listContentImportSources (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/content_import_sources") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.listContentImportSources(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "https://www.example.com" }; + const rawResponseBody = { + type: "content_import_source", + id: 36, + last_synced_at: 1734537261, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537261, + updated_at: 1734537261, + }; + server + .mockEndpoint() + .post("/ai/content_import_sources") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.createContentImportSource({ + url: "https://www.example.com", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 36, + last_synced_at: 1734537261, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537261, + updated_at: 1734537261, + }); + }); + + test("createContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "url" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ai/content_import_sources") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.createContentImportSource({ + url: "url", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "content_import_source", + id: 38, + last_synced_at: 1734537265, + sync_behavior: "api", + status: "active", + url: "https://support.example.com/us/5", + created_at: 1734537265, + updated_at: 1734537265, + }; + server + .mockEndpoint() + .get("/ai/content_import_sources/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.getContentImportSource({ + id: "id", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 38, + last_synced_at: 1734537265, + sync_behavior: "api", + status: "active", + url: "https://support.example.com/us/5", + created_at: 1734537265, + updated_at: 1734537265, + }); + }); + + test("getContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/content_import_sources/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.getContentImportSource({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "https://www.example.com" }; + const rawResponseBody = { + type: "content_import_source", + id: 39, + last_synced_at: 1734537267, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537267, + updated_at: 1734537267, + }; + server + .mockEndpoint() + .put("/ai/content_import_sources/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.updateContentImportSource({ + id: "id", + sync_behavior: "api", + url: "https://www.example.com", + }); + expect(response).toEqual({ + type: "content_import_source", + id: 39, + last_synced_at: 1734537267, + sync_behavior: "api", + status: "active", + url: "https://www.example.com", + created_at: 1734537267, + updated_at: 1734537267, + }); + }); + + test("updateContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { sync_behavior: "api", url: "url" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ai/content_import_sources/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.updateContentImportSource({ + id: "id", + sync_behavior: "api", + url: "url", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteContentImportSource (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().delete("/ai/content_import_sources/id").respondWith().statusCode(200).build(); + + const response = await client.unstable.aiContent.deleteContentImportSource({ + id: "id", + }); + expect(response).toEqual(undefined); + }); + + test("deleteContentImportSource (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/ai/content_import_sources/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.deleteContentImportSource({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listExternalPages (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + total_count: 3, + data: [ + { + type: "external_page", + id: "19", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/3", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 42, + external_id: "3", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "18", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/2", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 41, + external_id: "2", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "17", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/1", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 40, + external_id: "1", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + ], + }; + server.mockEndpoint().get("/ai/external_pages").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.aiContent.listExternalPages(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + total_count: 3, + data: [ + { + type: "external_page", + id: "19", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/3", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 42, + external_id: "3", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "18", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/2", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 41, + external_id: "2", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + { + type: "external_page", + id: "17", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/1", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 40, + external_id: "1", + created_at: 1734537269, + updated_at: 1734537269, + last_ingested_at: 1734537269, + }, + ], + }); + }); + + test("listExternalPages (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ai/external_pages").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.aiContent.listExternalPages(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Test", + html: "

Test

", + url: "https://www.example.com", + locale: "en", + source_id: 44, + external_id: "abc1234", + }; + const rawResponseBody = { + type: "external_page", + id: "21", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 44, + external_id: "abc1234", + created_at: 1734537273, + updated_at: 1734537274, + last_ingested_at: 1734537274, + }; + server + .mockEndpoint() + .post("/ai/external_pages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.createExternalPage({ + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 44, + external_id: "abc1234", + }); + expect(response).toEqual({ + type: "external_page", + id: "21", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 44, + external_id: "abc1234", + created_at: 1734537273, + updated_at: 1734537274, + last_ingested_at: 1734537274, + }); + }); + + test("createExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", html: "html", locale: "en", source_id: 1, external_id: "external_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ai/external_pages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.createExternalPage({ + title: "title", + html: "html", + source_id: 1, + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "external_page", + id: "23", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/6", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 46, + external_id: "5", + created_at: 1734537278, + updated_at: 1734537278, + last_ingested_at: 1734537278, + }; + server + .mockEndpoint() + .get("/ai/external_pages/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.getExternalPage({ + id: "id", + }); + expect(response).toEqual({ + type: "external_page", + id: "23", + title: "My External Content", + html: "

Hello world

This is external content

", + url: "https://support.example.com/us/6", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 46, + external_id: "5", + created_at: 1734537278, + updated_at: 1734537278, + last_ingested_at: 1734537278, + }); + }); + + test("getExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/ai/external_pages/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.getExternalPage({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Test", + html: "

Test

", + url: "https://www.example.com", + locale: "en", + source_id: 47, + external_id: "5678", + }; + const rawResponseBody = { + type: "external_page", + id: "24", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 47, + external_id: "5678", + created_at: 1734537280, + updated_at: 1734537281, + last_ingested_at: 1734537281, + }; + server + .mockEndpoint() + .put("/ai/external_pages/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.updateExternalPage({ + id: "id", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + source_id: 47, + external_id: "5678", + }); + expect(response).toEqual({ + type: "external_page", + id: "24", + title: "Test", + html: "

Test

", + url: "https://www.example.com", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 47, + external_id: "5678", + created_at: 1734537280, + updated_at: 1734537281, + last_ingested_at: 1734537281, + }); + }); + + test("updateExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", html: "html", url: "url", locale: "en", source_id: 1 }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ai/external_pages/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.updateExternalPage({ + id: "id", + title: "title", + html: "html", + url: "url", + source_id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteExternalPage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "external_page", + id: "22", + title: "My External Content", + html: "", + url: "https://support.example.com/us/5", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 45, + external_id: "4", + created_at: 1734537276, + updated_at: 1734537276, + last_ingested_at: 1734537276, + }; + server + .mockEndpoint() + .delete("/ai/external_pages/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.aiContent.deleteExternalPage({ + id: "id", + }); + expect(response).toEqual({ + type: "external_page", + id: "22", + title: "My External Content", + html: "", + url: "https://support.example.com/us/5", + ai_agent_availability: true, + ai_copilot_availability: true, + fin_availability: true, + locale: "en", + source_id: 45, + external_id: "4", + created_at: 1734537276, + updated_at: 1734537276, + last_ingested_at: 1734537276, + }); + }); + + test("deleteExternalPage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/ai/external_pages/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.aiContent.deleteExternalPage({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/articles.test.ts b/tests/wire/unstable/articles.test.ts new file mode 100644 index 00000000..20562566 --- /dev/null +++ b/tests/wire/unstable/articles.test.ts @@ -0,0 +1,2141 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("ArticlesClient", () => { + test("listArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "article", + id: "39", + workspace_id: "this_is_an_id64_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267492, + state: "published", + created_at: 1734537283, + updated_at: 1734537283, + url: "http://help-center.test/myapp-64/en/articles/39-this-is-the-article-title", + parent_id: 143, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + }; + server.mockEndpoint().get("/articles").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.articles.listArticles(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "article", + id: "39", + workspace_id: "this_is_an_id64_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267492, + state: "published", + created_at: 1734537283, + updated_at: 1734537283, + url: "http://help-center.test/myapp-64/en/articles/39-this-is-the-article-title", + parent_id: 143, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + }); + }); + + test("listArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/articles").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.listArticles(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { + statistics: { + type: "article_statistics", + views: 1, + conversions: 1, + reactions: 1, + happy_reaction_percentage: 1.1, + neutral_reaction_percentage: 1.1, + sad_reaction_percentage: 1.1, + }, + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }; + server + .mockEndpoint() + .post("/articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.articles.createArticle({ + key: "value", + }); + expect(response).toEqual({ + statistics: { + type: "article_statistics", + views: 1, + conversions: 1, + reactions: 1, + happy_reaction_percentage: 1.1, + neutral_reaction_percentage: 1.1, + sad_reaction_percentage: 1.1, + }, + type: "article", + id: "id", + workspace_id: "workspace_id", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + parent_id: 1, + parent_ids: [1, 1], + parent_type: "parent_type", + default_locale: "default_locale", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bg: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + bs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ca: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + cs: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + da: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + de: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + el: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + en: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + es: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + et: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + fr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + he: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + hu: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + id: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + it: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ja: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ko: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + lv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + mn: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nb: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + nl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + pt: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ro: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + ru: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sl: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + sv: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + tr: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + vi: { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "pt-BR": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-CN": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + "zh-TW": { + type: "article_content", + title: "title", + description: "description", + body: "body", + author_id: 1, + state: "published", + created_at: 1, + updated_at: 1, + url: "url", + }, + }, + }); + }); + + test("createArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.articles.createArticle({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.articles.createArticle({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "article", + id: "45", + workspace_id: "this_is_an_id74_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267502, + state: "published", + created_at: 1734537292, + updated_at: 1734537292, + url: "http://help-center.test/myapp-74/en/articles/45-this-is-the-article-title", + parent_id: 148, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.articles.retrieveArticle({ + id: 1, + }); + expect(response).toEqual({ + type: "article", + id: "45", + workspace_id: "this_is_an_id74_that_should_be_at_least_4", + title: "This is the article title", + description: "", + body: "", + author_id: 991267502, + state: "published", + created_at: 1734537292, + updated_at: 1734537292, + url: "http://help-center.test/myapp-74/en/articles/45-this-is-the-article-title", + parent_id: 148, + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + translated_content: { + type: "article_translated_content", + ar: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bg: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + bs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ca: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + cs: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + da: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + de: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + el: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + en: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + es: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + et: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + fr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + he: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + hu: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + id: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + it: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ja: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ko: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + lv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + mn: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nb: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + nl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + pt: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ro: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + ru: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sl: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + sv: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + tr: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + vi: { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "pt-BR": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-CN": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + "zh-TW": { + type: "article_content", + title: "How to create a new article", + description: "This article will show you how to create a new article.", + body: "This is the body of the article.", + author_id: 1, + state: "published", + created_at: 1663597223, + updated_at: 1663597260, + url: "http://intercom.test/help/en/articles/3-default-language", + }, + }, + statistics: { + type: "article_statistics", + views: 0, + conversions: 0, + reactions: 0, + happy_reaction_percentage: 0, + neutral_reaction_percentage: 0, + sad_reaction_percentage: 0, + }, + }); + }); + + test("retrieveArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.retrieveArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/articles/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.retrieveArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "51", object: "article", deleted: true }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.articles.deleteArticle({ + id: 1, + }); + expect(response).toEqual({ + id: "51", + object: "article", + deleted: true, + }); + }); + + test("deleteArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.deleteArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/articles/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.deleteArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("searchArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + total_count: 1, + data: { + articles: [ + { + type: "article", + id: "55", + workspace_id: "this_is_an_id92_that_should_be_at_least_4", + title: "Title 1", + description: "", + body: "", + author_id: 991267521, + state: "draft", + created_at: 1734537306, + updated_at: 1734537306, + url: "http://intercom.test/help/en/articles/3-default-language", + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + highlights: [{ article_id: "123" }], + }, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + }; + server.mockEndpoint().get("/articles/search").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.articles.searchArticles({ + phrase: "Getting started", + state: "published", + help_center_id: 1, + highlight: true, + }); + expect(response).toEqual({ + type: "list", + total_count: 1, + data: { + articles: [ + { + type: "article", + id: "55", + workspace_id: "this_is_an_id92_that_should_be_at_least_4", + title: "Title 1", + description: "", + body: "", + author_id: 991267521, + state: "draft", + created_at: 1734537306, + updated_at: 1734537306, + url: "http://intercom.test/help/en/articles/3-default-language", + parent_ids: [18, 19], + parent_type: "collection", + default_locale: "en", + }, + ], + highlights: [ + { + article_id: "123", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + }); + }); + + test("searchArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/articles/search").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.articles.searchArticles(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/awayStatusReasons.test.ts b/tests/wire/unstable/awayStatusReasons.test.ts new file mode 100644 index 00000000..f0416817 --- /dev/null +++ b/tests/wire/unstable/awayStatusReasons.test.ts @@ -0,0 +1,74 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("AwayStatusReasonsClient", () => { + test("listAwayStatusReasons (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = [ + { + type: "away_status_reason", + id: "id", + label: "On a break", + emoji: "☕", + order: 1, + deleted: false, + created_at: 1734537243, + updated_at: 1734537243, + }, + ]; + server + .mockEndpoint() + .get("/away_status_reasons") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.awayStatusReasons.listAwayStatusReasons(); + expect(response).toEqual([ + { + type: "away_status_reason", + id: "id", + label: "On a break", + emoji: "\u2615", + order: 1, + deleted: false, + created_at: 1734537243, + updated_at: 1734537243, + }, + ]); + }); + + test("listAwayStatusReasons (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/away_status_reasons") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.awayStatusReasons.listAwayStatusReasons(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/brands.test.ts b/tests/wire/unstable/brands.test.ts new file mode 100644 index 00000000..5dfe7df0 --- /dev/null +++ b/tests/wire/unstable/brands.test.ts @@ -0,0 +1,162 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("BrandsClient", () => { + test("listBrands (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "brand", + id: "tlkp1d91", + name: "Default Brand", + is_default: true, + created_at: 1673778600, + updated_at: 1711031100, + help_center_id: "11", + default_address_settings_id: "13", + }, + { + type: "brand", + id: "3", + name: "Premium Brand", + is_default: false, + created_at: 1686387300, + updated_at: 1709229600, + help_center_id: "10", + default_address_settings_id: "15", + }, + ], + }; + server.mockEndpoint().get("/brands").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.brands.listBrands(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "brand", + id: "tlkp1d91", + name: "Default Brand", + is_default: true, + created_at: 1673778600, + updated_at: 1711031100, + help_center_id: "11", + default_address_settings_id: "13", + }, + { + type: "brand", + id: "3", + name: "Premium Brand", + is_default: false, + created_at: 1686387300, + updated_at: 1709229600, + help_center_id: "10", + default_address_settings_id: "15", + }, + ], + }); + }); + + test("listBrands (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/brands").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.brands.listBrands(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveBrand (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "brand", + id: "15", + name: "Premium Brand", + is_default: false, + created_at: 1686387300, + updated_at: 1709229600, + help_center_id: "20", + default_address_settings_id: "15", + }; + server.mockEndpoint().get("/brands/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.brands.retrieveBrand({ + id: "id", + }); + expect(response).toEqual({ + type: "brand", + id: "15", + name: "Premium Brand", + is_default: false, + created_at: 1686387300, + updated_at: 1709229600, + help_center_id: "20", + default_address_settings_id: "15", + }); + }); + + test("retrieveBrand (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/brands/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.brands.retrieveBrand({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveBrand (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/brands/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.brands.retrieveBrand({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/calls.test.ts b/tests/wire/unstable/calls.test.ts new file mode 100644 index 00000000..4840a470 --- /dev/null +++ b/tests/wire/unstable/calls.test.ts @@ -0,0 +1,758 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("CallsClient", () => { + test("listCalls (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 25, + total_pages: 0, + }, + }; + server.mockEndpoint().get("/calls").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.calls.listCalls({ + page: 1, + per_page: 1, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 25, + total_pages: 0, + }, + }); + }); + + test("listCalls (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/calls").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.calls.listCalls(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("showCall (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: 1734537437, + answered_at: 1734537440, + ended_at: 1734537530, + created_at: 1734537437, + updated_at: 1734537531, + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "answered", + phone: "+15551234567", + fin_recording_url: "https://api.intercom.io/calls/124/recording", + fin_transcription_url: "https://api.intercom.io/calls/124/transcript", + }; + server.mockEndpoint().get("/calls/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.calls.showCall({ + id: "id", + }); + expect(response).toEqual({ + type: "call", + id: "123", + conversation_id: "456", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: 1734537437, + answered_at: 1734537440, + ended_at: 1734537530, + created_at: 1734537437, + updated_at: 1734537531, + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "answered", + phone: "+15551234567", + fin_recording_url: "https://api.intercom.io/calls/124/recording", + fin_transcription_url: "https://api.intercom.io/calls/124/transcript", + }); + }); + + test("showCall (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/calls/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.calls.showCall({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("showCall (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/calls/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.calls.showCall({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("showCallRecording (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().get("/calls/id/recording").respondWith().statusCode(200).build(); + + const response = await client.unstable.calls.showCallRecording({ + id: "id", + }); + expect(response).toEqual(undefined); + }); + + test("showCallRecording (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/calls/id/recording") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.showCallRecording({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("showCallRecording (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/calls/id/recording") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.showCallRecording({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listCallsWithTranscripts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["64619700005694", "64619700005695"] }; + const rawResponseBody = { + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "64619700005694", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + transcript: [{ key: "value" }], + transcript_status: "completed", + }, + ], + }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.calls.listCallsWithTranscripts({ + conversation_ids: ["64619700005694", "64619700005695"], + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "call", + id: "123", + conversation_id: "64619700005694", + admin_id: "789", + contact_id: "6762f0dd1bb69f9f2193bb83", + state: "completed", + initiated_at: "2024-01-15T09:30:00Z", + answered_at: "2024-01-15T09:30:00Z", + ended_at: "2024-01-15T09:30:00Z", + created_at: "2024-01-15T09:30:00Z", + updated_at: "2024-01-15T09:30:00Z", + recording_url: "https://api.intercom.io/calls/123/recording", + transcription_url: "https://api.intercom.io/calls/123/transcript", + call_type: "phone", + direction: "outbound", + ended_reason: "completed", + phone: "+15551234567", + fin_recording_url: "fin_recording_url", + fin_transcription_url: "fin_transcription_url", + transcript: [ + { + key: "value", + }, + ], + transcript_status: "completed", + }, + ], + }); + }); + + test("listCallsWithTranscripts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["conversation_ids", "conversation_ids"] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.listCallsWithTranscripts({ + conversation_ids: ["conversation_ids", "conversation_ids"], + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("listCallsWithTranscripts (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { conversation_ids: ["conversation_ids", "conversation_ids"] }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/calls/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.listCallsWithTranscripts({ + conversation_ids: ["conversation_ids", "conversation_ids"], + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("registerFinVoiceCall (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { phone_number: "+1234567890", call_id: "call-123-abc" }; + const rawResponseBody = { + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [{ key: "value" }], + call_summary: "Customer called about billing issue...", + intent: [{ key: "value" }], + }; + server + .mockEndpoint() + .post("/fin_voice/register") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.calls.registerFinVoiceCall({ + phone_number: "+1234567890", + call_id: "call-123-abc", + }); + expect(response).toEqual({ + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [ + { + key: "value", + }, + ], + call_summary: "Customer called about billing issue...", + intent: [ + { + key: "value", + }, + ], + }); + }); + + test("registerFinVoiceCall (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/fin_voice/register") + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.registerFinVoiceCall(undefined); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("registerFinVoiceCall (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/fin_voice/register") + .respondWith() + .statusCode(409) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.registerFinVoiceCall(undefined); + }).rejects.toThrow(Intercom.unstable.ConflictError); + }); + + test("collectFinVoiceCallById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [{ key: "value" }], + call_summary: "Customer called about billing issue...", + intent: [{ key: "value" }], + }; + server + .mockEndpoint() + .get("/fin_voice/collect/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.calls.collectFinVoiceCallById({ + id: 1, + }); + expect(response).toEqual({ + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [ + { + key: "value", + }, + ], + call_summary: "Customer called about billing issue...", + intent: [ + { + key: "value", + }, + ], + }); + }); + + test("collectFinVoiceCallById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/fin_voice/collect/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.collectFinVoiceCallById({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("collectFinVoiceCallByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [{ key: "value" }], + call_summary: "Customer called about billing issue...", + intent: [{ key: "value" }], + }; + server + .mockEndpoint() + .get("/fin_voice/external_id/external_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.calls.collectFinVoiceCallByExternalId({ + external_id: "external_id", + }); + expect(response).toEqual({ + id: 12345, + app_id: 12345, + user_phone_number: "+1234567890", + status: "registered", + intercom_call_id: "1234", + external_call_id: "call-123-abc", + intercom_conversation_id: "5678", + call_transcript: [ + { + key: "value", + }, + ], + call_summary: "Customer called about billing issue...", + intent: [ + { + key: "value", + }, + ], + }); + }); + + test("collectFinVoiceCallByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/fin_voice/external_id/external_id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.collectFinVoiceCallByExternalId({ + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("collectFinVoiceCallByPhoneNumber (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "error.list", + request_id: "f93ecfa8-d08a-4325-8694-89aeb89c8f85", + errors: [{ code: "unauthorized", message: "Access Token Invalid", field: "email" }], + }; + server + .mockEndpoint() + .get("/fin_voice/phone_number/phone_number") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.calls.collectFinVoiceCallByPhoneNumber({ + phone_number: "phone_number", + }); + expect(response).toEqual({ + type: "error.list", + request_id: "f93ecfa8-d08a-4325-8694-89aeb89c8f85", + errors: [ + { + code: "unauthorized", + message: "Access Token Invalid", + field: "email", + }, + ], + }); + }); + + test("collectFinVoiceCallByPhoneNumber (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/fin_voice/phone_number/phone_number") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.collectFinVoiceCallByPhoneNumber({ + phone_number: "phone_number", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("collectFinVoiceCallByPhoneNumber (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/fin_voice/phone_number/phone_number") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.calls.collectFinVoiceCallByPhoneNumber({ + phone_number: "phone_number", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/companies.test.ts b/tests/wire/unstable/companies.test.ts new file mode 100644 index 00000000..646e1411 --- /dev/null +++ b/tests/wire/unstable/companies.test.ts @@ -0,0 +1,2011 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("CompaniesClient", () => { + test("retrieveCompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 15, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f07a1bb69f9f2193baea", + name: "IntercomQATest1", + app_id: "this_is_an_id153_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537338, + created_at: 1734537338, + updated_at: 1734537338, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { key: "value" }, + tags: { type: "tag.list" }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { type: "note.list" }, + }, + ], + }; + server.mockEndpoint().get("/companies").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.companies.retrieveCompany({ + name: "my company", + company_id: "12345", + tag_id: "678910", + segment_id: "98765", + page: 1, + per_page: 1, + }); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 15, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f07a1bb69f9f2193baea", + name: "IntercomQATest1", + app_id: "this_is_an_id153_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537338, + created_at: 1734537338, + updated_at: 1734537338, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + }, + }, + ], + }); + }); + + test("retrieveCompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/companies").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.retrieveCompany(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveCompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/companies").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.retrieveCompany(); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("createOrUpdateCompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { + type: "company", + id: "id", + name: "name", + app_id: "app_id", + plan: { type: "type", id: "id", name: "name" }, + company_id: "company_id", + remote_created_at: 1, + created_at: 1, + updated_at: 1, + last_request_at: 1, + size: 1, + website: "website", + industry: "industry", + monthly_spend: 1, + session_count: 1, + user_count: 1, + custom_attributes: { custom_attributes: "custom_attributes" }, + tags: { type: "tag.list", tags: [{ key: "value" }, { key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + type: "segment", + id: "id", + name: "name", + created_at: 1, + updated_at: 1, + person_type: "contact", + count: 1, + }, + { + type: "segment", + id: "id", + name: "name", + created_at: 1, + updated_at: 1, + person_type: "contact", + count: 1, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "type", + id: "id", + created_at: 1, + company: { type: "type", id: "id" }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: "avatar", + team_priority_level: {}, + }, + body: "body", + }, + { + type: "type", + id: "id", + created_at: 1, + company: { type: "type", id: "id" }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: "avatar", + team_priority_level: {}, + }, + body: "body", + }, + ], + }, + }; + server + .mockEndpoint() + .post("/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.createOrUpdateCompany({ + key: "value", + }); + expect(response).toEqual({ + type: "company", + id: "id", + name: "name", + app_id: "app_id", + plan: { + type: "type", + id: "id", + name: "name", + }, + company_id: "company_id", + remote_created_at: 1, + created_at: 1, + updated_at: 1, + last_request_at: 1, + size: 1, + website: "website", + industry: "industry", + monthly_spend: 1, + session_count: 1, + user_count: 1, + custom_attributes: { + custom_attributes: "custom_attributes", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + type: "segment", + id: "id", + name: "name", + created_at: 1, + updated_at: 1, + person_type: "contact", + count: 1, + }, + { + type: "segment", + id: "id", + name: "name", + created_at: 1, + updated_at: 1, + person_type: "contact", + count: 1, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "type", + id: "id", + created_at: 1, + company: { + type: "type", + id: "id", + }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: "avatar", + team_priority_level: {}, + }, + body: "body", + }, + { + type: "type", + id: "id", + created_at: 1, + company: { + type: "type", + id: "id", + }, + author: { + type: "type", + id: "id", + name: "name", + email: "email", + job_title: "job_title", + away_mode_enabled: true, + away_mode_reassign: true, + away_status_reason_id: 1, + has_inbox_seat: true, + team_ids: [1, 1], + avatar: "avatar", + team_priority_level: {}, + }, + body: "body", + }, + ], + }, + }); + }); + + test("createOrUpdateCompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.createOrUpdateCompany({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createOrUpdateCompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.createOrUpdateCompany({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("RetrieveACompanyById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f07f1bb69f9f2193baf5", + name: "company1", + app_id: "this_is_an_id159_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537343, + created_at: 1734537343, + updated_at: 1734537343, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.retrieveACompanyById({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "company", + id: "6762f07f1bb69f9f2193baf5", + name: "company1", + app_id: "this_is_an_id159_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537343, + created_at: 1734537343, + updated_at: 1734537343, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("RetrieveACompanyById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/companies/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.retrieveACompanyById({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("RetrieveACompanyById (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/companies/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.retrieveACompanyById({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("UpdateCompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .put("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.updateCompany({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "company", + id: "6762f0841bb69f9f2193baff", + name: "company2", + app_id: "this_is_an_id165_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537348, + created_at: 1734537348, + updated_at: 1734537348, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("UpdateCompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().put("/companies/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.updateCompany({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("UpdateCompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().put("/companies/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.updateCompany({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteCompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "6762f0881bb69f9f2193bb09", object: "company", deleted: true }; + server + .mockEndpoint() + .delete("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.deleteCompany({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + id: "6762f0881bb69f9f2193bb09", + object: "company", + deleted: true, + }); + }); + + test("deleteCompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/companies/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.deleteCompany({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteCompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/companies/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.deleteCompany({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("ListAttachedContacts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", total_count: 100, has_more: true }, + notes: { url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", total_count: 100, has_more: true }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 50, + total_pages: 0, + }, + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632/contacts") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.listAttachedContacts({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", + total_count: 100, + has_more: true, + }, + notes: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + total_count: 100, + has_more: true, + }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 50, + total_pages: 0, + }, + }); + }); + + test("ListAttachedContacts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/companies/id/contacts") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.listAttachedContacts({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("ListAttachedContacts (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/id/contacts") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.listAttachedContacts({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("ListAttachedSegmentsForCompanies (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "segment", + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + person_type: "contact", + count: 3, + }, + ], + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632/segments") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.listAttachedSegmentsForCompanies({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "segment", + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + person_type: "contact", + count: 3, + }, + ], + }); + }); + + test("ListAttachedSegmentsForCompanies (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/companies/id/segments") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.listAttachedSegmentsForCompanies({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("ListAttachedSegmentsForCompanies (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/id/segments") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.listAttachedSegmentsForCompanies({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listAllCompanies (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 15, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f0941bb69f9f2193bb25", + name: "IntercomQATest1", + app_id: "this_is_an_id189_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537364, + created_at: 1734537364, + updated_at: 1734537364, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { key: "value" }, + tags: { type: "tag.list" }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { type: "note.list" }, + }, + ], + }; + server.mockEndpoint().post("/companies/list").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.companies.listAllCompanies({ + page: 1, + per_page: 1, + order: "desc", + }); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 15, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "company", + id: "6762f0941bb69f9f2193bb25", + name: "IntercomQATest1", + app_id: "this_is_an_id189_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537364, + created_at: 1734537364, + updated_at: 1734537364, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + }, + }, + ], + }); + }); + + test("listAllCompanies (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/companies/list").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.listAllCompanies(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("scrollOverAllCompanies (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "company", + id: "6762f0971bb69f9f2193bb2b", + name: "IntercomQATest1", + app_id: "this_is_an_id193_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537367, + created_at: 1734537367, + updated_at: 1734537367, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { key: "value" }, + tags: { type: "tag.list" }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { type: "note.list" }, + }, + ], + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 2, + total_pages: 13, + }, + total_count: 100, + scroll_param: "69352cd2-ab5b-42ac-b004-a13d4e55e9b0", + }; + server.mockEndpoint().get("/companies/scroll").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.companies.scrollOverAllCompanies({ + scroll_param: "scroll_param", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "company", + id: "6762f0971bb69f9f2193bb2b", + name: "IntercomQATest1", + app_id: "this_is_an_id193_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "remote_companies_scroll_2", + remote_created_at: 1734537367, + created_at: 1734537367, + updated_at: 1734537367, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 4, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + }, + }, + ], + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 2, + total_pages: 13, + }, + total_count: 100, + scroll_param: "69352cd2-ab5b-42ac-b004-a13d4e55e9b0", + }); + }); + + test("scrollOverAllCompanies (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/companies/scroll").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.companies.scrollOverAllCompanies(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachContactToACompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "6762f09a1bb69f9f2193bb34" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "6762f09a1bb69f9f2193bb34", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("attachContactToACompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "58a430d35458202d41b1e65b" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "58a430d35458202d41b1e65b", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("attachContactToACompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "123" }; + const rawResponseBody = { + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "123", + }); + expect(response).toEqual({ + type: "company", + id: "6762f09a1bb69f9f2193bb34", + name: "company6", + app_id: "this_is_an_id197_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537370, + created_at: 1734537370, + updated_at: 1734537370, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 1, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("attachContactToACompany (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "company_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("attachContactToACompany (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "company_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachContactToACompany (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { company_id: "company_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/id/companies") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.attachContactToACompany({ + id: "id", + company_id: "company_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachContactFromACompany (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "company", + id: "6762f0a01bb69f9f2193bb44", + name: "company8", + app_id: "this_is_an_id205_that_should_be_at_least_", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "1", + remote_created_at: 1734537376, + created_at: 1734537376, + updated_at: 1734537377, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { key: "value" }, + tags: { type: "tag.list", tags: [{ key: "value" }] }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [{ type: "note", id: "17495962", created_at: 1674589321, body: "

Text for the note.

" }], + }, + }; + server + .mockEndpoint() + .delete("/contacts/58a430d35458202d41b1e65b/companies/58a430d35458202d41b1e65b") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.companies.detachContactFromACompany({ + contact_id: "58a430d35458202d41b1e65b", + id: "58a430d35458202d41b1e65b", + }); + expect(response).toEqual({ + type: "company", + id: "6762f0a01bb69f9f2193bb44", + name: "company8", + app_id: "this_is_an_id205_that_should_be_at_least_", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "1", + remote_created_at: 1734537376, + created_at: 1734537376, + updated_at: 1734537377, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 0, + session_count: 0, + user_count: 0, + custom_attributes: { + key: "value", + }, + tags: { + type: "tag.list", + tags: [ + { + key: "value", + }, + ], + }, + segments: { + type: "segment.list", + segments: [ + { + id: "56203d253cba154d39010062", + name: "Active", + created_at: 1394621988, + updated_at: 1394622004, + count: 3, + }, + ], + }, + notes: { + type: "note.list", + notes: [ + { + type: "note", + id: "17495962", + created_at: 1674589321, + body: "

Text for the note.

", + }, + ], + }, + }); + }); + + test("detachContactFromACompany (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/companies/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.detachContactFromACompany({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachContactFromACompany (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/companies/id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.companies.detachContactFromACompany({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/contacts.test.ts b/tests/wire/unstable/contacts.test.ts new file mode 100644 index 00000000..4893898e --- /dev/null +++ b/tests/wire/unstable/contacts.test.ts @@ -0,0 +1,2297 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("ContactsClient", () => { + test("listCompaniesForAContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + companies: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { type: "plan", id: "269315", name: "Pro" }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + total_count: 1, + pages: { type: "pages", page: 1, next: "next", per_page: 50, total_pages: 1 }, + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/companies") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.listCompaniesForAContact({ + id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + companies: [ + { + type: "company", + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + plan: { + type: "plan", + id: "269315", + name: "Pro", + }, + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: "next", + per_page: 50, + total_pages: 1, + }, + }); + }); + + test("listCompaniesForAContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/id/companies") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listCompaniesForAContact({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listCompaniesForAContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/id/companies") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listCompaniesForAContact({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listSegmentsForAContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "segment", + id: "6762f0b21bb69f9f2193bb65", + name: "segment", + created_at: 1734537394, + updated_at: 1734537394, + person_type: "user", + count: 3, + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/segments") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.listSegmentsForAContact({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "segment", + id: "6762f0b21bb69f9f2193bb65", + name: "segment", + created_at: 1734537394, + updated_at: 1734537394, + person_type: "user", + count: 3, + }, + ], + }); + }); + + test("listSegmentsForAContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/segments") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listSegmentsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listSegmentsForAContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/segments") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listSegmentsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listSubscriptionsForAContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "subscription", + id: "91", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_out", + content_types: ["email"], + }, + { + type: "subscription", + id: "93", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/subscriptions") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.listSubscriptionsForAContact({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "subscription", + id: "91", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_out", + content_types: ["email"], + }, + { + type: "subscription", + id: "93", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }, + ], + }); + }); + + test("listSubscriptionsForAContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/subscriptions") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listSubscriptionsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listSubscriptionsForAContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/subscriptions") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listSubscriptionsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listTagsForAContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "tag", + id: "80", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965/tags") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.listTagsForAContact({ + contact_id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "tag", + id: "80", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }); + }); + + test("listTagsForAContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/contact_id/tags") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listTagsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listTagsForAContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/contacts/contact_id/tags") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.listTagsForAContact({ + contact_id: "contact_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("ShowContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "contact", + id: "6762f0d01bb69f9f2193bb7d", + external_id: "70", + workspace_id: "this_is_an_id283_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537424, + updated_at: 1734537424, + signed_up_at: 1734537424, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0d01bb69f9f2193bb7d/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .get("/contacts/63a07ddf05a32042dffac965") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.showContact({ + id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0d01bb69f9f2193bb7d", + external_id: "70", + workspace_id: "this_is_an_id283_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537424, + updated_at: 1734537424, + signed_up_at: 1734537424, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0d01bb69f9f2193bb7d/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("ShowContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/contacts/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.contacts.showContact({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("UpdateContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { email: "joebloggs@intercom.io", name: "joe bloggs" }; + const rawResponseBody = { + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .put("/contacts/63a07ddf05a32042dffac965") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.updateContact({ + id: "63a07ddf05a32042dffac965", + email: "joebloggs@intercom.io", + name: "joe bloggs", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("UpdateContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { custom_attributes: { order: ["21"] } }; + const rawResponseBody = { + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { order_number: "ORDER-12345", total_amount: 99.99 }, + type: "Order", + }, + ], + }, + }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .put("/contacts/63a07ddf05a32042dffac965") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.updateContact({ + id: "63a07ddf05a32042dffac965", + custom_attributes: { + order: ["21"], + }, + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0cd1bb69f9f2193bb7c", + external_id: "70", + workspace_id: "this_is_an_id279_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "joe bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537421, + updated_at: 1734537422, + signed_up_at: 1734537421, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { + order_number: "ORDER-12345", + total_amount: 99.99, + }, + type: "Order", + }, + ], + }, + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0cd1bb69f9f2193bb7c/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("UpdateContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/contacts/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.updateContact({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("DeleteContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", deleted: true }; + server.mockEndpoint().delete("/contacts/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.contacts.deleteContact({ + id: "id", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + deleted: true, + }); + }); + + test("DeleteContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/contacts/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.contacts.deleteContact({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("MergeContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: "6762f0d51bb69f9f2193bb7f", into: "6762f0d51bb69f9f2193bb80" }; + const rawResponseBody = { + type: "contact", + id: "6762f0d51bb69f9f2193bb80", + external_id: "70", + workspace_id: "this_is_an_id291_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537429, + updated_at: 1734537430, + signed_up_at: 1734537429, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0d51bb69f9f2193bb80/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .post("/contacts/merge") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.mergeContact({ + from: "6762f0d51bb69f9f2193bb7f", + into: "6762f0d51bb69f9f2193bb80", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0d51bb69f9f2193bb80", + external_id: "70", + workspace_id: "this_is_an_id291_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537429, + updated_at: 1734537430, + signed_up_at: 1734537429, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0d51bb69f9f2193bb80/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("MergeContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/merge") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.mergeContact(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("SearchContacts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", total_count: 100, has_more: true }, + notes: { url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", total_count: 100, has_more: true }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 0, + }, + }; + server + .mockEndpoint() + .post("/contacts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.searchContacts({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", + total_count: 100, + has_more: true, + }, + notes: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + total_count: 100, + has_more: true, + }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 0, + }, + }); + }); + + test("SearchContacts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { query: {} }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.searchContacts({ + query: {}, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("ListContacts (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", total_count: 100, has_more: true }, + notes: { url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", total_count: 100, has_more: true }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 0, + }, + }; + server.mockEndpoint().get("/contacts").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.contacts.listContacts(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "ecahpwf5", + role: "user", + email: "joe@example.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: true, + marked_email_as_spam: true, + unsubscribed_from_emails: true, + created_at: 1571672154, + updated_at: 1571672154, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/tags", + total_count: 100, + has_more: true, + }, + notes: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + total_count: 100, + has_more: true, + }, + companies: { + url: "/contacts/5ba682d23d7cf92bef87bfd4/companies", + total_count: 100, + has_more: true, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + }, + ], + total_count: 0, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 0, + }, + }); + }); + + test("ListContacts (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/contacts").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.contacts.listContacts(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("CreateContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { email: "joebloggs@intercom.io" }; + const rawResponseBody = { + type: "contact", + id: "6762f0dd1bb69f9f2193bb83", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id303_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537437, + updated_at: 1734537437, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0dd1bb69f9f2193bb83/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .post("/contacts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.createContact({ + email: "joebloggs@intercom.io", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0dd1bb69f9f2193bb83", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id303_that_should_be_at_least_", + role: "user", + email: "joebloggs@intercom.io", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537437, + updated_at: 1734537437, + signed_up_at: 1571672154, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0dd1bb69f9f2193bb83/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("CreateContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.createContact({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("ShowContactByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "contact", + id: "6762f0df1bb69f9f2193bb84", + external_id: "70", + workspace_id: "this_is_an_id307_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537439, + updated_at: 1734537439, + signed_up_at: 1734537439, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f0df1bb69f9f2193bb84/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + enabled_push_messaging: true, + }; + server + .mockEndpoint() + .get("/contacts/find_by_external_id/cdd29344-5e0c-4ef0-ac56-f9ba2979bc27") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.showContactByExternalId({ + external_id: "cdd29344-5e0c-4ef0-ac56-f9ba2979bc27", + }); + expect(response).toEqual({ + type: "contact", + id: "6762f0df1bb69f9f2193bb84", + external_id: "70", + workspace_id: "this_is_an_id307_that_should_be_at_least_", + role: "user", + email: "joe@bloggs.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "Joe Bloggs", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734537439, + updated_at: 1734537439, + signed_up_at: 1734537439, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f0df1bb69f9f2193bb84/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + enabled_push_messaging: true, + }); + }); + + test("ShowContactByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/contacts/find_by_external_id/external_id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.contacts.showContactByExternalId({ + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("ArchiveContact", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", archived: true }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/archive") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.archiveContact({ + id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + archived: true, + }); + }); + + test("UnarchiveContact", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", archived: false }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/unarchive") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.unarchiveContact({ + id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + archived: false, + }); + }); + + test("BlockContact", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70", blocked: true }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/block") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.contacts.blockContact({ + id: "63a07ddf05a32042dffac965", + }); + expect(response).toEqual({ + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + blocked: true, + }); + }); +}); diff --git a/tests/wire/unstable/conversations.test.ts b/tests/wire/unstable/conversations.test.ts new file mode 100644 index 00000000..4dca52d8 --- /dev/null +++ b/tests/wire/unstable/conversations.test.ts @@ -0,0 +1,10888 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("ConversationsClient", () => { + test("listConversations (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "471", + title: "Conversation Title", + created_at: 1734537460, + updated_at: 1734537460, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }], + }, + conversation_rating: { rating: 5, remark: "", created_at: 1671028894, updated_at: 1671028894 }, + source: { + type: "conversation", + id: "403918320", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267628", + name: "Ciaran166 Lee", + email: "admin166@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f0f31bb69f9f2193bb8b", external_id: "70" }], + }, + teammates: { type: "admin.list" }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { total_count: 1 }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 1, + }, + }; + server.mockEndpoint().get("/conversations").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.conversations.listConversations({ + per_page: 1, + starting_after: "starting_after", + }); + expect(response).toEqual({ + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "471", + title: "Conversation Title", + created_at: 1734537460, + updated_at: 1734537460, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + }, + source: { + type: "conversation", + id: "403918320", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267628", + name: "Ciaran166 Lee", + email: "admin166@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f0f31bb69f9f2193bb8b", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 1, + }, + }); + }); + + test("listConversations (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/conversations").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.conversations.listConversations(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listConversations (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/conversations").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.conversations.listConversations(); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("createConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "user", id: "6762f11b1bb69f9f2193bba3" }, body: "Hello there" }; + const rawResponseBody = { + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.createConversation({ + from: { + type: "user", + id: "6762f11b1bb69f9f2193bba3", + }, + body: "Hello there", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }); + }); + + test("createConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "user", id: "123_doesnt_exist" }, body: "Hello there" }; + const rawResponseBody = { + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.createConversation({ + from: { + type: "user", + id: "123_doesnt_exist", + }, + body: "Hello there", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918330", + created_at: 1734537501, + subject: "Greetings", + body: "Hello there", + message_type: "inapp", + conversation_id: "499", + }); + }); + + test("createConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.createConversation({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.createConversation({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("createConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { from: { type: "lead", id: "blackcurrant............" }, body: "body" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.createConversation({ + from: { + type: "lead", + id: "blackcurrant............", + }, + body: "body", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("retrieveConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "conversation", + id: "503", + title: "Conversation Title", + created_at: 1734537511, + updated_at: 1734537511, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918334", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267645", + name: "Ciaran176 Lee", + email: "admin176@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1261bb69f9f2193bba7", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + assigned_to: { type: "contact", id: "1a2b3c" }, + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_started", + body: "

Okay!

", + created_at: 1740141842, + updated_at: 1740141842, + notified_at: 1740141842, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { action: { name: "Jira Create Issue" } }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1740141851, + updated_at: 1740141851, + notified_at: 1740141851, + author: { + type: "bot", + id: "278", + name: "Fin", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { attribute: { name: "jira_issue_key" }, value: { name: "PROJ-007" } }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_finished", + body: "

Okay!

", + created_at: 1740141857, + updated_at: 1740141857, + notified_at: 1740141857, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "closed", + tags: [{ type: "tag", id: "123456", name: "Test tag" }], + event_details: { action: { name: "Jira Create Issue", result: "success" } }, + app_package_code: "test-integration", + }, + ], + total_count: 4, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server.mockEndpoint().get("/conversations/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.conversations.retrieveConversation({ + id: 1, + display_as: "plaintext", + include_translations: true, + }); + expect(response).toEqual({ + type: "conversation", + id: "503", + title: "Conversation Title", + created_at: 1734537511, + updated_at: 1734537511, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918334", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267645", + name: "Ciaran176 Lee", + email: "admin176@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1261bb69f9f2193bba7", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + assigned_to: { + type: "contact", + id: "1a2b3c", + }, + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_started", + body: "

Okay!

", + created_at: 1740141842, + updated_at: 1740141842, + notified_at: 1740141842, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + action: { + name: "Jira Create Issue", + }, + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1740141851, + updated_at: 1740141851, + notified_at: 1740141851, + author: { + type: "bot", + id: "278", + name: "Fin", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "open", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + attribute: { + name: "jira_issue_key", + }, + value: { + name: "PROJ-007", + }, + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "3", + part_type: "custom_action_finished", + body: "

Okay!

", + created_at: 1740141857, + updated_at: 1740141857, + notified_at: 1740141857, + author: { + type: "admin", + id: "274", + name: "Jamie Oliver", + email: "jamie+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + state: "closed", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + }, + ], + event_details: { + action: { + name: "Jira Create Issue", + result: "success", + }, + }, + app_package_code: "test-integration", + }, + ], + total_count: 4, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("retrieveConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/conversations/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.conversations.retrieveConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/conversations/1").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.conversations.retrieveConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("retrieveConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/conversations/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.conversations.retrieveConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + read: true, + title: "new conversation title", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1301bb69f9f2193bbab", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { issue_type: "Billing", priority: "High" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.updateConversation({ + id: 1, + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1301bb69f9f2193bbab", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("updateConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { custom_attributes: { order: {} } }; + const rawResponseBody = { + type: "conversation", + id: "508", + title: "Conversation Title", + created_at: 1734537525, + updated_at: 1734537525, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918339", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267659", + name: "Ciaran185 Lee", + email: "admin185@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1341bb69f9f2193bbac", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1671028894, + updated_at: 1671028894, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }, + ], + }, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 0, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.updateConversation({ + id: 1, + display_as: "plaintext", + custom_attributes: { + order: {}, + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "508", + title: "Conversation Title", + created_at: 1734537525, + updated_at: 1734537525, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918339", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267659", + name: "Ciaran185 Lee", + email: "admin185@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1341bb69f9f2193bbac", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + order: { + type: "Order.list", + instances: [ + { + id: "21", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1671028894, + updated_at: 1671028894, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }, + ], + }, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 0, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("updateConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + read: true, + title: "new conversation title", + custom_attributes: { issue_type: "Billing", priority: "High" }, + }; + const rawResponseBody = { + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1301bb69f9f2193bbab", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { issue_type: "Billing", priority: "High" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.updateConversation({ + id: 1, + display_as: "plaintext", + read: true, + title: "new conversation title", + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "507", + title: "Conversation Title", + created_at: 1734537521, + updated_at: 1734537523, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918338", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267653", + name: "Ciaran180 Lee", + email: "admin180@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1301bb69f9f2193bbab", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + issue_type: "Billing", + priority: "High", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "129", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + { + type: "conversation_part", + id: "130", + part_type: "conversation_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537523, + updated_at: 1734537523, + notified_at: 1734537523, + author: { + type: "bot", + id: "991267654", + name: "Fin", + email: "operator+this_is_an_id354_that_should_be_at_least_@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("updateConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.updateConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.updateConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("updateConversation (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/conversations/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.updateConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "512", object: "conversation", deleted: true }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.deleteConversation({ + id: 1, + }); + expect(response).toEqual({ + id: "512", + object: "conversation", + deleted: true, + }); + }); + + test("deleteConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.deleteConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/1") + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.deleteConversation({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("searchConversations", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "515", + title: "Conversation Title", + created_at: 1734537546, + updated_at: 1734537546, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }], + }, + conversation_rating: { rating: 5, remark: "", created_at: 1671028894, updated_at: 1671028894 }, + source: { + type: "conversation", + id: "403918346", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267691", + name: "Ciaran210 Lee", + email: "admin210@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f14a1bb69f9f2193bbb3", external_id: "70" }], + }, + teammates: { type: "admin.list" }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { total_count: 1 }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 1, + }, + }; + server + .mockEndpoint() + .post("/conversations/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.searchConversations({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + expect(response).toEqual({ + type: "conversation.list", + conversations: [ + { + type: "conversation", + id: "515", + title: "Conversation Title", + created_at: 1734537546, + updated_at: 1734537546, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + }, + source: { + type: "conversation", + id: "403918346", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267691", + name: "Ciaran210 Lee", + email: "admin210@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f14a1bb69f9f2193bbb3", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_title: "My AI Workflow", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + }, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 1, + }, + }); + }); + + test("replyConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.replyConversation({ + id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1571bb69f9f2193bbbb", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("replyConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }; + const rawResponseBody = { + type: "conversation", + id: "525", + title: "Conversation Title", + created_at: 1734537563, + updated_at: 1734537565, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918350", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f15b1bb69f9f2193bbbc", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "133", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537565, + updated_at: 1734537565, + notified_at: 1734537565, + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.replyConversation({ + id: '123 or "last"', + body: { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "525", + title: "Conversation Title", + created_at: 1734537563, + updated_at: 1734537565, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918350", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f15b1bb69f9f2193bbbc", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "133", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537565, + updated_at: 1734537565, + notified_at: 1734537565, + author: { + type: "admin", + id: "991267696", + name: "Ciaran213 Lee", + email: "admin213@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("replyConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { text: "Yes", uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" }, + { text: "No", uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6" }, + ], + }; + const rawResponseBody = { + type: "conversation", + id: "526", + title: "Conversation Title", + created_at: 1734537567, + updated_at: 1734537568, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918351", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f15e1bb69f9f2193bbbd", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "134", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537568, + updated_at: 1734537568, + notified_at: 1734537568, + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.replyConversation({ + id: '123 or "last"', + body: { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { + text: "Yes", + uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb", + }, + { + text: "No", + uuid: "f4a98af1-be56-4948-a57e-e1a83f8484c6", + }, + ], + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "526", + title: "Conversation Title", + created_at: 1734537567, + updated_at: 1734537568, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918351", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f15e1bb69f9f2193bbbd", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "134", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537568, + updated_at: 1734537568, + notified_at: 1734537568, + author: { + type: "admin", + id: "991267698", + name: "Ciaran214 Lee", + email: "admin214@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("replyConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "body", + reply_options: [{ text: "Yes", uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb" }], + intercom_user_id: "6762f1621bb69f9f2193bbbe", + }; + const rawResponseBody = { + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1571bb69f9f2193bbbb", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.replyConversation({ + id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "body", + reply_options: [ + { + text: "Yes", + uuid: "a5e1c524-5ddd-4c3e-9328-6bca5d6e3edb", + }, + ], + intercom_user_id: "6762f1621bb69f9f2193bbbe", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "524", + title: "Conversation Title", + created_at: 1734537559, + updated_at: 1734537561, + waiting_since: 1734537561, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918349", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267694", + name: "Ciaran212 Lee", + email: "admin212@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1571bb69f9f2193bbbb", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537561, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "132", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537561, + updated_at: 1734537561, + notified_at: 1734537561, + author: { + type: "user", + id: "6762f1571bb69f9f2193bbbb", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("replyConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1661bb69f9f2193bbbf", + }; + const rawResponseBody = { + type: "conversation", + id: "527", + title: "Conversation Title", + created_at: 1734537571, + updated_at: 1734537572, + waiting_since: 1734537572, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918352", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267700", + name: "Ciaran215 Lee", + email: "admin215@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1621bb69f9f2193bbbe", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537572, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "135", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537572, + updated_at: 1734537572, + notified_at: 1734537572, + author: { + type: "user", + id: "6762f1621bb69f9f2193bbbe", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123%20or%20%22last%22/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.replyConversation({ + id: '123 or "last"', + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f1661bb69f9f2193bbbf", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "527", + title: "Conversation Title", + created_at: 1734537571, + updated_at: 1734537572, + waiting_since: 1734537572, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918352", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267700", + name: "Ciaran215 Lee", + email: "admin215@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1621bb69f9f2193bbbe", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537572, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "135", + part_type: "open", + body: "

Thanks again :)

", + created_at: 1734537572, + updated_at: 1734537572, + notified_at: 1734537572, + author: { + type: "user", + id: "6762f1621bb69f9f2193bbbe", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("replyConversation (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.replyConversation({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("replyConversation (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.replyConversation({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("replyConversation (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.replyConversation({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("manageConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "12345" }; + const rawResponseBody = { + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f16e1bb69f9f2193bbc2", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f16e1bb69f9f2193bbc2", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manageConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "snoozed", admin_id: "5017691", snoozed_until: 1673609604 }; + const rawResponseBody = { + type: "conversation", + id: "532", + title: "Conversation Title", + created_at: 1734537586, + updated_at: 1734537587, + waiting_since: 1663597260, + snoozed_until: 1734541187, + open: true, + state: "snoozed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918357", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1711bb69f9f2193bbc3", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "137", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537587, + updated_at: 1734537587, + notified_at: 1734537587, + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "snoozed", + admin_id: "5017691", + snoozed_until: 1673609604, + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "532", + title: "Conversation Title", + created_at: 1734537586, + updated_at: 1734537587, + waiting_since: 1663597260, + snoozed_until: 1734541187, + open: true, + state: "snoozed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918357", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1711bb69f9f2193bbc3", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "137", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537587, + updated_at: 1734537587, + notified_at: 1734537587, + author: { + type: "admin", + id: "991267710", + name: "Ciaran220 Lee", + email: "admin220@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manageConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "open", admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "537", + title: "", + created_at: 1734537587, + updated_at: 1734537601, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918358", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1781bb69f9f2193bbc8", external_id: "74" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "139", + part_type: "open", + body: "

Okay!

", + created_at: 1734537601, + updated_at: 1734537601, + notified_at: 1734537601, + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "open", + admin_id: "5017690", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "537", + title: "", + created_at: 1734537587, + updated_at: 1734537601, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918358", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1781bb69f9f2193bbc8", + external_id: "74", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "139", + part_type: "open", + body: "

Okay!

", + created_at: 1734537601, + updated_at: 1734537601, + notified_at: 1734537601, + author: { + type: "admin", + id: "991267712", + name: "Ciaran221 Lee", + email: "admin221@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manageConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "assignment", type: "admin", admin_id: "12345", assignee_id: "4324241" }; + const rawResponseBody = { + type: "conversation", + id: "542", + title: "Conversation Title", + created_at: 1734537603, + updated_at: 1734537605, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 991267715, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918361", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1831bb69f9f2193bbcc", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "140", + part_type: "assign_and_reopen", + body: "

Okay!

", + created_at: 1734537605, + updated_at: 1734537605, + notified_at: 1734537605, + assigned_to: { type: "admin", id: "991267715" }, + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "assignment", + type: "admin", + admin_id: "12345", + assignee_id: "4324241", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "542", + title: "Conversation Title", + created_at: 1734537603, + updated_at: 1734537605, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: false, + priority: "not_priority", + admin_assignee_id: 991267715, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918361", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1831bb69f9f2193bbcc", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "140", + part_type: "assign_and_reopen", + body: "

Okay!

", + created_at: 1734537605, + updated_at: 1734537605, + notified_at: 1734537605, + assigned_to: { + type: "admin", + id: "991267715", + }, + author: { + type: "admin", + id: "991267715", + name: "Ciaran223 Lee", + email: "admin223@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manageConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "12345" }; + const rawResponseBody = { + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f16e1bb69f9f2193bbc2", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.manageConversation({ + id: "123", + body: { + message_type: "close", + type: "admin", + admin_id: "12345", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "531", + title: "Conversation Title", + created_at: 1734537582, + updated_at: 1734537584, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: false, + state: "closed", + read: false, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918356", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f16e1bb69f9f2193bbc2", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "136", + part_type: "close", + body: "

Goodbye :)

", + created_at: 1734537584, + updated_at: 1734537584, + notified_at: 1734537584, + author: { + type: "admin", + id: "991267708", + name: "Ciaran219 Lee", + email: "admin219@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("manageConversation (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.manageConversation({ + id: "id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("manageConversation (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.manageConversation({ + id: "id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("manageConversation (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { message_type: "close", type: "admin", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/id/parts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.manageConversation({ + id: "id", + body: { + message_type: "close", + type: "admin", + admin_id: "admin_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("attachContactToConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "12345", customer: { intercom_user_id: "6762f19b1bb69f9f2193bbd4" } }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.attachContactToConversation({ + id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19b1bb69f9f2193bbd4", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("attachContactToConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "12345", customer: { intercom_user_id: "6762f19e1bb69f9f2193bbd5" } }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/123/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.attachContactToConversation({ + id: "123", + admin_id: "12345", + customer: { + intercom_user_id: "6762f19e1bb69f9f2193bbd5", + }, + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("attachContactToConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.attachContactToConversation({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachContactToConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.attachContactToConversation({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("attachContactToConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/id/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.attachContactToConversation({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachContactFromConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactFromConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactFromConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactFromConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "5017690" }; + const rawResponseBody = { + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { type: "contact.list", contacts: [{ id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }] }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { + paid_subscriber: { type: "order.list", instances: [] }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 100, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .delete("/conversations/123/customers/123") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "123", + contact_id: "123", + admin_id: "5017690", + }); + expect(response).toEqual({ + type: "conversation", + id: "1295", + title: "Conversation Title", + created_at: 1663597223, + updated_at: 1663597260, + waiting_since: 1663597260, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "3", + delivered_as: "operator_initiated", + subject: "", + body: "

Hey there!

", + author: { + type: "admin", + id: "274", + name: "Operator", + email: "operator+abcd1234@intercom.io", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + paid_subscriber: { + type: "order.list", + instances: [], + }, + monthly_spend: "155.5", + team_mates: 9, + start_date_iso8601: "2023-03-04T09:46:14Z", + end_date_timestamp: 1677923174, + }, + first_contact_reply: { + created_at: 1663597223, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "3", + part_type: "comment", + body: "

Okay!

", + created_at: 1663597223, + updated_at: 1663597260, + notified_at: 1663597260, + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 100, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: true, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("detachContactFromConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachContactFromConversation (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(403) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("detachContactFromConversation (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachContactFromConversation (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/customers/contact_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.detachContactFromConversation({ + conversation_id: "conversation_id", + contact_id: "contact_id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); + + test("redactConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428", + }; + const rawResponseBody = { + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1f81bb69f9f2193bc09", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.redactConversation({ + type: "conversation_part", + conversation_id: "19894788788", + conversation_part_id: "19381789428", + }); + expect(response).toEqual({ + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1f81bb69f9f2193bc09", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("redactConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "really_123_doesnt_exist", + conversation_part_id: "really_123_doesnt_exist", + }; + const rawResponseBody = { + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { type: "tag.list", tags: [{ type: "tag", id: "123456", name: "Test tag", applied_at: 1663597223 }] }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { type: "contact", id: "5ba682d23d7cf92bef87bfd4", external_id: "70" }, + teammate: { type: "contact", id: "1a2b3c" }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f1f81bb69f9f2193bc09", external_id: "70" }], + }, + teammates: { type: "admin.list", teammates: [{ type: "contact", id: "1a2b3c" }] }, + custom_attributes: { key: "value" }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { type: "conversation_sla_summary", sla_name: "", sla_status: "hit" }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + assigned_team_first_response_time_in_office_hours: [ + { team_id: 100, team_name: "Team One", response_time: 2310 }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000" }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.redactConversation({ + type: "conversation_part", + conversation_id: "really_123_doesnt_exist", + conversation_part_id: "really_123_doesnt_exist", + }); + expect(response).toEqual({ + type: "conversation", + id: "608", + title: "Conversation Title", + created_at: 1734537721, + updated_at: 1734537724, + waiting_since: 1734537722, + snoozed_until: 1663597260, + open: true, + state: "open", + read: true, + priority: "not_priority", + admin_assignee_id: 0, + team_assignee_id: "5017691", + company_id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + tags: { + type: "tag.list", + tags: [ + { + type: "tag", + id: "123456", + name: "Test tag", + applied_at: 1663597223, + }, + ], + }, + conversation_rating: { + rating: 5, + remark: "", + created_at: 1671028894, + updated_at: 1671028894, + contact: { + type: "contact", + id: "5ba682d23d7cf92bef87bfd4", + external_id: "70", + }, + teammate: { + type: "contact", + id: "1a2b3c", + }, + }, + source: { + type: "conversation", + id: "403918391", + delivered_as: "admin_initiated", + subject: "", + body: "

this is the message body

", + author: { + type: "admin", + id: "991267757", + name: "Ciaran247 Lee", + email: "admin247@email.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + url: "url", + redacted: false, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f1f81bb69f9f2193bc09", + external_id: "70", + }, + ], + }, + teammates: { + type: "admin.list", + teammates: [ + { + type: "contact", + id: "1a2b3c", + }, + ], + }, + custom_attributes: { + key: "value", + }, + first_contact_reply: { + created_at: 1734537722, + type: "conversation", + url: "https://developers.intercom.com/", + }, + sla_applied: { + type: "conversation_sla_summary", + sla_name: "", + sla_status: "hit", + }, + statistics: { + type: "conversation_statistics", + time_to_assignment: 2310, + time_to_admin_reply: 2310, + time_to_first_close: 2310, + time_to_last_close: 2310, + median_time_to_reply: 2310, + first_contact_reply_at: 1663597233, + first_assignment_at: 1663597233, + first_admin_reply_at: 1663597233, + first_close_at: 1663597233, + last_assignment_at: 1663597233, + last_assignment_admin_reply_at: 1663597233, + last_contact_reply_at: 1663597233, + last_admin_reply_at: 1663597233, + last_close_at: 1663597233, + last_closed_by_id: "c3po", + count_reopens: 1, + count_assignments: 1, + count_conversation_parts: 1, + assigned_team_first_response_time_by_team: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + assigned_team_first_response_time_in_office_hours: [ + { + team_id: 100, + team_name: "Team One", + response_time: 2310, + }, + ], + handling_time: 2310, + adjusted_handling_time: 1800, + }, + conversation_parts: { + type: "conversation_part.list", + conversation_parts: [ + { + type: "conversation_part", + id: "149", + part_type: "open", + body: "

This message was deleted

", + created_at: 1734537722, + updated_at: 1734537724, + notified_at: 1734537722, + author: { + type: "user", + id: "6762f1f81bb69f9f2193bc09", + name: "Joe Bloggs", + email: "joe@bloggs.com", + from_ai_agent: true, + is_ai_answer: false, + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: true, + metadata: { + quick_reply_uuid: "123e4567-e89b-12d3-a456-426614174000", + }, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ai_agent_participated: false, + ai_agent: { + source_type: "essentials_plan_setup", + source_title: "My AI Workflow", + last_answer_type: "ai_answer", + resolution_state: "assumed_resolution", + rating: 4, + rating_remark: "Very helpful!", + created_at: 1663597260, + updated_at: 1663597260, + content_sources: { + type: "content_source.list", + total_count: 1, + content_sources: [ + { + url: "/fin-ai-agent/content?content=content_snippet&id=3234924", + title: "My internal content snippet", + locale: "en", + }, + ], + }, + }, + }); + }); + + test("redactConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.redactConversation({ + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("redactConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/redact") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.redactConversation({ + type: "conversation_part", + conversation_id: "conversation_id", + conversation_part_id: "conversation_part_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("convertConversationToTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "53" }; + const rawResponseBody = { + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { key: "value" }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f2041bb69f9f2193bc0c", external_id: "70" }], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.convertConversationToTicket({ + id: 1, + ticket_type_id: "53", + }); + expect(response).toEqual({ + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { + key: "value", + }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2041bb69f9f2193bc0c", + external_id: "70", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }); + }); + + test("convertConversationToTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "54" }; + const rawResponseBody = { + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { key: "value" }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [{ type: "contact", id: "6762f2041bb69f9f2193bc0c", external_id: "70" }], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.conversations.convertConversationToTicket({ + id: 1, + ticket_type_id: "54", + }); + expect(response).toEqual({ + type: "ticket", + id: "611", + ticket_id: "22", + category: "Customer", + ticket_attributes: { + key: "value", + }, + ticket_state: { + type: "ticket_state", + id: "7493", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "53", + category: "Customer", + name: "my-ticket-type-1", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id442_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537737, + updated_at: 1734537737, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2041bb69f9f2193bc0c", + external_id: "70", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537732, + updated_at: 1734537737, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "151", + part_type: "comment", + body: "

Comment for message

", + created_at: 1734537732, + updated_at: 1734537732, + author: { + type: "user", + id: "6762f2041bb69f9f2193bc0c", + name: "Joe Bloggs", + email: "joe@bloggs.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "152", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537737, + updated_at: 1734537737, + author: { + type: "bot", + id: "991267767", + name: "Fin", + email: "operator+this_is_an_id442_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 2, + }, + is_shared: true, + }); + }); + + test("convertConversationToTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/1/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.conversations.convertConversationToTicket({ + id: 1, + ticket_type_id: "ticket_type_id", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); +}); diff --git a/tests/wire/unstable/customChannelEvents.test.ts b/tests/wire/unstable/customChannelEvents.test.ts new file mode 100644 index 00000000..bb810951 --- /dev/null +++ b/tests/wire/unstable/customChannelEvents.test.ts @@ -0,0 +1,796 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("CustomChannelEventsClient", () => { + test("notifyNewConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "evt_12345", + external_conversation_id: "conv_67890", + contact: { type: "user", external_id: "user_001", name: "Jane Doe", email: "jane.doe@example.com" }, + }; + const rawResponseBody = { + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "evt_12345", + external_conversation_id: "conv_67890", + contact: { + type: "user", + external_id: "user_001", + name: "Jane Doe", + email: "jane.doe@example.com", + }, + }); + expect(response).toEqual({ + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }); + }); + + test("notifyNewConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("notifyNewConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("notifyNewConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("notifyNewConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_conversation") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewConversation({ + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); + + test("notifyNewMessage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "evt_54321", + external_conversation_id: "conv_98765", + contact: { type: "user", external_id: "user_002", name: "John Smith", email: "john.smith@example.com" }, + body: "Hello, I need help with my order.", + }; + const rawResponseBody = { + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customChannelEvents.notifyNewMessage({ + event_id: "evt_54321", + external_conversation_id: "conv_98765", + contact: { + type: "user", + external_id: "user_002", + name: "John Smith", + email: "john.smith@example.com", + }, + body: "Hello, I need help with my order.", + }); + expect(response).toEqual({ + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }); + }); + + test("notifyNewMessage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("notifyNewMessage (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("notifyNewMessage (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("notifyNewMessage (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_new_message") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyNewMessage({ + body: "body", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); + + test("notifyQuickReplySelected (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { type: "user", external_id: "user_003", name: "Alice Example", email: "alice@example.com" }, + quick_reply_option_id: "1234", + }; + const rawResponseBody = { + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customChannelEvents.notifyQuickReplySelected({ + event_id: "evt_67890", + external_conversation_id: "conv_13579", + contact: { + type: "user", + external_id: "user_003", + name: "Alice Example", + email: "alice@example.com", + }, + quick_reply_option_id: "1234", + }); + expect(response).toEqual({ + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }); + }); + + test("notifyQuickReplySelected (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("notifyQuickReplySelected (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("notifyQuickReplySelected (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("notifyQuickReplySelected (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_quick_reply_selected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyQuickReplySelected({ + quick_reply_option_id: "quick_reply_option_id", + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); + + test("notifyAttributeCollected (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + event_id: "evt_24680", + external_conversation_id: "conv_11223", + contact: { type: "user", external_id: "user_004", name: "Bob Example", email: "bob@example.com" }, + attribute: { id: "shipping_address", value: "123 Main St, Springfield" }, + }; + const rawResponseBody = { + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customChannelEvents.notifyAttributeCollected({ + event_id: "evt_24680", + external_conversation_id: "conv_11223", + contact: { + type: "user", + external_id: "user_004", + name: "Bob Example", + email: "bob@example.com", + }, + attribute: { + id: "shipping_address", + value: "123 Main St, Springfield", + }, + }); + expect(response).toEqual({ + external_conversation_id: "customer_conversation_id_12", + conversation_id: "intercom_conversation_id_34", + external_contact_id: "customer_contact_id_56", + contact_id: "intercom_contact_id_79", + }); + }); + + test("notifyAttributeCollected (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("notifyAttributeCollected (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("notifyAttributeCollected (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("notifyAttributeCollected (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + attribute: { id: "id", value: "value" }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { type: "user", external_id: "external_id" }, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_channel_events/notify_attribute_collected") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customChannelEvents.notifyAttributeCollected({ + attribute: { + id: "id", + value: "value", + }, + event_id: "event_id", + external_conversation_id: "external_conversation_id", + contact: { + type: "user", + external_id: "external_id", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/unstable/customObjectInstances.test.ts b/tests/wire/unstable/customObjectInstances.test.ts new file mode 100644 index 00000000..6f46b5a0 --- /dev/null +++ b/tests/wire/unstable/customObjectInstances.test.ts @@ -0,0 +1,475 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("CustomObjectInstancesClient", () => { + test("getCustomObjectInstancesByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "24", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537748, + updated_at: 1734537748, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .get("/custom_object_instances/Order") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + external_id: "external_id", + }); + expect(response).toEqual({ + id: "24", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537748, + updated_at: 1734537748, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("getCustomObjectInstancesByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getCustomObjectInstancesByExternalId (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.getCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("createCustomObjectInstances (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + const rawResponseBody = { + id: "22", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1734537745, + updated_at: 1734537745, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .post("/custom_object_instances/Order") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "Order", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + expect(response).toEqual({ + id: "22", + external_id: "123", + external_created_at: 1392036272, + external_updated_at: 1392036272, + created_at: 1734537745, + updated_at: 1734537745, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("createCustomObjectInstances (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/custom_object_instances/custom_object_type_identifier") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "custom_object_type_identifier", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createCustomObjectInstances (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/custom_object_instances/custom_object_type_identifier") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.createCustomObjectInstances({ + custom_object_type_identifier: "custom_object_type_identifier", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteCustomObjectInstancesById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { object: "Order", id: "26", deleted: true }; + server + .mockEndpoint() + .delete("/custom_object_instances/Order") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + external_id: "external_id", + }); + expect(response).toEqual({ + object: "Order", + id: "26", + deleted: true, + }); + }); + + test("deleteCustomObjectInstancesById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteCustomObjectInstancesById (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.deleteCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + external_id: "external_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("getCustomObjectInstancesById (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "25", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537750, + updated_at: 1734537750, + type: "Order", + custom_attributes: { order_number: "ORDER-12345", total_amount: "custom_attributes" }, + }; + server + .mockEndpoint() + .get("/custom_object_instances/Order/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "Order", + id: "id", + }); + expect(response).toEqual({ + id: "25", + external_id: "123", + external_created_at: 1571672154, + external_updated_at: 1571672154, + created_at: 1734537750, + updated_at: 1734537750, + type: "Order", + custom_attributes: { + order_number: "ORDER-12345", + total_amount: "custom_attributes", + }, + }); + }); + + test("getCustomObjectInstancesById (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getCustomObjectInstancesById (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/custom_object_instances/custom_object_type_identifier/id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.getCustomObjectInstancesById({ + custom_object_type_identifier: "custom_object_type_identifier", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteCustomObjectInstancesByExternalId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { object: "Order", id: "26", deleted: true }; + server + .mockEndpoint() + .delete("/custom_object_instances/Order/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "Order", + id: "id", + }); + expect(response).toEqual({ + object: "Order", + id: "26", + deleted: true, + }); + }); + + test("deleteCustomObjectInstancesByExternalId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteCustomObjectInstancesByExternalId (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/custom_object_instances/custom_object_type_identifier/id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.customObjectInstances.deleteCustomObjectInstancesByExternalId({ + custom_object_type_identifier: "custom_object_type_identifier", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/dataAttributes.test.ts b/tests/wire/unstable/dataAttributes.test.ts new file mode 100644 index 00000000..40902954 --- /dev/null +++ b/tests/wire/unstable/dataAttributes.test.ts @@ -0,0 +1,992 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("DataAttributesClient", () => { + test("lisDataAttributes (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "name", + label: "Company name", + description: "The name of a company", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "company_id", + full_name: "company_id", + label: "Company ID", + description: "A number identifying a company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "last_request_at", + full_name: "last_request_at", + label: "Company last seen", + description: "The last day anyone from a company visited your site or app", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "remote_created_at", + full_name: "remote_created_at", + label: "Company created at", + description: "The day a company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "user_count", + full_name: "user_count", + label: "People", + description: "The number of people in a company", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "session_count", + full_name: "session_count", + label: "Company web sessions", + description: "All visits from anyone in a company to your product's site or app", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "plan.name", + label: "Plan", + description: "A specific plan or level within your product that companies have signed up to", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "monthly_spend", + full_name: "monthly_spend", + label: "Monthly Spend", + description: "The monthly revenue you receive from a company", + data_type: "float", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "size", + full_name: "size", + label: "Company size", + description: "The number of people employed in this company, expressed as a single number", + data_type: "integer", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "industry", + full_name: "industry", + label: "Company industry", + description: "The category or domain this company belongs to e.g. 'ecommerce' or 'SaaS'", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "website", + full_name: "website", + label: "Company website", + description: "The web address for the company's primary marketing site", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 34, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: + "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537753, + updated_at: 1734537753, + admin_id: "991267784", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "id", + label: "ID", + description: "The Intercom defined id representing the company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "created_at", + full_name: "created_at", + label: "Created at", + description: "The time the company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "updated_at", + full_name: "updated_at", + label: "Updated at", + description: "The last time the company was updated", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "plan.id", + label: "Plan ID", + description: "The Intercom defined id representing the plan", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "app_id", + full_name: "app_id", + label: "App ID", + description: "The Intercom defined id representing the app", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + ], + }; + server.mockEndpoint().get("/data_attributes").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.dataAttributes.lisDataAttributes({ + model: "contact", + include_archived: true, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "name", + label: "Company name", + description: "The name of a company", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "company_id", + full_name: "company_id", + label: "Company ID", + description: "A number identifying a company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "last_request_at", + full_name: "last_request_at", + label: "Company last seen", + description: "The last day anyone from a company visited your site or app", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "remote_created_at", + full_name: "remote_created_at", + label: "Company created at", + description: "The day a company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "user_count", + full_name: "user_count", + label: "People", + description: "The number of people in a company", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "session_count", + full_name: "session_count", + label: "Company web sessions", + description: "All visits from anyone in a company to your product's site or app", + data_type: "integer", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "name", + full_name: "plan.name", + label: "Plan", + description: "A specific plan or level within your product that companies have signed up to", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "monthly_spend", + full_name: "monthly_spend", + label: "Monthly Spend", + description: "The monthly revenue you receive from a company", + data_type: "float", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "size", + full_name: "size", + label: "Company size", + description: "The number of people employed in this company, expressed as a single number", + data_type: "integer", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "industry", + full_name: "industry", + label: "Company industry", + description: "The category or domain this company belongs to e.g. 'ecommerce' or 'SaaS'", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "website", + full_name: "website", + label: "Company website", + description: "The web address for the company's primary marketing site", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 34, + model: "company", + name: "The One Ring", + full_name: "custom_attributes.The One Ring", + label: "The One Ring", + description: + "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them.", + data_type: "string", + options: ["true", "false"], + api_writable: true, + messenger_writable: true, + ui_writable: false, + custom: true, + archived: false, + created_at: 1734537753, + updated_at: 1734537753, + admin_id: "991267784", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "id", + label: "ID", + description: "The Intercom defined id representing the company", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "created_at", + full_name: "created_at", + label: "Created at", + description: "The time the company was added to Intercom", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "updated_at", + full_name: "updated_at", + label: "Updated at", + description: "The last time the company was updated", + data_type: "date", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "id", + full_name: "plan.id", + label: "Plan ID", + description: "The Intercom defined id representing the plan", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + { + type: "data_attribute", + id: 12878, + model: "company", + name: "app_id", + full_name: "app_id", + label: "App ID", + description: "The Intercom defined id representing the app", + data_type: "string", + options: ["true", "false"], + api_writable: false, + messenger_writable: true, + ui_writable: false, + custom: false, + archived: false, + created_at: 1671028894, + updated_at: 1671028894, + admin_id: "5712945", + }, + ], + }); + }); + + test("lisDataAttributes (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/data_attributes").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.dataAttributes.lisDataAttributes(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createDataAttribute (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { + type: "data_attribute", + id: 1, + model: "contact", + name: "name", + full_name: "full_name", + label: "label", + description: "description", + data_type: "string", + options: ["options", "options"], + api_writable: true, + messenger_writable: true, + ui_writable: true, + custom: true, + archived: true, + created_at: 1, + updated_at: 1, + admin_id: "admin_id", + }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.dataAttributes.createDataAttribute({ + key: "value", + }); + expect(response).toEqual({ + type: "data_attribute", + id: 1, + model: "contact", + name: "name", + full_name: "full_name", + label: "label", + description: "description", + data_type: "string", + options: ["options", "options"], + api_writable: true, + messenger_writable: true, + ui_writable: true, + custom: true, + archived: true, + created_at: 1, + updated_at: 1, + admin_id: "admin_id", + }); + }); + + test("createDataAttribute (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.createDataAttribute({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createDataAttribute (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/data_attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.createDataAttribute({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateDataAttribute (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { + type: "data_attribute", + id: 1, + model: "contact", + name: "name", + full_name: "full_name", + label: "label", + description: "description", + data_type: "string", + options: ["options", "options"], + api_writable: true, + messenger_writable: true, + ui_writable: true, + custom: true, + archived: true, + created_at: 1, + updated_at: 1, + admin_id: "admin_id", + }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + key: "value", + }, + }); + expect(response).toEqual({ + type: "data_attribute", + id: 1, + model: "contact", + name: "name", + full_name: "full_name", + label: "label", + description: "description", + data_type: "string", + options: ["options", "options"], + api_writable: true, + messenger_writable: true, + ui_writable: true, + custom: true, + archived: true, + created_at: 1, + updated_at: 1, + admin_id: "admin_id", + }); + }); + + test("updateDataAttribute (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + key: "value", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("updateDataAttribute (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + key: "value", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateDataAttribute (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + key: "value", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateDataAttribute (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/data_attributes/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataAttributes.updateDataAttribute({ + id: 1, + body: { + key: "value", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/unstable/dataEvents.test.ts b/tests/wire/unstable/dataEvents.test.ts new file mode 100644 index 00000000..14d6052a --- /dev/null +++ b/tests/wire/unstable/dataEvents.test.ts @@ -0,0 +1,164 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("DataEventsClient", () => { + test("lisDataEvents (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "event.summary", + email: "email", + intercom_user_id: "intercom_user_id", + user_id: "user_id", + events: [ + { name: "name", first: "first", last: "last", count: 1, description: "description" }, + { name: "name", first: "first", last: "last", count: 1, description: "description" }, + ], + }; + server.mockEndpoint().get("/events").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.dataEvents.lisDataEvents({ + filter: { + user_id: "user_id", + }, + type: "type", + }); + expect(response).toEqual({ + type: "event.summary", + email: "email", + intercom_user_id: "intercom_user_id", + user_id: "user_id", + events: [ + { + name: "name", + first: "first", + last: "last", + count: 1, + description: "description", + }, + { + name: "name", + first: "first", + last: "last", + count: 1, + description: "description", + }, + ], + }); + }); + + test("lisDataEvents (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/events").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.dataEvents.lisDataEvents({ + filter: { + user_id: "user_id", + }, + type: "type", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createDataEvent (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + + server.mockEndpoint().post("/events").jsonBody(rawRequestBody).respondWith().statusCode(200).build(); + + const response = await client.unstable.dataEvents.createDataEvent({ + key: "value", + }); + expect(response).toEqual(undefined); + }); + + test("createDataEvent (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/events") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataEvents.createDataEvent({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("dataEventSummaries (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + + server.mockEndpoint().post("/events/summaries").jsonBody(rawRequestBody).respondWith().statusCode(200).build(); + + const response = await client.unstable.dataEvents.dataEventSummaries(); + expect(response).toEqual(undefined); + }); + + test("dataEventSummaries (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/events/summaries") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.dataEvents.dataEventSummaries(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/dataExport.test.ts b/tests/wire/unstable/dataExport.test.ts new file mode 100644 index 00000000..7db13db4 --- /dev/null +++ b/tests/wire/unstable/dataExport.test.ts @@ -0,0 +1,127 @@ +// This file was auto-generated by Fern from our API Definition. + +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("DataExportClient", () => { + test("createDataExport", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { created_at_after: 1734519776, created_at_before: 1734537776 }; + const rawResponseBody = { + job_identfier: "orzzsbd7hk67xyu", + status: "pending", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .post("/export/content/data") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.dataExport.createDataExport({ + created_at_after: 1734519776, + created_at_before: 1734537776, + }); + expect(response).toEqual({ + job_identfier: "orzzsbd7hk67xyu", + status: "pending", + download_expires_at: "", + download_url: "", + }); + }); + + test("getDataExport", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + job_identfier: "orzzsbd7hk67xyu", + status: "pending", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .get("/export/content/data/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.dataExport.getDataExport({ + job_identifier: "job_identifier", + }); + expect(response).toEqual({ + job_identfier: "orzzsbd7hk67xyu", + status: "pending", + download_expires_at: "", + download_url: "", + }); + }); + + test("cancelDataExport", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + job_identfier: "orzzsbd7hk67xyu", + status: "canceled", + download_expires_at: "", + download_url: "", + }; + server + .mockEndpoint() + .post("/export/cancel/job_identifier") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.dataExport.cancelDataExport({ + job_identifier: "job_identifier", + }); + expect(response).toEqual({ + job_identfier: "orzzsbd7hk67xyu", + status: "canceled", + download_expires_at: "", + download_url: "", + }); + }); + + test("downloadDataExport", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().get("/download/content/data/job_identifier").respondWith().statusCode(200).build(); + + const response = await client.unstable.dataExport.downloadDataExport({ + job_identifier: "job_identifier", + }); + expect(response).toEqual(undefined); + }); +}); diff --git a/tests/wire/unstable/emails.test.ts b/tests/wire/unstable/emails.test.ts new file mode 100644 index 00000000..95a02bd0 --- /dev/null +++ b/tests/wire/unstable/emails.test.ts @@ -0,0 +1,174 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("EmailsClient", () => { + test("listEmails (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "email_setting", + id: "1", + email: "support@company.com", + verified: true, + domain: "company.com", + brand_id: "9", + forwarding_enabled: true, + forwarded_email_last_received_at: 1710498600, + created_at: 1692530400, + updated_at: 1710498600, + }, + { + type: "email_setting", + id: "2", + email: "hello@company.com", + verified: true, + domain: "company.com", + brand_id: "10", + forwarding_enabled: false, + forwarded_email_last_received_at: 1710498600, + created_at: 1683729000, + updated_at: 1701424500, + }, + ], + }; + server.mockEndpoint().get("/emails").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.emails.listEmails(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "email_setting", + id: "1", + email: "support@company.com", + verified: true, + domain: "company.com", + brand_id: "9", + forwarding_enabled: true, + forwarded_email_last_received_at: 1710498600, + created_at: 1692530400, + updated_at: 1710498600, + }, + { + type: "email_setting", + id: "2", + email: "hello@company.com", + verified: true, + domain: "company.com", + brand_id: "10", + forwarding_enabled: false, + forwarded_email_last_received_at: 1710498600, + created_at: 1683729000, + updated_at: 1701424500, + }, + ], + }); + }); + + test("listEmails (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/emails").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.emails.listEmails(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveEmail (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "email_setting", + id: "10", + email: "support@company.com", + verified: true, + domain: "company.com", + brand_id: "15", + forwarding_enabled: true, + forwarded_email_last_received_at: 1710498600, + created_at: 1692530400, + updated_at: 1710498600, + }; + server.mockEndpoint().get("/emails/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.emails.retrieveEmail({ + id: "id", + }); + expect(response).toEqual({ + type: "email_setting", + id: "10", + email: "support@company.com", + verified: true, + domain: "company.com", + brand_id: "15", + forwarding_enabled: true, + forwarded_email_last_received_at: 1710498600, + created_at: 1692530400, + updated_at: 1710498600, + }); + }); + + test("retrieveEmail (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/emails/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.emails.retrieveEmail({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveEmail (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/emails/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.emails.retrieveEmail({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/export.test.ts b/tests/wire/unstable/export.test.ts new file mode 100644 index 00000000..0027d596 --- /dev/null +++ b/tests/wire/unstable/export.test.ts @@ -0,0 +1,201 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("ExportClient", () => { + test("enqueueANewReportingDataExportJob (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000, + }; + const rawResponseBody = { + job_identifier: "job1", + status: "pending", + download_url: "download_url", + download_expires_at: "download_expires_at", + }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.export.enqueueANewReportingDataExportJob({ + dataset_id: "conversation", + attribute_ids: ["conversation_id", "conversation_started_at"], + start_time: 1717490000, + end_time: 1717510000, + }); + expect(response).toEqual({ + job_identifier: "job1", + status: "pending", + download_url: "download_url", + download_expires_at: "download_expires_at", + }); + }); + + test("enqueueANewReportingDataExportJob (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("enqueueANewReportingDataExportJob (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("enqueueANewReportingDataExportJob (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/export/reporting_data/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(429) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.export.enqueueANewReportingDataExportJob({ + dataset_id: "dataset_id", + attribute_ids: ["attribute_ids", "attribute_ids"], + start_time: 1000000, + end_time: 1000000, + }); + }).rejects.toThrow(Intercom.unstable.TooManyRequestsError); + }); + + test("listAvailableDatasetsAndAttributes", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + id: "conversation", + name: "Conversation", + description: "Conversation-level details: status, channel, assignee.", + default_time_attribute_id: "conversation_started_at", + attributes: [{ id: "conversation_id", name: "Conversation ID" }], + }, + ], + }; + server + .mockEndpoint() + .get("/export/reporting_data/get_datasets") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.export.listAvailableDatasetsAndAttributes(); + expect(response).toEqual({ + type: "list", + data: [ + { + id: "conversation", + name: "Conversation", + description: "Conversation-level details: status, channel, assignee.", + default_time_attribute_id: "conversation_started_at", + attributes: [ + { + id: "conversation_id", + name: "Conversation ID", + }, + ], + }, + ], + }); + }); +}); diff --git a/tests/wire/unstable/helpCenter.test.ts b/tests/wire/unstable/helpCenter.test.ts new file mode 100644 index 00000000..7e4acacd --- /dev/null +++ b/tests/wire/unstable/helpCenter.test.ts @@ -0,0 +1,1933 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("HelpCenterClient", () => { + test("listAllCollections (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 1, + }, + total_count: 2, + data: [ + { + id: "159", + workspace_id: "this_is_an_id96_that_should_be_at_least_4", + name: "English collection title", + description: "english collection description", + created_at: 1734537309, + updated_at: 1734537309, + url: "http://help-center.test/myapp-96/collection-17", + icon: "bookmark", + order: 17, + default_locale: "en", + parent_id: "6871118", + help_center_id: 79, + }, + { + id: "160", + workspace_id: "this_is_an_id96_that_should_be_at_least_4", + name: "English section title", + description: "Default language description", + created_at: 1734537309, + updated_at: 1734537309, + url: "http://help-center.test/myapp-96/section-1", + icon: "bookmark", + order: 1, + default_locale: "en", + parent_id: "159", + help_center_id: 1, + }, + ], + }; + server + .mockEndpoint() + .get("/help_center/collections") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.listAllCollections(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 1, + }, + total_count: 2, + data: [ + { + id: "159", + workspace_id: "this_is_an_id96_that_should_be_at_least_4", + name: "English collection title", + description: "english collection description", + created_at: 1734537309, + updated_at: 1734537309, + url: "http://help-center.test/myapp-96/collection-17", + icon: "bookmark", + order: 17, + default_locale: "en", + parent_id: "6871118", + help_center_id: 79, + }, + { + id: "160", + workspace_id: "this_is_an_id96_that_should_be_at_least_4", + name: "English section title", + description: "Default language description", + created_at: 1734537309, + updated_at: 1734537309, + url: "http://help-center.test/myapp-96/section-1", + icon: "bookmark", + order: 1, + default_locale: "en", + parent_id: "159", + help_center_id: 1, + }, + ], + }); + }); + + test("listAllCollections (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/collections") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.listAllCollections(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createCollection (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Thanks for everything" }; + const rawResponseBody = { + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 81, + }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.createCollection({ + name: "Thanks for everything", + }); + expect(response).toEqual({ + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 81, + }); + }); + + test("createCollection (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "collection 51", description: "Missing required parameter" }; + const rawResponseBody = { + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 81, + }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.createCollection({ + name: "collection 51", + description: "Missing required parameter", + }); + expect(response).toEqual({ + id: "165", + workspace_id: "this_is_an_id100_that_should_be_at_least_", + name: "Thanks for everything", + description: "", + created_at: 1734537312, + updated_at: 1734537312, + url: "http://help-center.test/myapp-100/", + icon: "book-bookmark", + order: 1, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 81, + }); + }); + + test("createCollection (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.createCollection({ + name: "name", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createCollection (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/help_center/collections") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.createCollection({ + name: "name", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveCollection (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "170", + workspace_id: "this_is_an_id106_that_should_be_at_least_", + name: "English collection title", + description: "english collection description", + created_at: 1734537315, + updated_at: 1734537315, + url: "http://help-center.test/myapp-106/collection-22", + icon: "bookmark", + order: 22, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 84, + }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.retrieveCollection({ + id: 1, + }); + expect(response).toEqual({ + id: "170", + workspace_id: "this_is_an_id106_that_should_be_at_least_", + name: "English collection title", + description: "english collection description", + created_at: 1734537315, + updated_at: 1734537315, + url: "http://help-center.test/myapp-106/collection-22", + icon: "bookmark", + order: 22, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 84, + }); + }); + + test("retrieveCollection (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.retrieveCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveCollection (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/help_center/collections/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.retrieveCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateCollection (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Update collection name" }; + const rawResponseBody = { + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 87, + }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.updateCollection({ + id: 1, + name: "Update collection name", + }); + expect(response).toEqual({ + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 87, + }); + }); + + test("updateCollection (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Update collection name" }; + const rawResponseBody = { + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { type: "group_content", name: "Collection name", description: " Collection description" }, + bg: { type: "group_content", name: "Collection name", description: " Collection description" }, + bs: { type: "group_content", name: "Collection name", description: " Collection description" }, + ca: { type: "group_content", name: "Collection name", description: " Collection description" }, + cs: { type: "group_content", name: "Collection name", description: " Collection description" }, + da: { type: "group_content", name: "Collection name", description: " Collection description" }, + de: { type: "group_content", name: "Collection name", description: " Collection description" }, + el: { type: "group_content", name: "Collection name", description: " Collection description" }, + en: { type: "group_content", name: "Collection name", description: " Collection description" }, + es: { type: "group_content", name: "Collection name", description: " Collection description" }, + et: { type: "group_content", name: "Collection name", description: " Collection description" }, + fi: { type: "group_content", name: "Collection name", description: " Collection description" }, + fr: { type: "group_content", name: "Collection name", description: " Collection description" }, + he: { type: "group_content", name: "Collection name", description: " Collection description" }, + hr: { type: "group_content", name: "Collection name", description: " Collection description" }, + hu: { type: "group_content", name: "Collection name", description: " Collection description" }, + id: { type: "group_content", name: "Collection name", description: " Collection description" }, + it: { type: "group_content", name: "Collection name", description: " Collection description" }, + ja: { type: "group_content", name: "Collection name", description: " Collection description" }, + ko: { type: "group_content", name: "Collection name", description: " Collection description" }, + lt: { type: "group_content", name: "Collection name", description: " Collection description" }, + lv: { type: "group_content", name: "Collection name", description: " Collection description" }, + mn: { type: "group_content", name: "Collection name", description: " Collection description" }, + nb: { type: "group_content", name: "Collection name", description: " Collection description" }, + nl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pl: { type: "group_content", name: "Collection name", description: " Collection description" }, + pt: { type: "group_content", name: "Collection name", description: " Collection description" }, + ro: { type: "group_content", name: "Collection name", description: " Collection description" }, + ru: { type: "group_content", name: "Collection name", description: " Collection description" }, + sl: { type: "group_content", name: "Collection name", description: " Collection description" }, + sr: { type: "group_content", name: "Collection name", description: " Collection description" }, + sv: { type: "group_content", name: "Collection name", description: " Collection description" }, + tr: { type: "group_content", name: "Collection name", description: " Collection description" }, + vi: { type: "group_content", name: "Collection name", description: " Collection description" }, + "pt-BR": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-CN": { type: "group_content", name: "Collection name", description: " Collection description" }, + "zh-TW": { type: "group_content", name: "Collection name", description: " Collection description" }, + }, + parent_id: "6871118", + help_center_id: 87, + }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.updateCollection({ + id: 1, + name: "Update collection name", + }); + expect(response).toEqual({ + id: "176", + workspace_id: "this_is_an_id112_that_should_be_at_least_", + name: "Update collection name", + description: "english collection description", + created_at: 1734537318, + updated_at: 1734537319, + url: "http://help-center.test/myapp-112/collection-25", + icon: "folder", + order: 25, + default_locale: "en", + translated_content: { + type: "group_translated_content", + ar: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bg: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + bs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ca: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + cs: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + da: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + de: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + el: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + en: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + es: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + et: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + fr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + he: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + hu: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + id: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + it: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ja: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ko: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + lv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + mn: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nb: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + nl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + pt: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ro: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + ru: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sl: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + sv: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + tr: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + vi: { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "pt-BR": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-CN": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + "zh-TW": { + type: "group_content", + name: "Collection name", + description: " Collection description", + }, + }, + parent_id: "6871118", + help_center_id: 87, + }); + }); + + test("updateCollection (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.updateCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateCollection (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/help_center/collections/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.updateCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteCollection (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "182", object: "collection", deleted: true }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.deleteCollection({ + id: 1, + }); + expect(response).toEqual({ + id: "182", + object: "collection", + deleted: true, + }); + }); + + test("deleteCollection (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.deleteCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteCollection (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/help_center/collections/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.deleteCollection({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("retrieveHelpCenter (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "93", + workspace_id: "this_is_an_id124_that_should_be_at_least_", + created_at: 1734537325, + updated_at: 1734537325, + identifier: "help-center-1", + website_turned_on: false, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.retrieveHelpCenter({ + id: 1, + }); + expect(response).toEqual({ + id: "93", + workspace_id: "this_is_an_id124_that_should_be_at_least_", + created_at: 1734537325, + updated_at: 1734537325, + identifier: "help-center-1", + website_turned_on: false, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }); + }); + + test("retrieveHelpCenter (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.retrieveHelpCenter({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveHelpCenter (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/help_center/help_centers/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.retrieveHelpCenter({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listHelpCenters (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + id: "123", + workspace_id: "hfi1bx4l", + created_at: 1672928359, + updated_at: 1672928610, + identifier: "intercom", + website_turned_on: true, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }, + ], + }; + server + .mockEndpoint() + .get("/help_center/help_centers") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.helpCenter.listHelpCenters(); + expect(response).toEqual({ + type: "list", + data: [ + { + id: "123", + workspace_id: "hfi1bx4l", + created_at: 1672928359, + updated_at: 1672928610, + identifier: "intercom", + website_turned_on: true, + display_name: "Intercom Help Center", + url: "https://help.mycompany.com", + custom_domain: "help.mycompany.com", + }, + ], + }); + }); + + test("listHelpCenters (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/help_center/help_centers") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.helpCenter.listHelpCenters(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/internalArticles.test.ts b/tests/wire/unstable/internalArticles.test.ts new file mode 100644 index 00000000..b8d9b058 --- /dev/null +++ b/tests/wire/unstable/internalArticles.test.ts @@ -0,0 +1,655 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("InternalArticlesClient", () => { + test("listInternalArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "internal_article", + id: "39", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }; + server.mockEndpoint().get("/internal_articles").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.internalArticles.listInternalArticles(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 25, + total_pages: 1, + }, + total_count: 1, + data: [ + { + type: "internal_article", + id: "39", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }); + }); + + test("listInternalArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/internal_articles").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.internalArticles.listInternalArticles(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252, + }; + const rawResponseBody = { + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .post("/internal_articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Article", + author_id: 991266252, + owner_id: 991266252, + }); + expect(response).toEqual({ + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("createInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Thanks for everything", + body: "Body of the Internal Article", + author_id: 1295, + owner_id: 1295, + }; + const rawResponseBody = { + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .post("/internal_articles") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.createInternalArticle({ + title: "Thanks for everything", + body: "Body of the Internal Article", + author_id: 1295, + owner_id: 1295, + }); + expect(response).toEqual({ + type: "internal_article", + id: "42", + title: "Thanks for everything", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("createInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/internal_articles") + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.createInternalArticle(undefined); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createInternalArticle (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/internal_articles") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.createInternalArticle(undefined); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "internal_article", + id: "45", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.retrieveInternalArticle({ + id: 1, + }); + expect(response).toEqual({ + type: "internal_article", + id: "45", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("retrieveInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.retrieveInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/internal_articles/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.retrieveInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.updateInternalArticle({ + id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("updateInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "Christmas is here!", body: "

New gifts in store for the jolly season

" }; + const rawResponseBody = { + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.updateInternalArticle({ + id: 1, + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + }); + expect(response).toEqual({ + type: "internal_article", + id: "48", + title: "title", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }); + }); + + test("updateInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.updateInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateInternalArticle (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/internal_articles/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.updateInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteInternalArticle (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "51", object: "internal_article", deleted: true }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.deleteInternalArticle({ + id: 1, + }); + expect(response).toEqual({ + id: "51", + object: "internal_article", + deleted: true, + }); + }); + + test("deleteInternalArticle (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.deleteInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteInternalArticle (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/internal_articles/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.deleteInternalArticle({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("searchInternalArticles (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + total_count: 1, + data: { + internal_articles: [ + { + id: "55", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + }; + server + .mockEndpoint() + .get("/internal_articles/search") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.internalArticles.searchInternalArticles({ + folder_id: "folder_id", + }); + expect(response).toEqual({ + type: "list", + total_count: 1, + data: { + internal_articles: [ + { + id: "55", + body: "Body of the Article", + owner_id: 991266252, + author_id: 991266252, + created_at: 1672928359, + updated_at: 1672928610, + locale: "en", + }, + ], + }, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + }); + }); + + test("searchInternalArticles (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/internal_articles/search") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.internalArticles.searchInternalArticles(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/jobs.test.ts b/tests/wire/unstable/jobs.test.ts new file mode 100644 index 00000000..7e511aee --- /dev/null +++ b/tests/wire/unstable/jobs.test.ts @@ -0,0 +1,79 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("JobsClient", () => { + test("status (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "job", + id: "2", + url: "https://api.intercom.io/jobs/status/20", + status: "success", + resource_type: "ticket", + resource_id: "20", + resource_url: "https://api.intercom.io/tickets/20", + }; + server.mockEndpoint().get("/jobs/status/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.jobs.status({ + id: "id", + }); + expect(response).toEqual({ + type: "job", + id: "2", + url: "https://api.intercom.io/jobs/status/20", + status: "success", + resource_type: "ticket", + resource_id: "20", + resource_url: "https://api.intercom.io/tickets/20", + }); + }); + + test("status (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/jobs/status/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.jobs.status({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("status (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/jobs/status/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.jobs.status({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/macros.test.ts b/tests/wire/unstable/macros.test.ts new file mode 100644 index 00000000..04168725 --- /dev/null +++ b/tests/wire/unstable/macros.test.ts @@ -0,0 +1,699 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("MacrosClient", () => { + test("listMacros (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "123", + name: "Order Status Update", + body: '

Hi , your order # is ready for pickup!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order #{{order.number}} is ready for pickup!', + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + { + type: "macro", + id: "456", + name: "Welcome Message", + body: '

Welcome to our support! I\'m . How can I help you today?

', + body_text: "Welcome to our support! I'm {{teammate.name}}. How can I help you today?", + created_at: "2025-07-21T14:44:35Z", + updated_at: "2025-07-21T14:44:35Z", + visible_to: "specific_teams", + visible_to_team_ids: ["789", "101"], + available_on: ["inbox"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "123", + name: "Order Status Update", + body: '

Hi , your order # is ready for pickup!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order #{{order.number}} is ready for pickup!', + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + { + type: "macro", + id: "456", + name: "Welcome Message", + body: '

Welcome to our support! I\'m . How can I help you today?

', + body_text: "Welcome to our support! I'm {{teammate.name}}. How can I help you today?", + created_at: "2025-07-21T14:44:35Z", + updated_at: "2025-07-21T14:44:35Z", + visible_to: "specific_teams", + visible_to_team_ids: ["789", "101"], + available_on: ["inbox"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + }, + }, + }); + }); + + test("listMacros (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "789", + name: "Refund Process", + body: '

I understand you\'d like a refund for order #. The refund will be processed within 3-5 business days.

', + body_text: + "I understand you'd like a refund for order #{{conversation.custom_attributes.order_number}}. The refund will be processed within 3-5 business days.", + created_at: "2025-07-21T07:15:34Z", + updated_at: "2025-07-21T07:15:34Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + { + type: "macro", + id: "101", + name: "Product Inquiry Response", + body: '

Thank you for your interest in . I\'d be happy to provide more information!

', + body_text: + 'Thank you for your interest in {{product.name|fallback:"our products"}}. I\'d be happy to provide more information!', + created_at: "2025-07-20T05:33:20Z", + updated_at: "2025-07-21T10:00:00Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0MDAwMDAuMCwgIjEwMSJd" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "789", + name: "Refund Process", + body: '

I understand you\'d like a refund for order #. The refund will be processed within 3-5 business days.

', + body_text: + "I understand you'd like a refund for order #{{conversation.custom_attributes.order_number}}. The refund will be processed within 3-5 business days.", + created_at: "2025-07-21T07:15:34Z", + updated_at: "2025-07-21T07:15:34Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + { + type: "macro", + id: "101", + name: "Product Inquiry Response", + body: '

Thank you for your interest in . I\'d be happy to provide more information!

', + body_text: + 'Thank you for your interest in {{product.name|fallback:"our products"}}. I\'d be happy to provide more information!', + created_at: "2025-07-20T05:33:20Z", + updated_at: "2025-07-21T10:00:00Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0MDAwMDAuMCwgIjEwMSJd", + }, + }, + }); + }); + + test("listMacros (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "234", + name: "Shipping Update Template", + body: '

Your order has been shipped via . Tracking number:

', + body_text: + 'Your order has been shipped via {{shipping.carrier|fallback:"our shipping partner"}}. Tracking number: {{shipping.tracking_number}}', + created_at: "2025-07-22T05:31:01Z", + updated_at: "2025-07-22T18:45:12Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "234", + name: "Shipping Update Template", + body: '

Your order has been shipped via . Tracking number:

', + body_text: + 'Your order has been shipped via {{shipping.carrier|fallback:"our shipping partner"}}. Tracking number: {{shipping.tracking_number}}', + created_at: "2025-07-22T05:31:01Z", + updated_at: "2025-07-22T18:45:12Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + }, + }, + }); + }); + + test("listMacros (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "567", + name: "Account Status Review", + body: '

Hi ,

Your account status:

Last activity:

', + body_text: + 'Hi {{user.first_name|fallback:"there"}},\n\nYour account status: {{user.custom_attributes.account_status|fallback:"pending review"}}\n\nLast activity: {{user.last_seen_at}}', + created_at: "2025-07-21T09:00:00Z", + updated_at: "2025-07-21T09:00:00Z", + visible_to: "specific_teams", + visible_to_team_ids: ["security_team"], + available_on: ["inbox"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "567", + name: "Account Status Review", + body: '

Hi ,

Your account status:

Last activity:

', + body_text: + 'Hi {{user.first_name|fallback:"there"}},\n\nYour account status: {{user.custom_attributes.account_status|fallback:"pending review"}}\n\nLast activity: {{user.last_seen_at}}', + created_at: "2025-07-21T09:00:00Z", + updated_at: "2025-07-21T09:00:00Z", + visible_to: "specific_teams", + visible_to_team_ids: ["security_team"], + available_on: ["inbox"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + }, + }, + }); + }); + + test("listMacros (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "123", + name: "Order Status Update", + body: '

Hi , your order is ready!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order is ready!', + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "123", + name: "Order Status Update", + body: '

Hi , your order is ready!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order is ready!', + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + }, + }, + }); + }); + + test("listMacros (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "macro", + id: "1001", + name: "Quick Response 1", + body: '

Hi , your order is ready!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order is ready!', + created_at: "2025-07-22T11:08:20Z", + updated_at: "2025-07-23T11:08:20Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }, + ], + pages: { type: "pages", per_page: 50, next: { starting_after: "WzE3MTk0OTAxMDAuMCwgIjEwMDIiXQ==" } }, + }; + server.mockEndpoint().get("/macros").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.listMacros({ + per_page: 1, + starting_after: "WzE3MTk0OTM3NTcuMCwgIjEyMyJd", + updated_since: 1000000, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "macro", + id: "1001", + name: "Quick Response 1", + body: '

Hi , your order is ready!

', + body_text: 'Hi {{user.name|fallback:"there"}}, your order is ready!', + created_at: "2025-07-22T11:08:20Z", + updated_at: "2025-07-23T11:08:20Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }, + ], + pages: { + type: "pages", + per_page: 50, + next: { + starting_after: "WzE3MTk0OTAxMDAuMCwgIjEwMDIiXQ==", + }, + }, + }); + }); + + test("listMacros (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/macros").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.listMacros(); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("listMacros (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/macros").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.listMacros(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listMacros (9)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/macros").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.listMacros(); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("getMacro (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "macro", + id: "789", + name: "Refund Process Explanation", + body: '

Hi ,

I understand you\'d like a refund for order #. The refund will be processed within 3-5 business days to your .

Is there anything else I can help you with?

', + body_text: + 'Hi {{user.first_name|fallback:"there"}},\n\nI understand you\'d like a refund for order #{{conversation.custom_attributes.order_number}}. The refund will be processed within 3-5 business days to your {{user.custom_attributes.payment_method|fallback:"original payment method"}}.\n\nIs there anything else I can help you with?', + created_at: "2025-07-21T14:44:35Z", + updated_at: "2025-07-21T14:44:35Z", + visible_to: "specific_teams", + visible_to_team_ids: ["support_team_1", "support_team_2"], + available_on: ["inbox", "messenger"], + }; + server.mockEndpoint().get("/macros/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.getMacro({ + id: "123", + }); + expect(response).toEqual({ + type: "macro", + id: "789", + name: "Refund Process Explanation", + body: '

Hi ,

I understand you\'d like a refund for order #. The refund will be processed within 3-5 business days to your .

Is there anything else I can help you with?

', + body_text: + 'Hi {{user.first_name|fallback:"there"}},\n\nI understand you\'d like a refund for order #{{conversation.custom_attributes.order_number}}. The refund will be processed within 3-5 business days to your {{user.custom_attributes.payment_method|fallback:"original payment method"}}.\n\nIs there anything else I can help you with?', + created_at: "2025-07-21T14:44:35Z", + updated_at: "2025-07-21T14:44:35Z", + visible_to: "specific_teams", + visible_to_team_ids: ["support_team_1", "support_team_2"], + available_on: ["inbox", "messenger"], + }); + }); + + test("getMacro (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "macro", + id: "456", + name: "Product Demo Request", + body: '

Hello ,

Thank you for your interest in ! I\'d love to schedule a personalized demo for your team at .

Would work for you?

', + body_text: + 'Hello {{user.name|fallback:"valued customer"}},\n\nThank you for your interest in {{product.name|fallback:"our products"}}! I\'d love to schedule a personalized demo for your team at {{company.name|fallback:"your company"}}.\n\nWould {{suggested_time|fallback:"next Tuesday at 2 PM EST"}} work for you?', + created_at: "2025-07-22T11:06:40Z", + updated_at: "2025-07-23T00:00:00Z", + visible_to: "specific_teams", + visible_to_team_ids: ["sales_team_us", "sales_team_eu"], + available_on: ["messenger"], + }; + server.mockEndpoint().get("/macros/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.getMacro({ + id: "123", + }); + expect(response).toEqual({ + type: "macro", + id: "456", + name: "Product Demo Request", + body: '

Hello ,

Thank you for your interest in ! I\'d love to schedule a personalized demo for your team at .

Would work for you?

', + body_text: + 'Hello {{user.name|fallback:"valued customer"}},\n\nThank you for your interest in {{product.name|fallback:"our products"}}! I\'d love to schedule a personalized demo for your team at {{company.name|fallback:"your company"}}.\n\nWould {{suggested_time|fallback:"next Tuesday at 2 PM EST"}} work for you?', + created_at: "2025-07-22T11:06:40Z", + updated_at: "2025-07-23T00:00:00Z", + visible_to: "specific_teams", + visible_to_team_ids: ["sales_team_us", "sales_team_eu"], + available_on: ["messenger"], + }); + }); + + test("getMacro (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "macro", + id: "890", + name: "API Integration Help", + body: '

Hi ,

I see you\'re having trouble with the integration. Your API key for app is configured correctly.

Error code:

Let me help you resolve this issue.

', + body_text: + 'Hi {{user.name}},\n\nI see you\'re having trouble with the {{conversation.custom_attributes.api_endpoint|fallback:"API"}} integration. Your API key for app {{app.id}} is configured correctly.\n\nError code: {{conversation.custom_attributes.error_code|fallback:"unknown"}}\n\nLet me help you resolve this issue.', + created_at: "2025-07-18T09:15:00Z", + updated_at: "2025-07-18T09:15:00Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }; + server.mockEndpoint().get("/macros/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.getMacro({ + id: "123", + }); + expect(response).toEqual({ + type: "macro", + id: "890", + name: "API Integration Help", + body: '

Hi ,

I see you\'re having trouble with the integration. Your API key for app is configured correctly.

Error code:

Let me help you resolve this issue.

', + body_text: + 'Hi {{user.name}},\n\nI see you\'re having trouble with the {{conversation.custom_attributes.api_endpoint|fallback:"API"}} integration. Your API key for app {{app.id}} is configured correctly.\n\nError code: {{conversation.custom_attributes.error_code|fallback:"unknown"}}\n\nLet me help you resolve this issue.', + created_at: "2025-07-18T09:15:00Z", + updated_at: "2025-07-18T09:15:00Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox"], + }); + }); + + test("getMacro (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "macro", + id: "123", + name: "Thank You Response", + body: "

Thank you for reaching out! We appreciate your message and will get back to you as soon as possible.

", + body_text: + "Thank you for reaching out! We appreciate your message and will get back to you as soon as possible.", + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }; + server.mockEndpoint().get("/macros/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.macros.getMacro({ + id: "123", + }); + expect(response).toEqual({ + type: "macro", + id: "123", + name: "Thank You Response", + body: "

Thank you for reaching out! We appreciate your message and will get back to you as soon as possible.

", + body_text: + "Thank you for reaching out! We appreciate your message and will get back to you as soon as possible.", + created_at: "2025-07-17T11:18:08Z", + updated_at: "2025-07-17T15:30:24Z", + visible_to: "everyone", + visible_to_team_ids: ["456", "789"], + available_on: ["inbox", "messenger"], + }); + }); + + test("getMacro (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/macros/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.getMacro({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getMacro (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/macros/id").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.getMacro({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("getMacro (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/macros/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.macros.getMacro({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/messages.test.ts b/tests/wire/unstable/messages.test.ts new file mode 100644 index 00000000..7b0b98a4 --- /dev/null +++ b/tests/wire/unstable/messages.test.ts @@ -0,0 +1,766 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("MessagesClient", () => { + test("createMessage (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "user", id: "6762f2341bb69f9f2193bc17" }, + body: "heyy", + referer: "https://twitter.com/bob", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "user", + id: "6762f2341bb69f9f2193bc17", + }, + body: "heyy", + referer: "https://twitter.com/bob", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "lead", id: "6762f2371bb69f9f2193bc18" }, + body: "heyy", + referer: "https://twitter.com/bob", + }; + const rawResponseBody = { + type: "user_message", + id: "403918397", + created_at: 1734537783, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "614", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "lead", + id: "6762f2371bb69f9f2193bc18", + }, + body: "heyy", + referer: "https://twitter.com/bob", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918397", + created_at: 1734537783, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "614", + }); + }); + + test("createMessage (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267816" }, + to: [ + { type: "user", id: "6762f2391bb69f9f2193bc19" }, + { type: "lead", id: "6762f23c1bb69f9f2193bc1b" }, + { type: "user", id: "6762f23d1bb69f9f2193bc1c" }, + ], + cc: [ + { type: "user", id: "6762f23e1bb69f9f2193bc1d" }, + { type: "user", id: "6762f23f1bb69f9f2193bc1e" }, + ], + bcc: [{ type: "user", id: "6762f23e1bb69f9f2193bc2f" }], + message_type: "conversation", + body: "heyy", + }; + const rawResponseBody = { + type: "admin_message", + id: "19", + created_at: 1734537786, + subject: "heyy", + body: "heyy", + message_type: "inapp", + conversation_id: "64619700005570", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267816", + }, + to: [ + { + type: "user", + id: "6762f2391bb69f9f2193bc19", + }, + { + type: "lead", + id: "6762f23c1bb69f9f2193bc1b", + }, + { + type: "user", + id: "6762f23d1bb69f9f2193bc1c", + }, + ], + cc: [ + { + type: "user", + id: "6762f23e1bb69f9f2193bc1d", + }, + { + type: "user", + id: "6762f23f1bb69f9f2193bc1e", + }, + ], + bcc: [ + { + type: "user", + id: "6762f23e1bb69f9f2193bc2f", + }, + ], + message_type: "conversation", + body: "heyy", + }); + expect(response).toEqual({ + type: "admin_message", + id: "19", + created_at: 1734537786, + subject: "heyy", + body: "heyy", + message_type: "inapp", + conversation_id: "64619700005570", + }); + }); + + test("createMessage (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267817" }, + to: { type: "user", id: "6762f23a1bb69f9f2193bc1a" }, + message_type: "sms", + body: "heyy", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267817", + }, + to: { + type: "user", + id: "6762f23a1bb69f9f2193bc1a", + }, + message_type: "sms", + body: "heyy", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267817" }, + to: { phone: 5547999998888, name: "John Doe" }, + message_type: "whatsapp", + components: [{ type: "BODY", parameters: [{ type: "text", text: "Username 123" }] }], + template: "keep_live", + locale: "en", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267817", + }, + to: { + phone: 5547999998888, + name: "John Doe", + }, + message_type: "whatsapp", + components: [ + { + type: "BODY", + parameters: [ + { + type: "text", + text: "Username 123", + }, + ], + }, + ], + template: "keep_live", + locale: "en", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267818" }, + to: { type: "user", id: "6762f23b1bb69f9f2193bc1a" }, + message_type: "inapp", + subject: "heyy", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267818", + }, + to: { + type: "user", + id: "6762f23b1bb69f9f2193bc1a", + }, + message_type: "inapp", + subject: "heyy", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267819" }, + to: { type: "user", user_id: "70" }, + message_type: "email", + body: "hey there", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267819", + }, + to: { + type: "user", + user_id: "70", + }, + message_type: "email", + body: "hey there", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (8)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267820" }, + to: { type: "user", id: "6762f23d1bb69f9f2193bc1c" }, + message_type: "email", + subject: "heyy", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267820", + }, + to: { + type: "user", + id: "6762f23d1bb69f9f2193bc1c", + }, + message_type: "email", + subject: "heyy", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (9)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + from: { type: "admin", id: "991267821" }, + to: { type: "user", id: "6762f23b1bb69f9f2193bc1d" }, + message_type: "sms", + body: "heyy https://picsum.photos/200/300", + }; + const rawResponseBody = { + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }; + server + .mockEndpoint() + .post("/messages") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.messages.createMessage({ + from: { + type: "admin", + id: "991267821", + }, + to: { + type: "user", + id: "6762f23b1bb69f9f2193bc1d", + }, + message_type: "sms", + body: "heyy https://picsum.photos/200/300", + }); + expect(response).toEqual({ + type: "user_message", + id: "403918396", + created_at: 1734537780, + subject: "Greetings", + body: "heyy", + message_type: "inapp", + conversation_id: "613", + }); + }); + + test("createMessage (10)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/messages").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.createMessage(undefined); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createMessage (11)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/messages").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.createMessage(undefined); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createMessage (12)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().post("/messages").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.createMessage(undefined); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("createMessage (13)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().post("/messages").respondWith().statusCode(422).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.createMessage(undefined); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); + + test("getWhatsAppMessageStatus (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + ruleset_id: "ruleset_id", + pages: { type: "pages", per_page: 50, total_pages: 3, next: { starting_after: "abc123" } }, + total_count: 125, + events: [ + { + id: "event_1", + conversation_id: "conv_123", + status: "delivered", + type: "broadcast_outbound", + created_at: 1734537980, + updated_at: 1734538000, + whatsapp_message_id: "wamid_123", + template_name: "appointment_reminder", + }, + { + id: "event_2", + conversation_id: "conv_456", + status: "sent", + type: "broadcast_outbound", + created_at: 1734537970, + updated_at: 1734538010, + whatsapp_message_id: "wamid_456", + template_name: "order_update", + }, + ], + }; + server.mockEndpoint().get("/messages/status").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + per_page: 1, + starting_after: "starting_after", + }); + expect(response).toEqual({ + type: "list", + ruleset_id: "ruleset_id", + pages: { + type: "pages", + per_page: 50, + total_pages: 3, + next: { + starting_after: "abc123", + }, + }, + total_count: 125, + events: [ + { + id: "event_1", + conversation_id: "conv_123", + status: "delivered", + type: "broadcast_outbound", + created_at: 1734537980, + updated_at: 1734538000, + whatsapp_message_id: "wamid_123", + template_name: "appointment_reminder", + }, + { + id: "event_2", + conversation_id: "conv_456", + status: "sent", + type: "broadcast_outbound", + created_at: 1734537970, + updated_at: 1734538010, + whatsapp_message_id: "wamid_456", + template_name: "order_update", + }, + ], + }); + }); + + test("getWhatsAppMessageStatus (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/messages/status").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("getWhatsAppMessageStatus (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/messages/status").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getWhatsAppMessageStatus (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/messages/status").respondWith().statusCode(403).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + }); + }).rejects.toThrow(Intercom.unstable.ForbiddenError); + }); + + test("getWhatsAppMessageStatus (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/messages/status").respondWith().statusCode(500).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.messages.getWhatsAppMessageStatus({ + ruleset_id: "ruleset_id", + }); + }).rejects.toThrow(Intercom.unstable.InternalServerError); + }); +}); diff --git a/tests/wire/unstable/news.test.ts b/tests/wire/unstable/news.test.ts new file mode 100644 index 00000000..6ee5092f --- /dev/null +++ b/tests/wire/unstable/news.test.ts @@ -0,0 +1,864 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("NewsClient", () => { + test("listNewsItems (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }; + server.mockEndpoint().get("/news/news_items").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.news.listNewsItems(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }); + }); + + test("listNewsItems (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/news_items").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.news.listNewsItems(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createNewsItem (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["😆", "😅"], + newsfeed_assignments: [{ newsfeed_id: 53, published_at: 1664638214 }], + }; + const rawResponseBody = { + type: "news-item", + id: "33", + workspace_id: "this_is_an_id534_that_should_be_at_least_", + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 53, published_at: 1664638214 }], + labels: ["New", "Product", "Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😆", "😅"], + deliver_silently: true, + created_at: 1734537797, + updated_at: 1734537797, + }; + server + .mockEndpoint() + .post("/news/news_items") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.createNewsItem({ + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + deliver_silently: true, + labels: ["Product", "Update", "New"], + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + newsfeed_assignments: [ + { + newsfeed_id: 53, + published_at: 1664638214, + }, + ], + }); + expect(response).toEqual({ + type: "news-item", + id: "33", + workspace_id: "this_is_an_id534_that_should_be_at_least_", + title: "Halloween is here!", + body: "

New costumes in store for this spooky season

", + sender_id: 991267834, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 53, + published_at: 1664638214, + }, + ], + labels: ["New", "Product", "Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE06", "\uD83D\uDE05"], + deliver_silently: true, + created_at: 1734537797, + updated_at: 1734537797, + }); + }); + + test("createNewsItem (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/news/news_items") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.createNewsItem({ + title: "title", + sender_id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveNewsItem (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "news-item", + id: "34", + workspace_id: "this_is_an_id538_that_should_be_at_least_", + title: "We have news", + body: "

Hello there,

", + sender_id: 991267837, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 55, published_at: 1734537800 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍", "👍", "👍", "👍"], + deliver_silently: false, + created_at: 1734537800, + updated_at: 1734537800, + }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.news.retrieveNewsItem({ + id: 1, + }); + expect(response).toEqual({ + type: "news-item", + id: "34", + workspace_id: "this_is_an_id538_that_should_be_at_least_", + title: "We have news", + body: "

Hello there,

", + sender_id: 991267837, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 55, + published_at: 1734537800, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D", "\uD83D\uDC4D", "\uD83D\uDC4D", "\uD83D\uDC4D"], + deliver_silently: false, + created_at: 1734537800, + updated_at: 1734537800, + }); + }); + + test("retrieveNewsItem (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.news.retrieveNewsItem({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveNewsItem (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/news/news_items/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.news.retrieveNewsItem({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateNewsItem (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["😝", "😂"], + }; + const rawResponseBody = { + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😝", "😂"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.updateNewsItem({ + id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + }, + }); + expect(response).toEqual({ + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }); + }); + + test("updateNewsItem (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267848, + reactions: ["😝", "😂"], + }; + const rawResponseBody = { + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["😝", "😂"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.updateNewsItem({ + id: 1, + body: { + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267848, + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + }, + }); + expect(response).toEqual({ + type: "news-item", + id: "37", + workspace_id: "this_is_an_id544_that_should_be_at_least_", + title: "Christmas is here!", + body: "

New gifts in store for the jolly season

", + sender_id: 991267845, + state: "live", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDE1D", "\uD83D\uDE02"], + deliver_silently: false, + created_at: 1734537803, + updated_at: 1734537804, + }); + }); + + test("updateNewsItem (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.updateNewsItem({ + id: 1, + body: { + title: "title", + sender_id: 1, + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateNewsItem (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { title: "title", sender_id: 1 }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/news/news_items/1") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.updateNewsItem({ + id: 1, + body: { + title: "title", + sender_id: 1, + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteNewsItem (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "40", object: "news-item", deleted: true }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.deleteNewsItem({ + id: 1, + }); + expect(response).toEqual({ + id: "40", + object: "news-item", + deleted: true, + }); + }); + + test("deleteNewsItem (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.deleteNewsItem({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteNewsItem (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/news/news_items/1") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.deleteNewsItem({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listLiveNewsfeedItems (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 20, + total_pages: 0, + }, + total_count: 0, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [{ newsfeed_id: 198313, published_at: 1674917488 }], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["👍"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }; + server + .mockEndpoint() + .get("/news/newsfeeds/123/items") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.listLiveNewsfeedItems({ + id: "123", + }); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 20, + total_pages: 0, + }, + total_count: 0, + data: [ + { + type: "news-item", + id: "141", + workspace_id: "t74hdn32", + title: "New feature: News Items", + body: "We are excited to announce the launch of News Items, a new content type in Intercom enabling you to announce product updates, company news, promotions, events and more with your customers.", + sender_id: 123, + state: "draft", + newsfeed_assignments: [ + { + newsfeed_id: 198313, + published_at: 1674917488, + }, + ], + labels: ["Product Update"], + cover_image_url: "https://example.com/cover.jpg", + reactions: ["\uD83D\uDC4D"], + deliver_silently: true, + created_at: 1610589632, + updated_at: 1610589632, + }, + ], + }); + }); + + test("listLiveNewsfeedItems (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/news/newsfeeds/id/items") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.news.listLiveNewsfeedItems({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("listNewsfeeds (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { type: "newsfeed", id: "12312", name: "My Newsfeed", created_at: 1674917488, updated_at: 1674917488 }, + { type: "newsfeed", id: "12312", name: "My Newsfeed", created_at: 1674917488, updated_at: 1674917488 }, + ], + }; + server.mockEndpoint().get("/news/newsfeeds").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.news.listNewsfeeds(); + expect(response).toEqual({ + type: "list", + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 10, + total_pages: 1, + }, + total_count: 2, + data: [ + { + id: "12312", + type: "newsfeed", + name: "My Newsfeed", + created_at: 1674917488, + updated_at: 1674917488, + }, + { + id: "12312", + type: "newsfeed", + name: "My Newsfeed", + created_at: 1674917488, + updated_at: 1674917488, + }, + ], + }); + }); + + test("listNewsfeeds (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/newsfeeds").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.news.listNewsfeeds(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveNewsfeed (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + id: "72", + type: "newsfeed", + name: "Visitor Feed", + created_at: 1734537815, + updated_at: 1734537815, + }; + server + .mockEndpoint() + .get("/news/newsfeeds/123") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.news.retrieveNewsfeed({ + id: "123", + }); + expect(response).toEqual({ + id: "72", + type: "newsfeed", + name: "Visitor Feed", + created_at: 1734537815, + updated_at: 1734537815, + }); + }); + + test("retrieveNewsfeed (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/news/newsfeeds/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.news.retrieveNewsfeed({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/notes.test.ts b/tests/wire/unstable/notes.test.ts new file mode 100644 index 00000000..64bff186 --- /dev/null +++ b/tests/wire/unstable/notes.test.ts @@ -0,0 +1,763 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("NotesClient", () => { + test("listCompanyNotes (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "note", + id: "26", + created_at: 1733932587, + contact: { id: "214656d0c743eafcfde7f248" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "25", + created_at: 1733846187, + contact: { id: "214656d0c743eafcfde7f248" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "24", + created_at: 1733846187, + contact: { id: "214656d0c743eafcfde7f248" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

This is a note.

", + }, + ], + total_count: 3, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 50, + total_pages: 1, + }, + }; + server + .mockEndpoint() + .get("/companies/5f4d3c1c-7b1b-4d7d-a97e-6095715c6632/notes") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.notes.listCompanyNotes({ + id: "5f4d3c1c-7b1b-4d7d-a97e-6095715c6632", + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "note", + id: "26", + created_at: 1733932587, + contact: { + id: "214656d0c743eafcfde7f248", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "25", + created_at: 1733846187, + contact: { + id: "214656d0c743eafcfde7f248", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "24", + created_at: 1733846187, + contact: { + id: "214656d0c743eafcfde7f248", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

This is a note.

", + }, + ], + total_count: 3, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 50, + total_pages: 1, + }, + }); + }); + + test("listCompanyNotes (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .get("/companies/id/notes") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.notes.listCompanyNotes({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listNotes (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "note", + id: "26", + created_at: 1733932587, + contact: { type: "contact", id: "6762f0ab1bb69f9f2193bb60" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "25", + created_at: 1733846187, + contact: { type: "contact", id: "6762f0ab1bb69f9f2193bb60" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "24", + created_at: 1733846187, + contact: { type: "contact", id: "6762f0ab1bb69f9f2193bb60" }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + ], + total_count: 3, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 50, + total_pages: 1, + }, + }; + server.mockEndpoint().get("/contacts/1/notes").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.notes.listNotes({ + id: 1, + }); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "note", + id: "26", + created_at: 1733932587, + contact: { + type: "contact", + id: "6762f0ab1bb69f9f2193bb60", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "25", + created_at: 1733846187, + contact: { + type: "contact", + id: "6762f0ab1bb69f9f2193bb60", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + { + type: "note", + id: "24", + created_at: 1733846187, + contact: { + type: "contact", + id: "6762f0ab1bb69f9f2193bb60", + }, + author: { + type: "admin", + id: "991267581", + name: "Ciaran122 Lee", + email: "admin122@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + }, + body: "

This is a note.

", + }, + ], + total_count: 3, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 50, + total_pages: 1, + }, + }); + }); + + test("listNotes (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/contacts/1/notes").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.notes.listNotes({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("createNote (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", contact_id: "6762f0ad1bb69f9f2193bb62", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/1/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.notes.createNote({ + id: 1, + body: "Hello", + contact_id: "6762f0ad1bb69f9f2193bb62", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("createNote (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", contact_id: "6762f0af1bb69f9f2193bb63", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/1/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.notes.createNote({ + id: 1, + body: "Hello", + contact_id: "6762f0af1bb69f9f2193bb63", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("createNote (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "Hello", contact_id: "123", admin_id: "123" }; + const rawResponseBody = { + type: "note", + id: "31", + created_at: 1734537390, + contact: { type: "contact", id: "6762f0ad1bb69f9f2193bb62" }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

Hello

", + }; + server + .mockEndpoint() + .post("/contacts/1/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.notes.createNote({ + id: 1, + body: "Hello", + contact_id: "123", + admin_id: "123", + }); + expect(response).toEqual({ + type: "note", + id: "31", + created_at: 1734537390, + contact: { + type: "contact", + id: "6762f0ad1bb69f9f2193bb62", + }, + author: { + type: "admin", + id: "991267583", + name: "Ciaran124 Lee", + email: "admin124@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

Hello

", + }); + }); + + test("createNote (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { body: "body" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/1/notes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.notes.createNote({ + id: 1, + body: "body", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("retrieveNote (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "note", + id: "34", + created_at: 1733846617, + contact: { type: "contact", id: "6762f2591bb69f9f2193bc1f" }, + author: { + type: "admin", + id: "991267864", + name: "Ciaran346 Lee", + email: "admin346@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { primary_team_ids: [814865], secondary_team_ids: [493881] }, + }, + body: "

This is a note.

", + }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.notes.retrieveNote({ + id: 1, + }); + expect(response).toEqual({ + type: "note", + id: "34", + created_at: 1733846617, + contact: { + type: "contact", + id: "6762f2591bb69f9f2193bc1f", + }, + author: { + type: "admin", + id: "991267864", + name: "Ciaran346 Lee", + email: "admin346@email.com", + job_title: "Associate", + away_mode_enabled: false, + away_mode_reassign: false, + away_status_reason_id: 12345, + has_inbox_seat: true, + team_ids: [814865], + avatar: "https://picsum.photos/200/300", + team_priority_level: { + primary_team_ids: [814865], + secondary_team_ids: [493881], + }, + }, + body: "

This is a note.

", + }); + }); + + test("retrieveNote (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.notes.retrieveNote({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveNote (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/notes/1").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.notes.retrieveNote({ + id: 1, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/segments.test.ts b/tests/wire/unstable/segments.test.ts new file mode 100644 index 00000000..71d84bae --- /dev/null +++ b/tests/wire/unstable/segments.test.ts @@ -0,0 +1,162 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("SegmentsClient", () => { + test("listSegments (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "segment.list", + segments: [ + { + type: "segment", + id: "6762f25c1bb69f9f2193bc22", + name: "John segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + { + type: "segment", + id: "6762f25c1bb69f9f2193bc23", + name: "Jane segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + ], + pages: { key: "value" }, + }; + server.mockEndpoint().get("/segments").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.segments.listSegments({ + include_count: true, + }); + expect(response).toEqual({ + type: "segment.list", + segments: [ + { + type: "segment", + id: "6762f25c1bb69f9f2193bc22", + name: "John segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + { + type: "segment", + id: "6762f25c1bb69f9f2193bc23", + name: "Jane segment", + created_at: 1734537820, + updated_at: 1734537820, + person_type: "user", + count: 3, + }, + ], + pages: { + key: "value", + }, + }); + }); + + test("listSegments (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/segments").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.segments.listSegments(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveSegment (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "segment", + id: "6762f25f1bb69f9f2193bc26", + name: "John segment", + created_at: 1734537823, + updated_at: 1734537823, + person_type: "user", + count: 3, + }; + server.mockEndpoint().get("/segments/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.segments.retrieveSegment({ + id: "123", + }); + expect(response).toEqual({ + type: "segment", + id: "6762f25f1bb69f9f2193bc26", + name: "John segment", + created_at: 1734537823, + updated_at: 1734537823, + person_type: "user", + count: 3, + }); + }); + + test("retrieveSegment (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/segments/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.segments.retrieveSegment({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveSegment (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/segments/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.segments.retrieveSegment({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/subscriptionTypes.test.ts b/tests/wire/unstable/subscriptionTypes.test.ts new file mode 100644 index 00000000..56304a5e --- /dev/null +++ b/tests/wire/unstable/subscriptionTypes.test.ts @@ -0,0 +1,410 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("SubscriptionTypesClient", () => { + test("attachSubscriptionTypeToContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "37846", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscriptionTypeToContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "37846", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscriptionTypeToContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "invalid_id", consent_type: "opt_in" }; + const rawResponseBody = { + type: "subscription", + id: "106", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "invalid_id", + consent_type: "opt_in", + }); + expect(response).toEqual({ + type: "subscription", + id: "106", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("attachSubscriptionTypeToContact (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", consent_type: "consent_type" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/contact_id/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "contact_id", + id: "id", + consent_type: "consent_type", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachSubscriptionTypeToContact (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", consent_type: "consent_type" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.subscriptionTypes.attachSubscriptionTypeToContact({ + contact_id: "contact_id", + id: "id", + consent_type: "consent_type", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachSubscriptionTypeToContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "subscription", + id: "122", + state: "live", + default_translation: { name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_in", + content_types: ["sms_message"], + }; + server + .mockEndpoint() + .delete("/contacts/63a07ddf05a32042dffac965/subscriptions/37846") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "37846", + }); + expect(response).toEqual({ + type: "subscription", + id: "122", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_in", + content_types: ["sms_message"], + }); + }); + + test("detachSubscriptionTypeToContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/subscriptions/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachSubscriptionTypeToContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/subscriptions/id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.subscriptionTypes.detachSubscriptionTypeToContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listSubscriptionTypes (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "subscription", + id: "135", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [{ name: "Newsletters", description: "Lorem ipsum dolor sit amet", locale: "en" }], + consent_type: "opt_out", + content_types: ["email"], + }, + ], + }; + server + .mockEndpoint() + .get("/subscription_types") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.subscriptionTypes.listSubscriptionTypes(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "subscription", + id: "135", + state: "live", + default_translation: { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + translations: [ + { + name: "Newsletters", + description: "Lorem ipsum dolor sit amet", + locale: "en", + }, + ], + consent_type: "opt_out", + content_types: ["email"], + }, + ], + }); + }); + + test("listSubscriptionTypes (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .get("/subscription_types") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.subscriptionTypes.listSubscriptionTypes(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/switch.test.ts b/tests/wire/unstable/switch.test.ts new file mode 100644 index 00000000..d7ee5321 --- /dev/null +++ b/tests/wire/unstable/switch.test.ts @@ -0,0 +1,113 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("SwitchClient", () => { + test("createPhoneSwitch (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "phone_call_redirect", phone: "phone" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.switch.createPhoneSwitch({ + key: "value", + }); + expect(response).toEqual({ + type: "phone_call_redirect", + phone: "phone", + }); + }); + + test("createPhoneSwitch (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.switch.createPhoneSwitch({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createPhoneSwitch (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.switch.createPhoneSwitch({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createPhoneSwitch (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/phone_call_redirects") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(422) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.switch.createPhoneSwitch({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnprocessableEntityError); + }); +}); diff --git a/tests/wire/unstable/tags.test.ts b/tests/wire/unstable/tags.test.ts new file mode 100644 index 00000000..e7094ebe --- /dev/null +++ b/tests/wire/unstable/tags.test.ts @@ -0,0 +1,1371 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TagsClient", () => { + test("attachTagToContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "123" }; + const rawResponseBody = { + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/contacts/63a07ddf05a32042dffac965/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "81", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToContact (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/contacts/contact_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachTagToContact (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/contacts/contact_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachTagFromContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "tag", + id: "84", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/contacts/63a07ddf05a32042dffac965/tags/7522907") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromContact({ + contact_id: "63a07ddf05a32042dffac965", + id: "7522907", + }); + expect(response).toEqual({ + type: "tag", + id: "84", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/contacts/contact_id/tags/id") + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachTagFromContact (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/contacts/contact_id/tags/id") + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromContact({ + contact_id: "contact_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("attachTagToConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/conversations/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/conversations/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "86", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/conversations/conversation_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachTagToConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/conversations/conversation_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachTagFromConversation (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromConversation (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromConversation (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/conversations/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromConversation({ + conversation_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "89", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromConversation (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/tags/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachTagFromConversation (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/conversations/conversation_id/tags/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromConversation({ + conversation_id: "conversation_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("listTags (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "tag", + id: "102", + name: "Manual tag 1", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }, + ], + }; + server.mockEndpoint().get("/tags").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.tags.listTags(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "tag", + id: "102", + name: "Manual tag 1", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }, + ], + }); + }); + + test("listTags (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tags").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.listTags(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createTag (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test" }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.createTag({ + name: "test", + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("createTag (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "Independent" }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.createTag({ + name: "Independent", + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("createTag (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test", companies: [{ company_id: "123" }] }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.createTag({ + name: "test", + companies: [ + { + company_id: "123", + }, + ], + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("createTag (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "test", users: [{ id: "123" }] }; + const rawResponseBody = { + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.createTag({ + name: "test", + users: [ + { + id: "123", + }, + ], + }); + expect(response).toEqual({ + type: "tag", + id: "105", + name: "test", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("createTag (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.createTag({ + name: "name", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("createTag (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.createTag({ + name: "name", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createTag (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.createTag({ + name: "name", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("findTag (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "tag", + id: "113", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server.mockEndpoint().get("/tags/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.tags.findTag({ + id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "113", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("findTag (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tags/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.findTag({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("findTag (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/tags/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.findTag({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteTag (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + server.mockEndpoint().delete("/tags/123").respondWith().statusCode(200).build(); + + const response = await client.unstable.tags.deleteTag({ + id: "123", + }); + expect(response).toEqual(undefined); + }); + + test("deleteTag (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/tags/id").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.deleteTag({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("deleteTag (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/tags/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.deleteTag({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteTag (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/tags/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tags.deleteTag({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("attachTagToTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tickets/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "7522907", admin_id: "780" }; + const rawResponseBody = { + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .post("/tickets/64619700005694/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.attachTagToTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "780", + }); + expect(response).toEqual({ + type: "tag", + id: "121", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("attachTagToTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/ticket_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("attachTagToTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id", admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/ticket_id/tags") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.attachTagToTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("detachTagFromTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "123" }; + const rawResponseBody = { + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { type: "contact", id: "1a2b3c" }, + }; + server + .mockEndpoint() + .delete("/tickets/64619700005694/tags/7522907") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tags.detachTagFromTicket({ + ticket_id: "64619700005694", + id: "7522907", + admin_id: "123", + }); + expect(response).toEqual({ + type: "tag", + id: "124", + name: "Manual tag", + applied_at: 1663597223, + applied_by: { + type: "contact", + id: "1a2b3c", + }, + }); + }); + + test("detachTagFromTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .delete("/tickets/ticket_id/tags/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("detachTagFromTicket (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { admin_id: "admin_id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .delete("/tickets/ticket_id/tags/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tags.detachTagFromTicket({ + ticket_id: "ticket_id", + id: "id", + admin_id: "admin_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/teams.test.ts b/tests/wire/unstable/teams.test.ts new file mode 100644 index 00000000..f25b2268 --- /dev/null +++ b/tests/wire/unstable/teams.test.ts @@ -0,0 +1,136 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TeamsClient", () => { + test("listTeams (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "team.list", + teams: [ + { + type: "team", + id: "814865", + name: "Example Team", + admin_ids: [493881], + admin_priority_level: { primary_admin_ids: [493881], secondary_admin_ids: [814865] }, + }, + ], + }; + server.mockEndpoint().get("/teams").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.teams.listTeams(); + expect(response).toEqual({ + type: "team.list", + teams: [ + { + type: "team", + id: "814865", + name: "Example Team", + admin_ids: [493881], + admin_priority_level: { + primary_admin_ids: [493881], + secondary_admin_ids: [814865], + }, + }, + ], + }); + }); + + test("listTeams (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/teams").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.teams.listTeams(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveTeam (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "team", + id: "991267902", + name: "team 1", + admin_ids: [493881], + admin_priority_level: { primary_admin_ids: [493881], secondary_admin_ids: [814865] }, + }; + server.mockEndpoint().get("/teams/123").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.teams.retrieveTeam({ + id: "123", + }); + expect(response).toEqual({ + type: "team", + id: "991267902", + name: "team 1", + admin_ids: [493881], + admin_priority_level: { + primary_admin_ids: [493881], + secondary_admin_ids: [814865], + }, + }); + }); + + test("retrieveTeam (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/teams/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.teams.retrieveTeam({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveTeam (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/teams/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.teams.retrieveTeam({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); +}); diff --git a/tests/wire/unstable/ticketStates.test.ts b/tests/wire/unstable/ticketStates.test.ts new file mode 100644 index 00000000..21e2b43c --- /dev/null +++ b/tests/wire/unstable/ticketStates.test.ts @@ -0,0 +1,504 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TicketStatesClient", () => { + test("listTicketStates (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "ticket_state", + id: "8269", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8270", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8271", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8272", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8273", + category: "submitted", + internal_label: "Admin label 1", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8274", + category: "submitted", + internal_label: "Admin label 2", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + ], + }; + server.mockEndpoint().get("/ticket_states").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.ticketStates.listTicketStates(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "ticket_state", + id: "8269", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8270", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8271", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8272", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8273", + category: "submitted", + internal_label: "Admin label 1", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "55", + category: "Back-office", + name: "my-ticket-type-3", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + { + type: "ticket_type", + id: "56", + category: "Back-office", + name: "my-ticket-type-4", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + { + type: "ticket_state", + id: "8274", + category: "submitted", + internal_label: "Admin label 2", + external_label: "User label", + archived: false, + ticket_types: { + type: "list", + data: [ + { + type: "ticket_type", + id: "58", + category: "Back-office", + name: "my-ticket-type-6", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "ecahpwf5", + archived: false, + }, + ], + }, + }, + ], + }); + }); + + test("listTicketStates (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ticket_states").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.ticketStates.listTicketStates(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/ticketTypeAttributes.test.ts b/tests/wire/unstable/ticketTypeAttributes.test.ts new file mode 100644 index 00000000..83b633bd --- /dev/null +++ b/tests/wire/unstable/ticketTypeAttributes.test.ts @@ -0,0 +1,200 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TicketTypeAttributesClient", () => { + test("createTicketTypeAttribute (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false, + }; + const rawResponseBody = { + type: "ticket_type_attribute", + id: "157", + workspace_id: "this_is_an_id640_that_should_be_at_least_", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + input_options: { multiline: false }, + order: 2, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: true, + visible_to_contacts: true, + default: false, + ticket_type_id: 63, + archived: false, + created_at: 1734537862, + updated_at: 1734537862, + }; + server + .mockEndpoint() + .post("/ticket_types/ticket_type_id/attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + required_to_create: false, + }); + expect(response).toEqual({ + type: "ticket_type_attribute", + id: "157", + workspace_id: "this_is_an_id640_that_should_be_at_least_", + name: "Attribute Title", + description: "Attribute Description", + data_type: "string", + input_options: { + multiline: false, + }, + order: 2, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: true, + visible_to_contacts: true, + default: false, + ticket_type_id: 63, + archived: false, + created_at: 1734537862, + updated_at: 1734537862, + }); + }); + + test("createTicketTypeAttribute (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { name: "name", description: "description", data_type: "string" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ticket_types/ticket_type_id/attributes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.ticketTypeAttributes.createTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + name: "name", + description: "description", + data_type: "string", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateTicketTypeAttribute (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { description: "New Attribute Description" }; + const rawResponseBody = { + type: "ticket_type_attribute", + id: "162", + workspace_id: "this_is_an_id644_that_should_be_at_least_", + name: "name", + description: "New Attribute Description", + data_type: "string", + input_options: { key: "value" }, + order: 0, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: false, + ticket_type_id: 65, + archived: false, + created_at: 1734537864, + updated_at: 1734537864, + }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id/attributes/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + id: "id", + description: "New Attribute Description", + }); + expect(response).toEqual({ + type: "ticket_type_attribute", + id: "162", + workspace_id: "this_is_an_id644_that_should_be_at_least_", + name: "name", + description: "New Attribute Description", + data_type: "string", + input_options: { + key: "value", + }, + order: 0, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: false, + ticket_type_id: 65, + archived: false, + created_at: 1734537864, + updated_at: 1734537864, + }); + }); + + test("updateTicketTypeAttribute (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/ticket_types/ticket_type_id/attributes/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.ticketTypeAttributes.updateTicketTypeAttribute({ + ticket_type_id: "ticket_type_id", + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/ticketTypes.test.ts b/tests/wire/unstable/ticketTypes.test.ts new file mode 100644 index 00000000..95efe063 --- /dev/null +++ b/tests/wire/unstable/ticketTypes.test.ts @@ -0,0 +1,518 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TicketTypesClient", () => { + test("listTicketTypes (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "list", + data: [ + { + type: "ticket_type", + id: "67", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id648_that_should_be_at_least_", + ticket_type_attributes: { type: "list" }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8321", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8322", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8323", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8324", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537866, + updated_at: 1734537866, + }, + ], + }; + server.mockEndpoint().get("/ticket_types").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.ticketTypes.listTicketTypes(); + expect(response).toEqual({ + type: "list", + data: [ + { + type: "ticket_type", + id: "67", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id648_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8321", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8322", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8323", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8324", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537866, + updated_at: 1734537866, + }, + ], + }); + }); + + test("listTicketTypes (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ticket_types").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.ticketTypes.listTicketTypes(); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("createTicketType (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { + type: "type", + id: "id", + category: "Customer", + name: "name", + description: "description", + icon: "icon", + workspace_id: "workspace_id", + ticket_type_attributes: { + type: "type", + ticket_type_attributes: [ + { + type: "type", + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + data_type: "data_type", + input_options: { input_options: { key: "value" } }, + order: 1, + required_to_create: true, + required_to_create_for_contacts: true, + visible_on_create: true, + visible_to_contacts: true, + default: true, + ticket_type_id: 1, + archived: true, + created_at: 1, + updated_at: 1, + }, + { + type: "type", + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + data_type: "data_type", + input_options: { input_options: { key: "value" } }, + order: 1, + required_to_create: true, + required_to_create_for_contacts: true, + visible_on_create: true, + visible_to_contacts: true, + default: true, + ticket_type_id: 1, + archived: true, + created_at: 1, + updated_at: 1, + }, + ], + }, + ticket_states: { + type: "type", + data: [ + { + type: "type", + id: "id", + category: "submitted", + internal_label: "internal_label", + external_label: "external_label", + }, + { + type: "type", + id: "id", + category: "submitted", + internal_label: "internal_label", + external_label: "external_label", + }, + ], + }, + archived: true, + created_at: 1, + updated_at: 1, + }; + server + .mockEndpoint() + .post("/ticket_types") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.ticketTypes.createTicketType({ + key: "value", + }); + expect(response).toEqual({ + type: "type", + id: "id", + category: "Customer", + name: "name", + description: "description", + icon: "icon", + workspace_id: "workspace_id", + ticket_type_attributes: { + type: "type", + ticket_type_attributes: [ + { + type: "type", + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + data_type: "data_type", + input_options: { + input_options: { + key: "value", + }, + }, + order: 1, + required_to_create: true, + required_to_create_for_contacts: true, + visible_on_create: true, + visible_to_contacts: true, + default: true, + ticket_type_id: 1, + archived: true, + created_at: 1, + updated_at: 1, + }, + { + type: "type", + id: "id", + workspace_id: "workspace_id", + name: "name", + description: "description", + data_type: "data_type", + input_options: { + input_options: { + key: "value", + }, + }, + order: 1, + required_to_create: true, + required_to_create_for_contacts: true, + visible_on_create: true, + visible_to_contacts: true, + default: true, + ticket_type_id: 1, + archived: true, + created_at: 1, + updated_at: 1, + }, + ], + }, + ticket_states: { + type: "type", + data: [ + { + type: "type", + id: "id", + category: "submitted", + internal_label: "internal_label", + external_label: "external_label", + }, + { + type: "type", + id: "id", + category: "submitted", + internal_label: "internal_label", + external_label: "external_label", + }, + ], + }, + archived: true, + created_at: 1, + updated_at: 1, + }); + }); + + test("createTicketType (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/ticket_types") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.ticketTypes.createTicketType({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getTicketType (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "ticket_type", + id: "72", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "🎟️", + workspace_id: "this_is_an_id656_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + data_type: "string", + input_options: { key: "value" }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8353", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8354", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8355", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8356", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537870, + updated_at: 1734537870, + }; + server.mockEndpoint().get("/ticket_types/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.ticketTypes.getTicketType({ + id: "id", + }); + expect(response).toEqual({ + type: "ticket_type", + id: "72", + category: "Customer", + name: "Bug Report", + description: "Bug Report Template", + icon: "\uD83C\uDF9F\uFE0F", + workspace_id: "this_is_an_id656_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [ + { + type: "ticket_type_attribute", + id: "1", + workspace_id: "ecahpwf5", + name: "Title", + description: "Bug title.", + data_type: "string", + input_options: { + key: "value", + }, + order: 1, + required_to_create: false, + required_to_create_for_contacts: false, + visible_on_create: false, + visible_to_contacts: false, + default: true, + ticket_type_id: 42, + archived: false, + }, + ], + }, + ticket_states: { + type: "list", + data: [ + { + type: "ticket_state", + id: "8353", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + { + type: "ticket_state", + id: "8354", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + { + type: "ticket_state", + id: "8355", + category: "waiting_on_customer", + internal_label: "Waiting on customer", + external_label: "Waiting on you", + }, + { + type: "ticket_state", + id: "8356", + category: "resolved", + internal_label: "Resolved", + external_label: "Resolved", + }, + ], + }, + archived: false, + created_at: 1734537870, + updated_at: 1734537870, + }); + }); + + test("getTicketType (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/ticket_types/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.ticketTypes.getTicketType({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/unstable/tickets.test.ts b/tests/wire/unstable/tickets.test.ts new file mode 100644 index 00000000..d1c30b68 --- /dev/null +++ b/tests/wire/unstable/tickets.test.ts @@ -0,0 +1,3265 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("TicketsClient", () => { + test("replyTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.replyTicket({ + id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2971bb69f9f2193bc49", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("replyTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.replyTicket({ + id: "123", + body: { + message_type: "note", + type: "admin", + body: "

An Unordered HTML List

  • Coffee
  • Tea
  • Milk

An Ordered HTML List

  1. Coffee
  2. Tea
  3. Milk
", + admin_id: "3156780", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("replyTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { text: "Yes", uuid: "0df48b85-9a93-4c66-a167-753eff0baaec" }, + { text: "No", uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938" }, + ], + }; + const rawResponseBody = { + type: "ticket_part", + id: "158", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537890, + updated_at: 1734537890, + author: { type: "admin", id: "991267948", name: "Ciaran423 Lee", email: "admin423@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.replyTicket({ + id: "123", + body: { + message_type: "quick_reply", + type: "admin", + admin_id: "3156780", + reply_options: [ + { + text: "Yes", + uuid: "0df48b85-9a93-4c66-a167-753eff0baaec", + }, + { + text: "No", + uuid: "4f0b5145-4193-4b4f-8cad-ce19478a3938", + }, + ], + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "158", + part_type: "quick_reply", + body: "

Okay!

", + created_at: 1734537890, + updated_at: 1734537890, + author: { + type: "admin", + id: "991267948", + name: "Ciaran423 Lee", + email: "admin423@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("replyTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2a41bb69f9f2193bc4c", + }; + const rawResponseBody = { + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { type: "admin", id: "991267943", name: "Ciaran419 Lee", email: "admin419@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }; + server + .mockEndpoint() + .post("/tickets/123/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.replyTicket({ + id: "123", + body: { + message_type: "comment", + type: "user", + body: "Thanks again :)", + intercom_user_id: "6762f2a41bb69f9f2193bc4c", + }, + }); + expect(response).toEqual({ + type: "ticket_part", + id: "156", + part_type: "note", + body: "

An Unordered HTML List

\n
    \n
  • Coffee
  • \n
  • Tea
  • \n
  • Milk
  • \n
\n

An Ordered HTML List

\n
    \n
  1. Coffee
  2. \n
  3. Tea
  4. \n
  5. Milk
  6. \n
", + created_at: 1734537884, + updated_at: 1734537884, + author: { + type: "admin", + id: "991267943", + name: "Ciaran419 Lee", + email: "admin419@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + redacted: false, + }); + }); + + test("replyTicket (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.replyTicket({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("replyTicket (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.replyTicket({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("replyTicket (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/id/reply") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.replyTicket({ + id: "id", + body: { + intercom_user_id: "intercom_user_id", + message_type: "comment", + type: "user", + body: "body", + }, + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("enqueueCreateTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "1234", contacts: [{ id: "6762f2d81bb69f9f2193bc54" }] }; + const rawResponseBody = { + type: "job", + id: "20", + url: "https://api.intercom.io/jobs/status/20", + status: "pending", + resource_type: "ticket", + resource_id: "resource_id", + resource_url: "http://api.intercom.io/tickets/123", + }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.enqueueCreateTicket({ + ticket_type_id: "1234", + contacts: [ + { + id: "6762f2d81bb69f9f2193bc54", + }, + ], + }); + expect(response).toEqual({ + type: "job", + id: "20", + url: "https://api.intercom.io/jobs/status/20", + status: "pending", + resource_type: "ticket", + resource_id: "resource_id", + resource_url: "http://api.intercom.io/tickets/123", + }); + }); + + test("enqueueCreateTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id", contacts: [{ id: "id" }, { id: "id" }] }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.enqueueCreateTicket({ + ticket_type_id: "ticket_type_id", + contacts: [ + { + id: "id", + }, + { + id: "id", + }, + ], + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("enqueueCreateTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_type_id: "ticket_type_id", contacts: [{ id: "id" }, { id: "id" }] }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/tickets/enqueue") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.enqueueCreateTicket({ + ticket_type_id: "ticket_type_id", + contacts: [ + { + id: "id", + }, + { + id: "id", + }, + ], + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("getTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "ticket", + id: "631", + ticket_id: "38", + category: "Back-office", + ticket_attributes: { _default_title_: "attribute_value", _default_description_: "ticket_attributes" }, + ticket_state: { + type: "ticket_state", + id: "8537", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "95", + category: "Back-office", + name: "my-ticket-type-30", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id702_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537973, + updated_at: 1734537973, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2f61bb69f9f2193bc59", + external_id: "b16afa36-2637-4880-adee-a46d145bc27f", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537974, + updated_at: 1734537976, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "185", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537975, + updated_at: 1734537975, + author: { type: "admin", id: "991268047", name: "Ciaran509 Lee", email: "admin509@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }; + server.mockEndpoint().get("/tickets/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.tickets.getTicket({ + id: "id", + }); + expect(response).toEqual({ + type: "ticket", + id: "631", + ticket_id: "38", + category: "Back-office", + ticket_attributes: { + _default_title_: "attribute_value", + _default_description_: "ticket_attributes", + }, + ticket_state: { + type: "ticket_state", + id: "8537", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "95", + category: "Back-office", + name: "my-ticket-type-30", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id702_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537973, + updated_at: 1734537973, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2f61bb69f9f2193bc59", + external_id: "b16afa36-2637-4880-adee-a46d145bc27f", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537974, + updated_at: 1734537976, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "185", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537975, + updated_at: 1734537975, + author: { + type: "admin", + id: "991268047", + name: "Ciaran509 Lee", + email: "admin509@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }); + }); + + test("getTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/tickets/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tickets.getTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.updateTicket({ + id: "id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + open: true, + snoozed_until: 1673609604, + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("updateTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.updateTicket({ + id: "id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("updateTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.updateTicket({ + id: "id", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state_id: "123", + admin_id: 991268011, + assignee_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("updateTicket (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { ticket_state_id: "123" }; + const rawResponseBody = { + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { _default_title_: "example", _default_description_: "there is a problem" }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { type: "list", ticket_type_attributes: [] }, + ticket_states: { type: "list", data: [] }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "10", label: "Photo" }, + value: { type: "value", id: [2], label: ["photo.png"] }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { type: "attribute", id: "7", label: "Progress" }, + value: { type: "value", id: "Fast", label: "Fast" }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { type: "admin", id: "991268013" }, + author: { type: "admin", id: "991268011", name: "Ciaran477 Lee", email: "admin477@email.com" }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.updateTicket({ + id: "id", + ticket_state_id: "123", + }); + expect(response).toEqual({ + type: "ticket", + id: "627", + ticket_id: "34", + category: "Back-office", + ticket_attributes: { + _default_title_: "example", + _default_description_: "there is a problem", + }, + ticket_state: { + type: "ticket_state", + id: "8498", + category: "in_progress", + internal_label: "In progress", + external_label: "In progress", + }, + ticket_type: { + type: "ticket_type", + id: "90", + category: "Back-office", + name: "my-ticket-type-25", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id692_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + ticket_type_attributes: [], + }, + ticket_states: { + type: "list", + data: [], + }, + archived: false, + created_at: 1734537948, + updated_at: 1734537948, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f2dd1bb69f9f2193bc55", + external_id: "8df1fa21-b41d-4621-9229-d6f7a3a590ce", + }, + ], + }, + admin_assignee_id: "991268013", + team_assignee_id: "0", + created_at: 1734537950, + updated_at: 1734537955, + open: true, + snoozed_until: 1734627600, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "176", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537951, + updated_at: 1734537951, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "177", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "10", + label: "Photo", + }, + value: { + type: "value", + id: [2], + label: ["photo.png"], + }, + }, + }, + { + type: "ticket_part", + id: "178", + part_type: "ticket_attribute_updated_by_admin", + body: "

Okay!

", + created_at: 1734537953, + updated_at: 1734537953, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + updated_attribute_data: { + attribute: { + type: "attribute", + id: "7", + label: "Progress", + }, + value: { + type: "value", + id: "Fast", + label: "Fast", + }, + }, + }, + { + type: "ticket_part", + id: "179", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "in_progress", + created_at: 1734537954, + updated_at: 1734537954, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "test-integration", + }, + { + type: "ticket_part", + id: "180", + part_type: "assignment", + body: "

Okay!

", + created_at: 1734537954, + updated_at: 1734537954, + assigned_to: { + type: "admin", + id: "991268013", + }, + author: { + type: "admin", + id: "991268011", + name: "Ciaran477 Lee", + email: "admin477@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + { + type: "ticket_part", + id: "181", + part_type: "snoozed", + body: "

Okay!

", + created_at: 1734537955, + updated_at: 1734537955, + author: { + type: "bot", + id: "991268012", + name: "Fin", + email: "operator+this_is_an_id692_that_should_be_at_least_@intercom.io", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 6, + }, + is_shared: false, + }); + }); + + test("updateTicket (5)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(400) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.updateTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.BadRequestError); + }); + + test("updateTicket (6)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.updateTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateTicket (7)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = {}; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/tickets/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.tickets.updateTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("deleteTicket (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { id: "632", object: "ticket", deleted: true }; + server.mockEndpoint().delete("/tickets/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.tickets.deleteTicket({ + id: "id", + }); + expect(response).toEqual({ + id: "632", + object: "ticket", + deleted: true, + }); + }); + + test("deleteTicket (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().delete("/tickets/id").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tickets.deleteTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("deleteTicket (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().delete("/tickets/id").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.tickets.deleteTicket({ + id: "id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("searchTickets", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + query: { operator: "AND", value: [{ field: "created_at", operator: ">", value: "1306054154" }] }, + pagination: { per_page: 5 }, + }; + const rawResponseBody = { + type: "ticket.list", + tickets: [ + { + type: "ticket", + id: "633", + ticket_id: "40", + category: "Back-office", + ticket_attributes: { _default_title_: "attribute_value", _default_description_: undefined }, + ticket_state: { + type: "ticket_state", + id: "8577", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "100", + category: "Back-office", + name: "my-ticket-type-35", + description: "my ticket type description is awesome.", + icon: "🦁", + workspace_id: "this_is_an_id712_that_should_be_at_least_", + ticket_type_attributes: { type: "list" }, + archived: false, + created_at: 1734537989, + updated_at: 1734537989, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f3061bb69f9f2193bc5b", + external_id: "9b913927-c084-4391-b1db-098341b5ffe3", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537990, + updated_at: 1734537992, + open: true, + snoozed_until: 1663597260, + linked_objects: { type: "list", total_count: 0, has_more: false, data: [{ id: "7583" }] }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "188", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537991, + updated_at: 1734537991, + author: { + type: "admin", + id: "991268079", + name: "Ciaran539 Lee", + email: "admin539@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { per_page: 2, starting_after: "your-cursor-from-response" }, + per_page: 5, + total_pages: 1, + }, + }; + server + .mockEndpoint() + .post("/tickets/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.tickets.searchTickets({ + query: { + operator: "AND", + value: [ + { + field: "created_at", + operator: ">", + value: "1306054154", + }, + ], + }, + pagination: { + per_page: 5, + }, + }); + expect(response).toEqual({ + type: "ticket.list", + tickets: [ + { + type: "ticket", + id: "633", + ticket_id: "40", + category: "Back-office", + ticket_attributes: { + _default_title_: "attribute_value", + }, + ticket_state: { + type: "ticket_state", + id: "8577", + category: "submitted", + internal_label: "Submitted", + external_label: "Submitted", + }, + ticket_type: { + type: "ticket_type", + id: "100", + category: "Back-office", + name: "my-ticket-type-35", + description: "my ticket type description is awesome.", + icon: "\uD83E\uDD81", + workspace_id: "this_is_an_id712_that_should_be_at_least_", + ticket_type_attributes: { + type: "list", + }, + archived: false, + created_at: 1734537989, + updated_at: 1734537989, + }, + contacts: { + type: "contact.list", + contacts: [ + { + type: "contact", + id: "6762f3061bb69f9f2193bc5b", + external_id: "9b913927-c084-4391-b1db-098341b5ffe3", + }, + ], + }, + admin_assignee_id: "0", + team_assignee_id: "0", + created_at: 1734537990, + updated_at: 1734537992, + open: true, + snoozed_until: 1663597260, + linked_objects: { + type: "list", + total_count: 0, + has_more: false, + data: [ + { + id: "7583", + }, + ], + }, + ticket_parts: { + type: "ticket_part.list", + ticket_parts: [ + { + type: "ticket_part", + id: "188", + part_type: "ticket_state_updated_by_admin", + body: "

Okay!

", + previous_ticket_state: "submitted", + ticket_state: "submitted", + created_at: 1734537991, + updated_at: 1734537991, + author: { + type: "admin", + id: "991268079", + name: "Ciaran539 Lee", + email: "admin539@email.com", + }, + attachments: [ + { + type: "upload", + name: "example.png", + url: "https://picsum.photos/200/300", + content_type: "image/png", + filesize: 100, + width: 100, + height: 100, + }, + ], + external_id: "abcd1234", + redacted: false, + app_package_code: "text-integration", + }, + ], + total_count: 1, + }, + is_shared: false, + }, + ], + total_count: 1, + pages: { + type: "pages", + page: 1, + next: { + per_page: 2, + starting_after: "your-cursor-from-response", + }, + per_page: 5, + total_pages: 1, + }, + }); + }); +}); diff --git a/tests/wire/unstable/visitors.test.ts b/tests/wire/unstable/visitors.test.ts new file mode 100644 index 00000000..b9c5c9b0 --- /dev/null +++ b/tests/wire/unstable/visitors.test.ts @@ -0,0 +1,866 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../../src/api/index"; +import { IntercomClient } from "../../../src/Client"; +import { mockServerPool } from "../../mock-server/MockServerPool"; + +describe("VisitorsClient", () => { + test("retrieveVisitorWithUserId (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "visitor", + id: "6762f3101bb69f9f2193bc64", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Jane Doe", + pseudonym: "Red Duck from Dublin", + avatar: { type: "avatar", image_url: "https://example.com/avatar.png" }, + app_id: "this_is_an_id722_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734538000, + remote_created_at: 1734538000, + signed_up_at: 1734538000, + updated_at: 1734538000, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.unstable.visitors.retrieveVisitorWithUserId({ + user_id: "user_id", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f3101bb69f9f2193bc64", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Jane Doe", + pseudonym: "Red Duck from Dublin", + avatar: { + type: "avatar", + image_url: "https://example.com/avatar.png", + }, + app_id: "this_is_an_id722_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734538000, + remote_created_at: 1734538000, + signed_up_at: 1734538000, + updated_at: 1734538000, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("retrieveVisitorWithUserId (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.visitors.retrieveVisitorWithUserId({ + user_id: "user_id", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("retrieveVisitorWithUserId (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.unstable.visitors.retrieveVisitorWithUserId({ + user_id: "user_id", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("updateVisitor (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "6762f30c1bb69f9f2193bc5e", name: "Gareth Bale" }; + const rawResponseBody = { + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.visitors.updateVisitor({ + id: "6762f30c1bb69f9f2193bc5e", + name: "Gareth Bale", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("updateVisitor (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { user_id: "fail", name: "Christian Fail" }; + const rawResponseBody = { + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.visitors.updateVisitor({ + user_id: "fail", + name: "Christian Fail", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: "custom_attributes", + monthly_spend: "custom_attributes", + team_mates: "custom_attributes", + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("updateVisitor (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.visitors.updateVisitor({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); + + test("updateVisitor (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { key: "value" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.visitors.updateVisitor({ + key: "value", + }); + }).rejects.toThrow(Intercom.unstable.NotFoundError); + }); + + test("convertVisitor (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "user", + user: { email: "foo@bar.com" }, + visitor: { user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3" }, + }; + const rawResponseBody = { + type: "contact", + id: "6762f3141bb69f9f2193bc6b", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id728_that_should_be_at_least_", + role: "user", + email: "foo@bar.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734538004, + updated_at: 1734538005, + signed_up_at: 1734538004, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: { type: "avatar", image_url: "https://example.org/128Wash.jpg" }, + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { + data: [{ type: "social_profile", name: "Facebook", url: "http://twitter.com/th1sland" }], + }, + }; + server + .mockEndpoint() + .post("/visitors/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.unstable.visitors.convertVisitor({ + type: "user", + user: { + email: "foo@bar.com", + }, + visitor: { + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + }, + }); + expect(response).toEqual({ + type: "contact", + id: "6762f3141bb69f9f2193bc6b", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id728_that_should_be_at_least_", + role: "user", + email: "foo@bar.com", + email_domain: "example.com", + phone: "+1123456789", + formatted_phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734538004, + updated_at: 1734538005, + signed_up_at: 1734538004, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: { + type: "avatar", + image_url: "https://example.org/128Wash.jpg", + }, + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + type: "social_profile", + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + }); + }); + + test("convertVisitor (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { type: "type", user: { key: "value" }, visitor: { key: "value" } }; + const rawResponseBody = { type: "type", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/visitors/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.unstable.visitors.convertVisitor({ + type: "type", + user: { + key: "value", + }, + visitor: { + key: "value", + }, + }); + }).rejects.toThrow(Intercom.unstable.UnauthorizedError); + }); +}); diff --git a/tests/wire/visitors.test.ts b/tests/wire/visitors.test.ts new file mode 100644 index 00000000..7adbb5f2 --- /dev/null +++ b/tests/wire/visitors.test.ts @@ -0,0 +1,847 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as Intercom from "../../src/api/index"; +import { IntercomClient } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("VisitorsClient", () => { + test("find (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { + type: "visitor", + id: "6762f3101bb69f9f2193bc64", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Jane Doe", + pseudonym: "Red Duck from Dublin", + avatar: { type: "avatar", image_url: "https://example.com/avatar.png" }, + app_id: "this_is_an_id722_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { paid_subscriber: true, monthly_spend: 155.5, team_mates: 9 }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734538000, + remote_created_at: 1734538000, + signed_up_at: 1734538000, + updated_at: 1734538000, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.visitors.find({ + user_id: "user_id", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f3101bb69f9f2193bc64", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Jane Doe", + pseudonym: "Red Duck from Dublin", + avatar: { + type: "avatar", + image_url: "https://example.com/avatar.png", + }, + app_id: "this_is_an_id722_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: true, + monthly_spend: 155.5, + team_mates: 9, + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734538000, + remote_created_at: 1734538000, + signed_up_at: 1734538000, + updated_at: 1734538000, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("find (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.visitors.find({ + user_id: "user_id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("find (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + + const rawResponseBody = { key: "value" }; + server.mockEndpoint().get("/visitors").respondWith().statusCode(404).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.visitors.find({ + user_id: "user_id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("update (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "6762f30c1bb69f9f2193bc5e", name: "Gareth Bale" }; + const rawResponseBody = { + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { paid_subscriber: true, monthly_spend: 155.5, team_mates: 9 }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.visitors.update({ + id: "6762f30c1bb69f9f2193bc5e", + name: "Gareth Bale", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: true, + monthly_spend: 155.5, + team_mates: 9, + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("update (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { user_id: "fail", name: "Christian Fail" }; + const rawResponseBody = { + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { paid_subscriber: true, monthly_spend: 155.5, team_mates: 9 }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { type: "social_profile.list", social_profiles: ["social_profiles"] }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { type: "tag.list", tags: [{ id: "8482", name: "tag_name" }] }, + segments: { type: "segment.list", segments: ["segments"] }, + custom_attributes: { key: "value" }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.visitors.update({ + user_id: "fail", + name: "Christian Fail", + }); + expect(response).toEqual({ + type: "visitor", + id: "6762f30c1bb69f9f2193bc5e", + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + anonymous: true, + email: "", + phone: "555-555-5555", + name: "Gareth Bale", + pseudonym: "Violet Suitcase", + avatar: { + type: "avatar", + image_url: "https://static.intercomassets.com/app/pseudonym_avatars_2019/violet-suitcase.png", + }, + app_id: "this_is_an_id716_that_should_be_at_least_", + companies: { + type: "company.list", + companies: [ + { + id: "531ee472cce572a6ec000006", + name: "Blue Sun", + app_id: "ecahpwf5", + company_id: "6", + remote_created_at: 1663597223, + created_at: 1663597223, + updated_at: 1663597223, + last_request_at: 1663597223, + size: 100, + website: "https://www.intercom.com", + industry: "Software", + monthly_spend: 100, + session_count: 100, + user_count: 100, + custom_attributes: { + paid_subscriber: true, + monthly_spend: 155.5, + team_mates: 9, + }, + }, + ], + }, + location_data: { + type: "location_data", + city_name: "Dublin", + continent_code: "EU", + country_code: "IRL", + country_name: "Ireland", + postal_code: "D02 N960", + region_name: "Leinster", + timezone: "Europe/Dublin", + }, + las_request_at: 1663597260, + created_at: 1734537996, + remote_created_at: 1734537996, + signed_up_at: 1734537996, + updated_at: 1734537997, + session_count: 0, + social_profiles: { + type: "social_profile.list", + social_profiles: ["social_profiles"], + }, + owner_id: "5169261", + unsubscribed_from_emails: false, + marked_email_as_spam: false, + has_hard_bounced: false, + tags: { + type: "tag.list", + tags: [ + { + id: "8482", + name: "tag_name", + }, + ], + }, + segments: { + type: "segment.list", + segments: ["segments"], + }, + custom_attributes: { + key: "value", + }, + referrer: "https://www.google.com/", + utm_campaign: "intercom-link", + utm_content: "banner", + utm_medium: "email", + utm_source: "Intercom", + utm_term: "messenger", + do_not_track: false, + }); + }); + + test("update (3)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.visitors.update({ + id: "id", + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); + + test("update (4)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { id: "id" }; + const rawResponseBody = { key: "value" }; + server + .mockEndpoint() + .put("/visitors") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(404) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.visitors.update({ + id: "id", + }); + }).rejects.toThrow(Intercom.NotFoundError); + }); + + test("mergeToContact (1)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { + type: "user", + user: { id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", email: "foo@bar.com" }, + visitor: { user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3" }, + }; + const rawResponseBody = { + type: "contact", + id: "6762f3141bb69f9f2193bc6b", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id728_that_should_be_at_least_", + role: "user", + email: "foo@bar.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734538004, + updated_at: 1734538005, + signed_up_at: 1734538004, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { key: "value" }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [{ type: "note", id: "123", url: "/contacts/5ba682d23d7cf92bef87bfd4/notes" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [{ id: "5ba682d23d7cf92bef87bfd4", url: "/companies/5ba682d23d7cf92bef87bfd4" }], + url: "/contacts/6762f3141bb69f9f2193bc6b/companies", + total_count: 0, + has_more: false, + }, + location: { type: "location", country: "Ireland", region: "Dublin", city: "Dublin" }, + social_profiles: { data: [{ name: "Facebook", url: "http://twitter.com/th1sland" }] }, + }; + server + .mockEndpoint() + .post("/visitors/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.visitors.mergeToContact({ + type: "user", + user: { + id: "8a88a590-e1c3-41e2-a502-e0649dbf721c", + email: "foo@bar.com", + }, + visitor: { + user_id: "3ecf64d0-9ed1-4e9f-88e1-da7d6e6782f3", + }, + }); + expect(response).toEqual({ + type: "contact", + id: "6762f3141bb69f9f2193bc6b", + external_id: "f3b87a2e09d514c6c2e79b9a", + workspace_id: "this_is_an_id728_that_should_be_at_least_", + role: "user", + email: "foo@bar.com", + email_domain: "example.com", + phone: "+1123456789", + name: "John Doe", + owner_id: 123, + has_hard_bounced: false, + marked_email_as_spam: false, + unsubscribed_from_emails: false, + created_at: 1734538004, + updated_at: 1734538005, + signed_up_at: 1734538004, + last_seen_at: 1571672154, + last_replied_at: 1571672154, + last_contacted_at: 1571672154, + last_email_opened_at: 1571672154, + last_email_clicked_at: 1571672154, + language_override: "en", + browser: "Chrome", + browser_version: "80.0.3987.132", + browser_language: "en-US", + os: "Mac OS X", + android_app_name: "Intercom", + android_app_version: "5.0.0", + android_device: "Pixel 3", + android_os_version: "10", + android_sdk_version: "28", + android_last_seen_at: 1571672154, + ios_app_name: "Intercom", + ios_app_version: "5.0.0", + ios_device: "iPhone 11", + ios_os_version: "13.3.1", + ios_sdk_version: "13.3.1", + ios_last_seen_at: 1571672154, + custom_attributes: { + key: "value", + }, + avatar: "https://example.org/128Wash.jpg", + tags: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/tags", + total_count: 0, + has_more: false, + }, + notes: { + data: [ + { + type: "note", + id: "123", + url: "/contacts/5ba682d23d7cf92bef87bfd4/notes", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/notes", + total_count: 0, + has_more: false, + }, + companies: { + data: [ + { + id: "5ba682d23d7cf92bef87bfd4", + url: "/companies/5ba682d23d7cf92bef87bfd4", + }, + ], + url: "/contacts/6762f3141bb69f9f2193bc6b/companies", + total_count: 0, + has_more: false, + }, + location: { + type: "location", + country: "Ireland", + region: "Dublin", + city: "Dublin", + }, + social_profiles: { + data: [ + { + name: "Facebook", + url: "http://twitter.com/th1sland", + }, + ], + }, + }); + }); + + test("mergeToContact (2)", async () => { + const server = mockServerPool.createServer(); + const client = new IntercomClient({ + maxRetries: 0, + token: "test", + version: "2.14", + environment: server.baseUrl, + }); + const rawRequestBody = { type: "type", user: { id: "id" }, visitor: { id: "id" } }; + const rawResponseBody = { type: "error.list", errors: [{ code: "code" }, { code: "code" }] }; + server + .mockEndpoint() + .post("/visitors/convert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(401) + .jsonBody(rawResponseBody) + .build(); + + await expect(async () => { + return await client.visitors.mergeToContact({ + type: "type", + user: { + id: "id", + }, + visitor: { + id: "id", + }, + }); + }).rejects.toThrow(Intercom.UnauthorizedError); + }); +}); diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 00000000..d7627675 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "extendedDiagnostics": true, + "strict": true, + "target": "ES6", + "moduleResolution": "node", + "esModuleInterop": true, + "skipLibCheck": true, + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "baseUrl": "src", + "isolatedModules": true, + "isolatedDeclarations": true + }, + "include": ["src"], + "exclude": [] +} diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json new file mode 100644 index 00000000..5c11446f --- /dev/null +++ b/tsconfig.cjs.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "module": "CommonJS", + "outDir": "dist/cjs" + }, + "include": ["src"], + "exclude": [] +} diff --git a/tsconfig.esm.json b/tsconfig.esm.json new file mode 100644 index 00000000..6ce90974 --- /dev/null +++ b/tsconfig.esm.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/esm", + "verbatimModuleSyntax": true + }, + "include": ["src"], + "exclude": [] +} diff --git a/tsconfig.json b/tsconfig.json index 1ec87dd7..d77fdf00 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,17 +1,3 @@ { - "compilerOptions": { - "extendedDiagnostics": true, - "strict": true, - "target": "ES6", - "moduleResolution": "node", - "esModuleInterop": true, - "skipLibCheck": true, - "declaration": true, - "outDir": "dist", - "rootDir": "src", - "baseUrl": "src", - "module": "CommonJS" - }, - "include": ["src"], - "exclude": [] + "extends": "./tsconfig.cjs.json" } diff --git a/vitest.config.mts b/vitest.config.mts new file mode 100644 index 00000000..ba2ec4f9 --- /dev/null +++ b/vitest.config.mts @@ -0,0 +1,28 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ + test: { + projects: [ + { + test: { + globals: true, + name: "unit", + environment: "node", + root: "./tests", + include: ["**/*.test.{js,ts,jsx,tsx}"], + exclude: ["wire/**"], + setupFiles: ["./setup.ts"], + }, + }, + { + test: { + globals: true, + name: "wire", + environment: "node", + root: "./tests/wire", + setupFiles: ["../setup.ts", "../mock-server/setup.ts"], + }, + }, + ], + passWithNoTests: true, + }, +}); diff --git a/yarn.lock b/yarn.lock deleted file mode 100644 index 0276a1af..00000000 --- a/yarn.lock +++ /dev/null @@ -1,3207 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@ampproject/remapping@^2.2.0": - version "2.3.0" - resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.3.0.tgz#ed441b6fa600072520ce18b43d2c8cc8caecc7f4" - integrity sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw== - dependencies: - "@jridgewell/gen-mapping" "^0.3.5" - "@jridgewell/trace-mapping" "^0.3.24" - -"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13", "@babel/code-frame@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.27.1.tgz#200f715e66d52a23b221a9435534a91cc13ad5be" - integrity sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg== - dependencies: - "@babel/helper-validator-identifier" "^7.27.1" - js-tokens "^4.0.0" - picocolors "^1.1.1" - -"@babel/compat-data@^7.27.2": - version "7.27.5" - resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.27.5.tgz#7d0658ec1a8420fc866d1df1b03bea0e79934c82" - integrity sha512-KiRAp/VoJaWkkte84TvUd9qjdbZAdiqyvMxrGl1N6vzFogKmaLgoM3L1kgtLicp2HP5fBJS8JrZKLVIZGVJAVg== - -"@babel/core@^7.11.6", "@babel/core@^7.12.3", "@babel/core@^7.23.9": - version "7.27.4" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.27.4.tgz#cc1fc55d0ce140a1828d1dd2a2eba285adbfb3ce" - integrity sha512-bXYxrXFubeYdvB0NhD/NBB3Qi6aZeV20GOWVI47t2dkecCEoneR4NPVcb7abpXDEvejgrUfFtG6vG/zxAKmg+g== - dependencies: - "@ampproject/remapping" "^2.2.0" - "@babel/code-frame" "^7.27.1" - "@babel/generator" "^7.27.3" - "@babel/helper-compilation-targets" "^7.27.2" - "@babel/helper-module-transforms" "^7.27.3" - "@babel/helpers" "^7.27.4" - "@babel/parser" "^7.27.4" - "@babel/template" "^7.27.2" - "@babel/traverse" "^7.27.4" - "@babel/types" "^7.27.3" - convert-source-map "^2.0.0" - debug "^4.1.0" - gensync "^1.0.0-beta.2" - json5 "^2.2.3" - semver "^6.3.1" - -"@babel/generator@^7.27.3", "@babel/generator@^7.7.2": - version "7.27.5" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.27.5.tgz#3eb01866b345ba261b04911020cbe22dd4be8c8c" - integrity sha512-ZGhA37l0e/g2s1Cnzdix0O3aLYm66eF8aufiVteOgnwxgnRP8GoyMj7VWsgWnQbVKXyge7hqrFh2K2TQM6t1Hw== - dependencies: - "@babel/parser" "^7.27.5" - "@babel/types" "^7.27.3" - "@jridgewell/gen-mapping" "^0.3.5" - "@jridgewell/trace-mapping" "^0.3.25" - jsesc "^3.0.2" - -"@babel/helper-compilation-targets@^7.27.2": - version "7.27.2" - resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz#46a0f6efab808d51d29ce96858dd10ce8732733d" - integrity sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ== - dependencies: - "@babel/compat-data" "^7.27.2" - "@babel/helper-validator-option" "^7.27.1" - browserslist "^4.24.0" - lru-cache "^5.1.1" - semver "^6.3.1" - -"@babel/helper-module-imports@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz#7ef769a323e2655e126673bb6d2d6913bbead204" - integrity sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w== - dependencies: - "@babel/traverse" "^7.27.1" - "@babel/types" "^7.27.1" - -"@babel/helper-module-transforms@^7.27.3": - version "7.27.3" - resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.27.3.tgz#db0bbcfba5802f9ef7870705a7ef8788508ede02" - integrity sha512-dSOvYwvyLsWBeIRyOeHXp5vPj5l1I011r52FM1+r1jCERv+aFXYk4whgQccYEGYxK2H3ZAIA8nuPkQ0HaUo3qg== - dependencies: - "@babel/helper-module-imports" "^7.27.1" - "@babel/helper-validator-identifier" "^7.27.1" - "@babel/traverse" "^7.27.3" - -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.27.1", "@babel/helper-plugin-utils@^7.8.0": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz#ddb2f876534ff8013e6c2b299bf4d39b3c51d44c" - integrity sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw== - -"@babel/helper-string-parser@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz#54da796097ab19ce67ed9f88b47bb2ec49367687" - integrity sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA== - -"@babel/helper-validator-identifier@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz#a7054dcc145a967dd4dc8fee845a57c1316c9df8" - integrity sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow== - -"@babel/helper-validator-option@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz#fa52f5b1e7db1ab049445b421c4471303897702f" - integrity sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg== - -"@babel/helpers@^7.27.4": - version "7.27.6" - resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.27.6.tgz#6456fed15b2cb669d2d1fabe84b66b34991d812c" - integrity sha512-muE8Tt8M22638HU31A3CgfSUciwz1fhATfoVai05aPXGor//CdWDCbnlY1yvBPo07njuVOCNGCSp/GTt12lIug== - dependencies: - "@babel/template" "^7.27.2" - "@babel/types" "^7.27.6" - -"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.20.7", "@babel/parser@^7.23.9", "@babel/parser@^7.27.2", "@babel/parser@^7.27.4", "@babel/parser@^7.27.5": - version "7.27.5" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.27.5.tgz#ed22f871f110aa285a6fd934a0efed621d118826" - integrity sha512-OsQd175SxWkGlzbny8J3K8TnnDD0N3lrIUtB92xwyRpzaenGZhxDvxN/JgU00U3CDZNj9tPuDJ5H0WS4Nt3vKg== - dependencies: - "@babel/types" "^7.27.3" - -"@babel/plugin-syntax-async-generators@^7.8.4": - version "7.8.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d" - integrity sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-bigint@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz#4c9a6f669f5d0cdf1b90a1671e9a146be5300cea" - integrity sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-class-properties@^7.12.13": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz#b5c987274c4a3a82b89714796931a6b53544ae10" - integrity sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-syntax-class-static-block@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz#195df89b146b4b78b3bf897fd7a257c84659d406" - integrity sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw== - dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - -"@babel/plugin-syntax-import-attributes@^7.24.7": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz#34c017d54496f9b11b61474e7ea3dfd5563ffe07" - integrity sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-syntax-import-meta@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz#ee601348c370fa334d2207be158777496521fd51" - integrity sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-json-strings@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a" - integrity sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-jsx@^7.7.2": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.27.1.tgz#2f9beb5eff30fa507c5532d107daac7b888fa34c" - integrity sha512-y8YTNIeKoyhGd9O0Jiyzyyqk8gdjnumGTQPsz0xOZOQ2RmkVJeZ1vmmfIvFEKqucBG6axJGBZDE/7iI5suUI/w== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-syntax-logical-assignment-operators@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699" - integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9" - integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-numeric-separator@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz#b9b070b3e33570cd9fd07ba7fa91c0dd37b9af97" - integrity sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-object-rest-spread@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz#60e225edcbd98a640332a2e72dd3e66f1af55871" - integrity sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-optional-catch-binding@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz#6111a265bcfb020eb9efd0fdfd7d26402b9ed6c1" - integrity sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-optional-chaining@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz#4f69c2ab95167e0180cd5336613f8c5788f7d48a" - integrity sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-private-property-in-object@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz#0dc6671ec0ea22b6e94a1114f857970cd39de1ad" - integrity sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg== - dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - -"@babel/plugin-syntax-top-level-await@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz#c1cfdadc35a646240001f06138247b741c34d94c" - integrity sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw== - dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - -"@babel/plugin-syntax-typescript@^7.7.2": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.27.1.tgz#5147d29066a793450f220c63fa3a9431b7e6dd18" - integrity sha512-xfYCBMxveHrRMnAWl1ZlPXOZjzkN82THFvLhQhFXFt81Z5HnN+EtUkZhv/zcKpmT3fzmWZB0ywiBrbC3vogbwQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/template@^7.27.2", "@babel/template@^7.3.3": - version "7.27.2" - resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.27.2.tgz#fa78ceed3c4e7b63ebf6cb39e5852fca45f6809d" - integrity sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw== - dependencies: - "@babel/code-frame" "^7.27.1" - "@babel/parser" "^7.27.2" - "@babel/types" "^7.27.1" - -"@babel/traverse@^7.27.1", "@babel/traverse@^7.27.3", "@babel/traverse@^7.27.4": - version "7.27.4" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.27.4.tgz#b0045ac7023c8472c3d35effd7cc9ebd638da6ea" - integrity sha512-oNcu2QbHqts9BtOWJosOVJapWjBDSxGCpFvikNR5TGDYDQf3JwpIoMzIKrvfoti93cLfPJEG4tH9SPVeyCGgdA== - dependencies: - "@babel/code-frame" "^7.27.1" - "@babel/generator" "^7.27.3" - "@babel/parser" "^7.27.4" - "@babel/template" "^7.27.2" - "@babel/types" "^7.27.3" - debug "^4.3.1" - globals "^11.1.0" - -"@babel/types@^7.0.0", "@babel/types@^7.20.7", "@babel/types@^7.27.1", "@babel/types@^7.27.3", "@babel/types@^7.27.6", "@babel/types@^7.3.3": - version "7.27.6" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.27.6.tgz#a434ca7add514d4e646c80f7375c0aa2befc5535" - integrity sha512-ETyHEk2VHHvl9b9jZP5IHPavHYk57EhanlRRuae9XCpb/j5bDCbPPMOBfCWhnl/7EDJz0jEMCi/RhccCE8r1+Q== - dependencies: - "@babel/helper-string-parser" "^7.27.1" - "@babel/helper-validator-identifier" "^7.27.1" - -"@bcoe/v8-coverage@^0.2.3": - version "0.2.3" - resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" - integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== - -"@istanbuljs/load-nyc-config@^1.0.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" - integrity sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ== - dependencies: - camelcase "^5.3.1" - find-up "^4.1.0" - get-package-type "^0.1.0" - js-yaml "^3.13.1" - resolve-from "^5.0.0" - -"@istanbuljs/schema@^0.1.2", "@istanbuljs/schema@^0.1.3": - version "0.1.3" - resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.3.tgz#e45e384e4b8ec16bce2fd903af78450f6bf7ec98" - integrity sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA== - -"@jest/console@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/console/-/console-29.7.0.tgz#cd4822dbdb84529265c5a2bdb529a3c9cc950ffc" - integrity sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg== - dependencies: - "@jest/types" "^29.6.3" - "@types/node" "*" - chalk "^4.0.0" - jest-message-util "^29.7.0" - jest-util "^29.7.0" - slash "^3.0.0" - -"@jest/core@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/core/-/core-29.7.0.tgz#b6cccc239f30ff36609658c5a5e2291757ce448f" - integrity sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg== - dependencies: - "@jest/console" "^29.7.0" - "@jest/reporters" "^29.7.0" - "@jest/test-result" "^29.7.0" - "@jest/transform" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - ansi-escapes "^4.2.1" - chalk "^4.0.0" - ci-info "^3.2.0" - exit "^0.1.2" - graceful-fs "^4.2.9" - jest-changed-files "^29.7.0" - jest-config "^29.7.0" - jest-haste-map "^29.7.0" - jest-message-util "^29.7.0" - jest-regex-util "^29.6.3" - jest-resolve "^29.7.0" - jest-resolve-dependencies "^29.7.0" - jest-runner "^29.7.0" - jest-runtime "^29.7.0" - jest-snapshot "^29.7.0" - jest-util "^29.7.0" - jest-validate "^29.7.0" - jest-watcher "^29.7.0" - micromatch "^4.0.4" - pretty-format "^29.7.0" - slash "^3.0.0" - strip-ansi "^6.0.0" - -"@jest/environment@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-29.7.0.tgz#24d61f54ff1f786f3cd4073b4b94416383baf2a7" - integrity sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw== - dependencies: - "@jest/fake-timers" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - jest-mock "^29.7.0" - -"@jest/expect-utils@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-29.7.0.tgz#023efe5d26a8a70f21677d0a1afc0f0a44e3a1c6" - integrity sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA== - dependencies: - jest-get-type "^29.6.3" - -"@jest/expect@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/expect/-/expect-29.7.0.tgz#76a3edb0cb753b70dfbfe23283510d3d45432bf2" - integrity sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ== - dependencies: - expect "^29.7.0" - jest-snapshot "^29.7.0" - -"@jest/fake-timers@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-29.7.0.tgz#fd91bf1fffb16d7d0d24a426ab1a47a49881a565" - integrity sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ== - dependencies: - "@jest/types" "^29.6.3" - "@sinonjs/fake-timers" "^10.0.2" - "@types/node" "*" - jest-message-util "^29.7.0" - jest-mock "^29.7.0" - jest-util "^29.7.0" - -"@jest/globals@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-29.7.0.tgz#8d9290f9ec47ff772607fa864ca1d5a2efae1d4d" - integrity sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ== - dependencies: - "@jest/environment" "^29.7.0" - "@jest/expect" "^29.7.0" - "@jest/types" "^29.6.3" - jest-mock "^29.7.0" - -"@jest/reporters@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-29.7.0.tgz#04b262ecb3b8faa83b0b3d321623972393e8f4c7" - integrity sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg== - dependencies: - "@bcoe/v8-coverage" "^0.2.3" - "@jest/console" "^29.7.0" - "@jest/test-result" "^29.7.0" - "@jest/transform" "^29.7.0" - "@jest/types" "^29.6.3" - "@jridgewell/trace-mapping" "^0.3.18" - "@types/node" "*" - chalk "^4.0.0" - collect-v8-coverage "^1.0.0" - exit "^0.1.2" - glob "^7.1.3" - graceful-fs "^4.2.9" - istanbul-lib-coverage "^3.0.0" - istanbul-lib-instrument "^6.0.0" - istanbul-lib-report "^3.0.0" - istanbul-lib-source-maps "^4.0.0" - istanbul-reports "^3.1.3" - jest-message-util "^29.7.0" - jest-util "^29.7.0" - jest-worker "^29.7.0" - slash "^3.0.0" - string-length "^4.0.1" - strip-ansi "^6.0.0" - v8-to-istanbul "^9.0.1" - -"@jest/schemas@^29.6.3": - version "29.6.3" - resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-29.6.3.tgz#430b5ce8a4e0044a7e3819663305a7b3091c8e03" - integrity sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA== - dependencies: - "@sinclair/typebox" "^0.27.8" - -"@jest/source-map@^29.6.3": - version "29.6.3" - resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.6.3.tgz#d90ba772095cf37a34a5eb9413f1b562a08554c4" - integrity sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw== - dependencies: - "@jridgewell/trace-mapping" "^0.3.18" - callsites "^3.0.0" - graceful-fs "^4.2.9" - -"@jest/test-result@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-29.7.0.tgz#8db9a80aa1a097bb2262572686734baed9b1657c" - integrity sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA== - dependencies: - "@jest/console" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/istanbul-lib-coverage" "^2.0.0" - collect-v8-coverage "^1.0.0" - -"@jest/test-sequencer@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz#6cef977ce1d39834a3aea887a1726628a6f072ce" - integrity sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw== - dependencies: - "@jest/test-result" "^29.7.0" - graceful-fs "^4.2.9" - jest-haste-map "^29.7.0" - slash "^3.0.0" - -"@jest/transform@^29.7.0": - version "29.7.0" - resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-29.7.0.tgz#df2dd9c346c7d7768b8a06639994640c642e284c" - integrity sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw== - dependencies: - "@babel/core" "^7.11.6" - "@jest/types" "^29.6.3" - "@jridgewell/trace-mapping" "^0.3.18" - babel-plugin-istanbul "^6.1.1" - chalk "^4.0.0" - convert-source-map "^2.0.0" - fast-json-stable-stringify "^2.1.0" - graceful-fs "^4.2.9" - jest-haste-map "^29.7.0" - jest-regex-util "^29.6.3" - jest-util "^29.7.0" - micromatch "^4.0.4" - pirates "^4.0.4" - slash "^3.0.0" - write-file-atomic "^4.0.2" - -"@jest/types@^29.6.3": - version "29.6.3" - resolved "https://registry.yarnpkg.com/@jest/types/-/types-29.6.3.tgz#1131f8cf634e7e84c5e77bab12f052af585fba59" - integrity sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw== - dependencies: - "@jest/schemas" "^29.6.3" - "@types/istanbul-lib-coverage" "^2.0.0" - "@types/istanbul-reports" "^3.0.0" - "@types/node" "*" - "@types/yargs" "^17.0.8" - chalk "^4.0.0" - -"@jridgewell/gen-mapping@^0.3.5": - version "0.3.8" - resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz#4f0e06362e01362f823d348f1872b08f666d8142" - integrity sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA== - dependencies: - "@jridgewell/set-array" "^1.2.1" - "@jridgewell/sourcemap-codec" "^1.4.10" - "@jridgewell/trace-mapping" "^0.3.24" - -"@jridgewell/resolve-uri@^3.1.0": - version "3.1.2" - resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz#7a0ee601f60f99a20c7c7c5ff0c80388c1189bd6" - integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw== - -"@jridgewell/set-array@^1.2.1": - version "1.2.1" - resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.2.1.tgz#558fb6472ed16a4c850b889530e6b36438c49280" - integrity sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A== - -"@jridgewell/source-map@^0.3.3": - version "0.3.6" - resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.6.tgz#9d71ca886e32502eb9362c9a74a46787c36df81a" - integrity sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ== - dependencies: - "@jridgewell/gen-mapping" "^0.3.5" - "@jridgewell/trace-mapping" "^0.3.25" - -"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14": - version "1.5.0" - resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz#3188bcb273a414b0d215fd22a58540b989b9409a" - integrity sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ== - -"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.18", "@jridgewell/trace-mapping@^0.3.24", "@jridgewell/trace-mapping@^0.3.25": - version "0.3.25" - resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz#15f190e98895f3fc23276ee14bc76b675c2e50f0" - integrity sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ== - dependencies: - "@jridgewell/resolve-uri" "^3.1.0" - "@jridgewell/sourcemap-codec" "^1.4.14" - -"@sinclair/typebox@^0.27.8": - version "0.27.8" - resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" - integrity sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA== - -"@sinonjs/commons@^3.0.0": - version "3.0.1" - resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-3.0.1.tgz#1029357e44ca901a615585f6d27738dbc89084cd" - integrity sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ== - dependencies: - type-detect "4.0.8" - -"@sinonjs/fake-timers@^10.0.2": - version "10.3.0" - resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz#55fdff1ecab9f354019129daf4df0dd4d923ea66" - integrity sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA== - dependencies: - "@sinonjs/commons" "^3.0.0" - -"@tootallnate/once@2": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-2.0.0.tgz#f544a148d3ab35801c1f633a7441fd87c2e484bf" - integrity sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A== - -"@types/babel__core@^7.1.14": - version "7.20.5" - resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.20.5.tgz#3df15f27ba85319caa07ba08d0721889bb39c017" - integrity sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA== - dependencies: - "@babel/parser" "^7.20.7" - "@babel/types" "^7.20.7" - "@types/babel__generator" "*" - "@types/babel__template" "*" - "@types/babel__traverse" "*" - -"@types/babel__generator@*": - version "7.27.0" - resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.27.0.tgz#b5819294c51179957afaec341442f9341e4108a9" - integrity sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg== - dependencies: - "@babel/types" "^7.0.0" - -"@types/babel__template@*": - version "7.4.4" - resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.4.4.tgz#5672513701c1b2199bc6dad636a9d7491586766f" - integrity sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A== - dependencies: - "@babel/parser" "^7.1.0" - "@babel/types" "^7.0.0" - -"@types/babel__traverse@*", "@types/babel__traverse@^7.0.6": - version "7.20.7" - resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.20.7.tgz#968cdc2366ec3da159f61166428ee40f370e56c2" - integrity sha512-dkO5fhS7+/oos4ciWxyEyjWe48zmG6wbCheo/G2ZnHx4fs3EU6YC6UM8rk56gAjNJ9P3MTH2jo5jb92/K6wbng== - dependencies: - "@babel/types" "^7.20.7" - -"@types/eslint-scope@^3.7.7": - version "3.7.7" - resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.7.tgz#3108bd5f18b0cdb277c867b3dd449c9ed7079ac5" - integrity sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg== - dependencies: - "@types/eslint" "*" - "@types/estree" "*" - -"@types/eslint@*": - version "9.6.1" - resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-9.6.1.tgz#d5795ad732ce81715f27f75da913004a56751584" - integrity sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag== - dependencies: - "@types/estree" "*" - "@types/json-schema" "*" - -"@types/estree@*", "@types/estree@^1.0.6": - version "1.0.8" - resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.8.tgz#958b91c991b1867ced318bedea0e215ee050726e" - integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w== - -"@types/graceful-fs@^4.1.3": - version "4.1.9" - resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.9.tgz#2a06bc0f68a20ab37b3e36aa238be6abdf49e8b4" - integrity sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ== - dependencies: - "@types/node" "*" - -"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": - version "2.0.6" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz#7739c232a1fee9b4d3ce8985f314c0c6d33549d7" - integrity sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w== - -"@types/istanbul-lib-report@*": - version "3.0.3" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz#53047614ae72e19fc0401d872de3ae2b4ce350bf" - integrity sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA== - dependencies: - "@types/istanbul-lib-coverage" "*" - -"@types/istanbul-reports@^3.0.0": - version "3.0.4" - resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz#0f03e3d2f670fbdac586e34b433783070cc16f54" - integrity sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ== - dependencies: - "@types/istanbul-lib-report" "*" - -"@types/jest@^29.5.14": - version "29.5.14" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-29.5.14.tgz#2b910912fa1d6856cadcd0c1f95af7df1d6049e5" - integrity sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ== - dependencies: - expect "^29.0.0" - pretty-format "^29.0.0" - -"@types/jsdom@^20.0.0": - version "20.0.1" - resolved "https://registry.yarnpkg.com/@types/jsdom/-/jsdom-20.0.1.tgz#07c14bc19bd2f918c1929541cdaacae894744808" - integrity sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ== - dependencies: - "@types/node" "*" - "@types/tough-cookie" "*" - parse5 "^7.0.0" - -"@types/json-schema@*", "@types/json-schema@^7.0.15", "@types/json-schema@^7.0.9": - version "7.0.15" - resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" - integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== - -"@types/node-fetch@^2.6.12": - version "2.6.12" - resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.12.tgz#8ab5c3ef8330f13100a7479e2cd56d3386830a03" - integrity sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA== - dependencies: - "@types/node" "*" - form-data "^4.0.0" - -"@types/node@*": - version "24.0.4" - resolved "https://registry.yarnpkg.com/@types/node/-/node-24.0.4.tgz#dbae889912bda33a7f57669fb8587c1a56bc0c1f" - integrity sha512-ulyqAkrhnuNq9pB76DRBTkcS6YsmDALy6Ua63V8OhrOBgbcYt6IOdzpw5P1+dyRIyMerzLkeYWBeOXPpA9GMAA== - dependencies: - undici-types "~7.8.0" - -"@types/node@^18.19.70": - version "18.19.112" - resolved "https://registry.yarnpkg.com/@types/node/-/node-18.19.112.tgz#cd2aee9c075402e0e1942a44101428881dbeb110" - integrity sha512-i+Vukt9POdS/MBI7YrrkkI5fMfwFtOjphSmt4WXYLfwqsfr6z/HdCx7LqT9M7JktGob8WNgj8nFB4TbGNE4Cog== - dependencies: - undici-types "~5.26.4" - -"@types/qs@^6.9.17": - version "6.14.0" - resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.14.0.tgz#d8b60cecf62f2db0fb68e5e006077b9178b85de5" - integrity sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ== - -"@types/readable-stream@^4.0.18": - version "4.0.21" - resolved "https://registry.yarnpkg.com/@types/readable-stream/-/readable-stream-4.0.21.tgz#716558454a5e0c3c0651520f8154efc3288f59cb" - integrity sha512-19eKVv9tugr03IgfXlA9UVUVRbW6IuqRO5B92Dl4a6pT7K8uaGrNS0GkxiZD0BOk6PLuXl5FhWl//eX/pzYdTQ== - dependencies: - "@types/node" "*" - -"@types/stack-utils@^2.0.0": - version "2.0.3" - resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.3.tgz#6209321eb2c1712a7e7466422b8cb1fc0d9dd5d8" - integrity sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw== - -"@types/tough-cookie@*": - version "4.0.5" - resolved "https://registry.yarnpkg.com/@types/tough-cookie/-/tough-cookie-4.0.5.tgz#cb6e2a691b70cb177c6e3ae9c1d2e8b2ea8cd304" - integrity sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA== - -"@types/url-join@4.0.1": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@types/url-join/-/url-join-4.0.1.tgz#4989c97f969464647a8586c7252d97b449cdc045" - integrity sha512-wDXw9LEEUHyV+7UWy7U315nrJGJ7p1BzaCxDpEoLr789Dk1WDVMMlf3iBfbG2F8NdWnYyFbtTxUn2ZNbm1Q4LQ== - -"@types/yargs-parser@*": - version "21.0.3" - resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.3.tgz#815e30b786d2e8f0dcd85fd5bcf5e1a04d008f15" - integrity sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ== - -"@types/yargs@^17.0.8": - version "17.0.33" - resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-17.0.33.tgz#8c32303da83eec050a84b3c7ae7b9f922d13e32d" - integrity sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA== - dependencies: - "@types/yargs-parser" "*" - -"@webassemblyjs/ast@1.14.1", "@webassemblyjs/ast@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.14.1.tgz#a9f6a07f2b03c95c8d38c4536a1fdfb521ff55b6" - integrity sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ== - dependencies: - "@webassemblyjs/helper-numbers" "1.13.2" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - -"@webassemblyjs/floating-point-hex-parser@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz#fcca1eeddb1cc4e7b6eed4fc7956d6813b21b9fb" - integrity sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA== - -"@webassemblyjs/helper-api-error@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz#e0a16152248bc38daee76dd7e21f15c5ef3ab1e7" - integrity sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ== - -"@webassemblyjs/helper-buffer@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz#822a9bc603166531f7d5df84e67b5bf99b72b96b" - integrity sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA== - -"@webassemblyjs/helper-numbers@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz#dbd932548e7119f4b8a7877fd5a8d20e63490b2d" - integrity sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA== - dependencies: - "@webassemblyjs/floating-point-hex-parser" "1.13.2" - "@webassemblyjs/helper-api-error" "1.13.2" - "@xtuc/long" "4.2.2" - -"@webassemblyjs/helper-wasm-bytecode@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz#e556108758f448aae84c850e593ce18a0eb31e0b" - integrity sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA== - -"@webassemblyjs/helper-wasm-section@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz#9629dda9c4430eab54b591053d6dc6f3ba050348" - integrity sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/wasm-gen" "1.14.1" - -"@webassemblyjs/ieee754@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz#1c5eaace1d606ada2c7fd7045ea9356c59ee0dba" - integrity sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw== - dependencies: - "@xtuc/ieee754" "^1.2.0" - -"@webassemblyjs/leb128@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.13.2.tgz#57c5c3deb0105d02ce25fa3fd74f4ebc9fd0bbb0" - integrity sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw== - dependencies: - "@xtuc/long" "4.2.2" - -"@webassemblyjs/utf8@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.13.2.tgz#917a20e93f71ad5602966c2d685ae0c6c21f60f1" - integrity sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ== - -"@webassemblyjs/wasm-edit@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz#ac6689f502219b59198ddec42dcd496b1004d597" - integrity sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/helper-wasm-section" "1.14.1" - "@webassemblyjs/wasm-gen" "1.14.1" - "@webassemblyjs/wasm-opt" "1.14.1" - "@webassemblyjs/wasm-parser" "1.14.1" - "@webassemblyjs/wast-printer" "1.14.1" - -"@webassemblyjs/wasm-gen@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz#991e7f0c090cb0bb62bbac882076e3d219da9570" - integrity sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/ieee754" "1.13.2" - "@webassemblyjs/leb128" "1.13.2" - "@webassemblyjs/utf8" "1.13.2" - -"@webassemblyjs/wasm-opt@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz#e6f71ed7ccae46781c206017d3c14c50efa8106b" - integrity sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/wasm-gen" "1.14.1" - "@webassemblyjs/wasm-parser" "1.14.1" - -"@webassemblyjs/wasm-parser@1.14.1", "@webassemblyjs/wasm-parser@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz#b3e13f1893605ca78b52c68e54cf6a865f90b9fb" - integrity sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-api-error" "1.13.2" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/ieee754" "1.13.2" - "@webassemblyjs/leb128" "1.13.2" - "@webassemblyjs/utf8" "1.13.2" - -"@webassemblyjs/wast-printer@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz#3bb3e9638a8ae5fdaf9610e7a06b4d9f9aa6fe07" - integrity sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@xtuc/long" "4.2.2" - -"@xtuc/ieee754@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" - integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== - -"@xtuc/long@4.2.2": - version "4.2.2" - resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" - integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== - -abab@^2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.6.tgz#41b80f2c871d19686216b82309231cfd3cb3d291" - integrity sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA== - -abort-controller@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" - integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== - dependencies: - event-target-shim "^5.0.0" - -acorn-globals@^7.0.0: - version "7.0.1" - resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-7.0.1.tgz#0dbf05c44fa7c94332914c02066d5beff62c40c3" - integrity sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q== - dependencies: - acorn "^8.1.0" - acorn-walk "^8.0.2" - -acorn-walk@^8.0.2: - version "8.3.4" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.3.4.tgz#794dd169c3977edf4ba4ea47583587c5866236b7" - integrity sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g== - dependencies: - acorn "^8.11.0" - -acorn@^8.1.0, acorn@^8.11.0, acorn@^8.14.0, acorn@^8.8.1: - version "8.15.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.15.0.tgz#a360898bc415edaac46c8241f6383975b930b816" - integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg== - -agent-base@6: - version "6.0.2" - resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.2.tgz#49fff58577cfee3f37176feab4c22e00f86d7f77" - integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ== - dependencies: - debug "4" - -ajv-formats@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ajv-formats/-/ajv-formats-2.1.1.tgz#6e669400659eb74973bbf2e33327180a0996b520" - integrity sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA== - dependencies: - ajv "^8.0.0" - -ajv-keywords@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-5.1.0.tgz#69d4d385a4733cdbeab44964a1170a88f87f0e16" - integrity sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw== - dependencies: - fast-deep-equal "^3.1.3" - -ajv@^8.0.0, ajv@^8.9.0: - version "8.17.1" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.17.1.tgz#37d9a5c776af6bc92d7f4f9510eba4c0a60d11a6" - integrity sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g== - dependencies: - fast-deep-equal "^3.1.3" - fast-uri "^3.0.1" - json-schema-traverse "^1.0.0" - require-from-string "^2.0.2" - -ansi-escapes@^4.2.1: - version "4.3.2" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" - integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== - dependencies: - type-fest "^0.21.3" - -ansi-regex@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" - integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== - -ansi-styles@^4.0.0, ansi-styles@^4.1.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" - integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== - dependencies: - color-convert "^2.0.1" - -ansi-styles@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" - integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== - -anymatch@^3.0.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" - integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - -argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" - integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== - dependencies: - sprintf-js "~1.0.2" - -async@^3.2.3: - version "3.2.6" - resolved "https://registry.yarnpkg.com/async/-/async-3.2.6.tgz#1b0728e14929d51b85b449b7f06e27c1145e38ce" - integrity sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA== - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q== - -babel-jest@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.7.0.tgz#f4369919225b684c56085998ac63dbd05be020d5" - integrity sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg== - dependencies: - "@jest/transform" "^29.7.0" - "@types/babel__core" "^7.1.14" - babel-plugin-istanbul "^6.1.1" - babel-preset-jest "^29.6.3" - chalk "^4.0.0" - graceful-fs "^4.2.9" - slash "^3.0.0" - -babel-plugin-istanbul@^6.1.1: - version "6.1.1" - resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz#fa88ec59232fd9b4e36dbbc540a8ec9a9b47da73" - integrity sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA== - dependencies: - "@babel/helper-plugin-utils" "^7.0.0" - "@istanbuljs/load-nyc-config" "^1.0.0" - "@istanbuljs/schema" "^0.1.2" - istanbul-lib-instrument "^5.0.4" - test-exclude "^6.0.0" - -babel-plugin-jest-hoist@^29.6.3: - version "29.6.3" - resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz#aadbe943464182a8922c3c927c3067ff40d24626" - integrity sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg== - dependencies: - "@babel/template" "^7.3.3" - "@babel/types" "^7.3.3" - "@types/babel__core" "^7.1.14" - "@types/babel__traverse" "^7.0.6" - -babel-preset-current-node-syntax@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.1.0.tgz#9a929eafece419612ef4ae4f60b1862ebad8ef30" - integrity sha512-ldYss8SbBlWva1bs28q78Ju5Zq1F+8BrqBZZ0VFhLBvhh6lCpC2o3gDJi/5DRLs9FgYZCnmPYIVFU4lRXCkyUw== - dependencies: - "@babel/plugin-syntax-async-generators" "^7.8.4" - "@babel/plugin-syntax-bigint" "^7.8.3" - "@babel/plugin-syntax-class-properties" "^7.12.13" - "@babel/plugin-syntax-class-static-block" "^7.14.5" - "@babel/plugin-syntax-import-attributes" "^7.24.7" - "@babel/plugin-syntax-import-meta" "^7.10.4" - "@babel/plugin-syntax-json-strings" "^7.8.3" - "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" - "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" - "@babel/plugin-syntax-numeric-separator" "^7.10.4" - "@babel/plugin-syntax-object-rest-spread" "^7.8.3" - "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" - "@babel/plugin-syntax-optional-chaining" "^7.8.3" - "@babel/plugin-syntax-private-property-in-object" "^7.14.5" - "@babel/plugin-syntax-top-level-await" "^7.14.5" - -babel-preset-jest@^29.6.3: - version "29.6.3" - resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz#fa05fa510e7d493896d7b0dd2033601c840f171c" - integrity sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA== - dependencies: - babel-plugin-jest-hoist "^29.6.3" - babel-preset-current-node-syntax "^1.0.0" - -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - -base64-js@^1.3.1: - version "1.5.1" - resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" - integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== - -brace-expansion@^1.1.7: - version "1.1.12" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.12.tgz#ab9b454466e5a8cc3a187beaad580412a9c5b843" - integrity sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -brace-expansion@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.2.tgz#54fc53237a613d854c7bd37463aad17df87214e7" - integrity sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ== - dependencies: - balanced-match "^1.0.0" - -braces@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" - integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== - dependencies: - fill-range "^7.1.1" - -browserslist@^4.24.0: - version "4.25.1" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.25.1.tgz#ba9e8e6f298a1d86f829c9b975e07948967bb111" - integrity sha512-KGj0KoOMXLpSNkkEI6Z6mShmQy0bc1I+T7K9N81k4WWMrfz+6fQ6es80B/YLAeRoKvjYE1YSHHOW1qe9xIVzHw== - dependencies: - caniuse-lite "^1.0.30001726" - electron-to-chromium "^1.5.173" - node-releases "^2.0.19" - update-browserslist-db "^1.1.3" - -bs-logger@^0.2.6: - version "0.2.6" - resolved "https://registry.yarnpkg.com/bs-logger/-/bs-logger-0.2.6.tgz#eb7d365307a72cf974cc6cda76b68354ad336bd8" - integrity sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog== - dependencies: - fast-json-stable-stringify "2.x" - -bser@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" - integrity sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ== - dependencies: - node-int64 "^0.4.0" - -buffer-from@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" - integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== - -buffer@^6.0.3: - version "6.0.3" - resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" - integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== - dependencies: - base64-js "^1.3.1" - ieee754 "^1.2.1" - -call-bind-apply-helpers@^1.0.1, call-bind-apply-helpers@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz#4b5428c222be985d79c3d82657479dbe0b59b2d6" - integrity sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ== - dependencies: - es-errors "^1.3.0" - function-bind "^1.1.2" - -call-bound@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/call-bound/-/call-bound-1.0.4.tgz#238de935d2a2a692928c538c7ccfa91067fd062a" - integrity sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg== - dependencies: - call-bind-apply-helpers "^1.0.2" - get-intrinsic "^1.3.0" - -callsites@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" - integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== - -camelcase@^5.3.1: - version "5.3.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" - integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== - -camelcase@^6.2.0: - version "6.3.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a" - integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== - -caniuse-lite@^1.0.30001726: - version "1.0.30001726" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001726.tgz#a15bd87d5a4bf01f6b6f70ae7c97fdfd28b5ae47" - integrity sha512-VQAUIUzBiZ/UnlM28fSp2CRF3ivUn1BWEvxMcVTNwpw91Py1pGbPIyIKtd+tzct9C3ouceCVdGAXxZOpZAsgdw== - -chalk@^4.0.0, chalk@^4.0.2, chalk@^4.1.0: - version "4.1.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" - integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== - dependencies: - ansi-styles "^4.1.0" - supports-color "^7.1.0" - -char-regex@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" - integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== - -chrome-trace-event@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz#05bffd7ff928465093314708c93bdfa9bd1f0f5b" - integrity sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ== - -ci-info@^3.2.0: - version "3.9.0" - resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.9.0.tgz#4279a62028a7b1f262f3473fc9605f5e218c59b4" - integrity sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ== - -cjs-module-lexer@^1.0.0: - version "1.4.3" - resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz#0f79731eb8cfe1ec72acd4066efac9d61991b00d" - integrity sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q== - -cliui@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa" - integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ== - dependencies: - string-width "^4.2.0" - strip-ansi "^6.0.1" - wrap-ansi "^7.0.0" - -co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ== - -collect-v8-coverage@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz#c0b29bcd33bcd0779a1344c2136051e6afd3d9e9" - integrity sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q== - -color-convert@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" - integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== - dependencies: - color-name "~1.1.4" - -color-name@~1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" - integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== - -combined-stream@^1.0.8: - version "1.0.8" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" - integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== - dependencies: - delayed-stream "~1.0.0" - -commander@^2.20.0: - version "2.20.3" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" - integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== - -convert-source-map@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" - integrity sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg== - -create-jest@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/create-jest/-/create-jest-29.7.0.tgz#a355c5b3cb1e1af02ba177fe7afd7feee49a5320" - integrity sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q== - dependencies: - "@jest/types" "^29.6.3" - chalk "^4.0.0" - exit "^0.1.2" - graceful-fs "^4.2.9" - jest-config "^29.7.0" - jest-util "^29.7.0" - prompts "^2.0.1" - -cross-spawn@^7.0.3: - version "7.0.6" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" - integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== - dependencies: - path-key "^3.1.0" - shebang-command "^2.0.0" - which "^2.0.1" - -cssom@^0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.5.0.tgz#d254fa92cd8b6fbd83811b9fbaed34663cc17c36" - integrity sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw== - -cssom@~0.3.6: - version "0.3.8" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" - integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== - -cssstyle@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-2.3.0.tgz#ff665a0ddbdc31864b09647f34163443d90b0852" - integrity sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A== - dependencies: - cssom "~0.3.6" - -data-urls@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-3.0.2.tgz#9cf24a477ae22bcef5cd5f6f0bfbc1d2d3be9143" - integrity sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ== - dependencies: - abab "^2.0.6" - whatwg-mimetype "^3.0.0" - whatwg-url "^11.0.0" - -debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1: - version "4.4.1" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.1.tgz#e5a8bc6cbc4c6cd3e64308b0693a3d4fa550189b" - integrity sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ== - dependencies: - ms "^2.1.3" - -decimal.js@^10.4.2: - version "10.5.0" - resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.5.0.tgz#0f371c7cf6c4898ce0afb09836db73cd82010f22" - integrity sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw== - -dedent@^1.0.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/dedent/-/dedent-1.6.0.tgz#79d52d6389b1ffa67d2bcef59ba51847a9d503b2" - integrity sha512-F1Z+5UCFpmQUzJa11agbyPVMbpgT/qA3/SKyJ1jyBgm7dUcUEa8v9JwDkerSQXfakBwFljIxhOJqGkjUwZ9FSA== - -deepmerge@^4.2.2: - version "4.3.1" - resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.3.1.tgz#44b5f2147cd3b00d4b56137685966f26fd25dd4a" - integrity sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A== - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ== - -detect-newline@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651" - integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== - -diff-sequences@^29.6.3: - version "29.6.3" - resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.6.3.tgz#4deaf894d11407c51efc8418012f9e70b84ea921" - integrity sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q== - -domexception@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/domexception/-/domexception-4.0.0.tgz#4ad1be56ccadc86fc76d033353999a8037d03673" - integrity sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw== - dependencies: - webidl-conversions "^7.0.0" - -dunder-proto@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/dunder-proto/-/dunder-proto-1.0.1.tgz#d7ae667e1dc83482f8b70fd0f6eefc50da30f58a" - integrity sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A== - dependencies: - call-bind-apply-helpers "^1.0.1" - es-errors "^1.3.0" - gopd "^1.2.0" - -ejs@^3.1.10: - version "3.1.10" - resolved "https://registry.yarnpkg.com/ejs/-/ejs-3.1.10.tgz#69ab8358b14e896f80cc39e62087b88500c3ac3b" - integrity sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA== - dependencies: - jake "^10.8.5" - -electron-to-chromium@^1.5.173: - version "1.5.173" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.173.tgz#1aeba57204fe19425921a29946ef543653f5e896" - integrity sha512-2bFhXP2zqSfQHugjqJIDFVwa+qIxyNApenmXTp9EjaKtdPrES5Qcn9/aSFy/NaP2E+fWG/zxKu/LBvY36p5VNQ== - -emittery@^0.13.1: - version "0.13.1" - resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.13.1.tgz#c04b8c3457490e0847ae51fced3af52d338e3dad" - integrity sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ== - -emoji-regex@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" - integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== - -enhanced-resolve@^5.0.0, enhanced-resolve@^5.17.1: - version "5.18.2" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.18.2.tgz#7903c5b32ffd4b2143eeb4b92472bd68effd5464" - integrity sha512-6Jw4sE1maoRJo3q8MsSIn2onJFbLTOjY9hlx4DZXmOKvLRd1Ok2kXmAGXaafL2+ijsJZ1ClYbl/pmqr9+k4iUQ== - dependencies: - graceful-fs "^4.2.4" - tapable "^2.2.0" - -entities@^6.0.0: - version "6.0.1" - resolved "https://registry.yarnpkg.com/entities/-/entities-6.0.1.tgz#c28c34a43379ca7f61d074130b2f5f7020a30694" - integrity sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g== - -error-ex@^1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" - integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== - dependencies: - is-arrayish "^0.2.1" - -es-define-property@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/es-define-property/-/es-define-property-1.0.1.tgz#983eb2f9a6724e9303f61addf011c72e09e0b0fa" - integrity sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g== - -es-errors@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/es-errors/-/es-errors-1.3.0.tgz#05f75a25dab98e4fb1dcd5e1472c0546d5057c8f" - integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== - -es-module-lexer@^1.2.1: - version "1.7.0" - resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-1.7.0.tgz#9159601561880a85f2734560a9099b2c31e5372a" - integrity sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA== - -es-object-atoms@^1.0.0, es-object-atoms@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz#1c4f2c4837327597ce69d2ca190a7fdd172338c1" - integrity sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA== - dependencies: - es-errors "^1.3.0" - -es-set-tostringtag@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz#f31dbbe0c183b00a6d26eb6325c810c0fd18bd4d" - integrity sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA== - dependencies: - es-errors "^1.3.0" - get-intrinsic "^1.2.6" - has-tostringtag "^1.0.2" - hasown "^2.0.2" - -escalade@^3.1.1, escalade@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5" - integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA== - -escape-string-regexp@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344" - integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== - -escodegen@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-2.1.0.tgz#ba93bbb7a43986d29d6041f99f5262da773e2e17" - integrity sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w== - dependencies: - esprima "^4.0.1" - estraverse "^5.2.0" - esutils "^2.0.2" - optionalDependencies: - source-map "~0.6.1" - -eslint-scope@5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" - integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== - dependencies: - esrecurse "^4.3.0" - estraverse "^4.1.1" - -esprima@^4.0.0, esprima@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" - integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== - -esrecurse@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" - integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== - dependencies: - estraverse "^5.2.0" - -estraverse@^4.1.1: - version "4.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" - integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== - -estraverse@^5.2.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" - integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== - -esutils@^2.0.2: - version "2.0.3" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" - integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== - -event-target-shim@^5.0.0: - version "5.0.1" - resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" - integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== - -events@^3.2.0, events@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" - integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== - -execa@^5.0.0: - version "5.1.1" - resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd" - integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg== - dependencies: - cross-spawn "^7.0.3" - get-stream "^6.0.0" - human-signals "^2.1.0" - is-stream "^2.0.0" - merge-stream "^2.0.0" - npm-run-path "^4.0.1" - onetime "^5.1.2" - signal-exit "^3.0.3" - strip-final-newline "^2.0.0" - -exit@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" - integrity sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ== - -expect@^29.0.0, expect@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/expect/-/expect-29.7.0.tgz#578874590dcb3214514084c08115d8aee61e11bc" - integrity sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw== - dependencies: - "@jest/expect-utils" "^29.7.0" - jest-get-type "^29.6.3" - jest-matcher-utils "^29.7.0" - jest-message-util "^29.7.0" - jest-util "^29.7.0" - -fast-deep-equal@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" - integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== - -fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" - integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== - -fast-uri@^3.0.1: - version "3.0.6" - resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.0.6.tgz#88f130b77cfaea2378d56bf970dea21257a68748" - integrity sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw== - -fb-watchman@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.2.tgz#e9524ee6b5c77e9e5001af0f85f3adbb8623255c" - integrity sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA== - dependencies: - bser "2.1.1" - -filelist@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/filelist/-/filelist-1.0.4.tgz#f78978a1e944775ff9e62e744424f215e58352b5" - integrity sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q== - dependencies: - minimatch "^5.0.1" - -fill-range@^7.1.1: - version "7.1.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" - integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== - dependencies: - to-regex-range "^5.0.1" - -find-up@^4.0.0, find-up@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" - integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== - dependencies: - locate-path "^5.0.0" - path-exists "^4.0.0" - -form-data@^4.0.0: - version "4.0.4" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.4.tgz#784cdcce0669a9d68e94d11ac4eea98088edd2c4" - integrity sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow== - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.8" - es-set-tostringtag "^2.1.0" - hasown "^2.0.2" - mime-types "^2.1.12" - -formdata-node@^6.0.3: - version "6.0.3" - resolved "https://registry.yarnpkg.com/formdata-node/-/formdata-node-6.0.3.tgz#48f8e2206ae2befded82af621ef015f08168dc6d" - integrity sha512-8e1++BCiTzUno9v5IZ2J6bv4RU+3UKDmqWUQD0MIMVCd9AdhWkO1gw57oo1mNEX1dMq2EGI+FbWz4B92pscSQg== - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== - -fsevents@^2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6" - integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== - -function-bind@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c" - integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA== - -gensync@^1.0.0-beta.2: - version "1.0.0-beta.2" - resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" - integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== - -get-caller-file@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" - integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== - -get-intrinsic@^1.2.5, get-intrinsic@^1.2.6, get-intrinsic@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz#743f0e3b6964a93a5491ed1bffaae054d7f98d01" - integrity sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ== - dependencies: - call-bind-apply-helpers "^1.0.2" - es-define-property "^1.0.1" - es-errors "^1.3.0" - es-object-atoms "^1.1.1" - function-bind "^1.1.2" - get-proto "^1.0.1" - gopd "^1.2.0" - has-symbols "^1.1.0" - hasown "^2.0.2" - math-intrinsics "^1.1.0" - -get-package-type@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a" - integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q== - -get-proto@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/get-proto/-/get-proto-1.0.1.tgz#150b3f2743869ef3e851ec0c49d15b1d14d00ee1" - integrity sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g== - dependencies: - dunder-proto "^1.0.1" - es-object-atoms "^1.0.0" - -get-stream@^6.0.0: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - -glob-to-regexp@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" - integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== - -glob@^7.1.3, glob@^7.1.4: - version "7.2.3" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" - integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.1.1" - once "^1.3.0" - path-is-absolute "^1.0.0" - -globals@^11.1.0: - version "11.12.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e" - integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== - -gopd@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1" - integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg== - -graceful-fs@^4.1.2, graceful-fs@^4.2.11, graceful-fs@^4.2.4, graceful-fs@^4.2.9: - version "4.2.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" - integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== - -has-flag@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" - integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== - -has-symbols@^1.0.3, has-symbols@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338" - integrity sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ== - -has-tostringtag@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/has-tostringtag/-/has-tostringtag-1.0.2.tgz#2cdc42d40bef2e5b4eeab7c01a73c54ce7ab5abc" - integrity sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw== - dependencies: - has-symbols "^1.0.3" - -hasown@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/hasown/-/hasown-2.0.2.tgz#003eaf91be7adc372e84ec59dc37252cedb80003" - integrity sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ== - dependencies: - function-bind "^1.1.2" - -html-encoding-sniffer@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz#2cb1a8cf0db52414776e5b2a7a04d5dd98158de9" - integrity sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA== - dependencies: - whatwg-encoding "^2.0.0" - -html-escaper@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" - integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== - -http-proxy-agent@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz#5129800203520d434f142bc78ff3c170800f2b43" - integrity sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w== - dependencies: - "@tootallnate/once" "2" - agent-base "6" - debug "4" - -https-proxy-agent@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz#c59ef224a04fe8b754f3db0063a25ea30d0005d6" - integrity sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA== - dependencies: - agent-base "6" - debug "4" - -human-signals@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" - integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== - -iconv-lite@0.6.3: - version "0.6.3" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501" - integrity sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw== - dependencies: - safer-buffer ">= 2.1.2 < 3.0.0" - -ieee754@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" - integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== - -import-local@^3.0.2: - version "3.2.0" - resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.2.0.tgz#c3d5c745798c02a6f8b897726aba5100186ee260" - integrity sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA== - dependencies: - pkg-dir "^4.2.0" - resolve-cwd "^3.0.0" - -imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA== - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== - -is-core-module@^2.16.0: - version "2.16.1" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.16.1.tgz#2a98801a849f43e2add644fbb6bc6229b19a4ef4" - integrity sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w== - dependencies: - hasown "^2.0.2" - -is-fullwidth-code-point@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" - integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== - -is-generator-fn@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" - integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - -is-potential-custom-element-name@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5" - integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ== - -is-stream@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" - integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== - -istanbul-lib-coverage@^3.0.0, istanbul-lib-coverage@^3.2.0: - version "3.2.2" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz#2d166c4b0644d43a39f04bf6c2edd1e585f31756" - integrity sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg== - -istanbul-lib-instrument@^5.0.4: - version "5.2.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz#d10c8885c2125574e1c231cacadf955675e1ce3d" - integrity sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg== - dependencies: - "@babel/core" "^7.12.3" - "@babel/parser" "^7.14.7" - "@istanbuljs/schema" "^0.1.2" - istanbul-lib-coverage "^3.2.0" - semver "^6.3.0" - -istanbul-lib-instrument@^6.0.0: - version "6.0.3" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz#fa15401df6c15874bcb2105f773325d78c666765" - integrity sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q== - dependencies: - "@babel/core" "^7.23.9" - "@babel/parser" "^7.23.9" - "@istanbuljs/schema" "^0.1.3" - istanbul-lib-coverage "^3.2.0" - semver "^7.5.4" - -istanbul-lib-report@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz#908305bac9a5bd175ac6a74489eafd0fc2445a7d" - integrity sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw== - dependencies: - istanbul-lib-coverage "^3.0.0" - make-dir "^4.0.0" - supports-color "^7.1.0" - -istanbul-lib-source-maps@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz#895f3a709fcfba34c6de5a42939022f3e4358551" - integrity sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw== - dependencies: - debug "^4.1.1" - istanbul-lib-coverage "^3.0.0" - source-map "^0.6.1" - -istanbul-reports@^3.1.3: - version "3.1.7" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.1.7.tgz#daed12b9e1dca518e15c056e1e537e741280fa0b" - integrity sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g== - dependencies: - html-escaper "^2.0.0" - istanbul-lib-report "^3.0.0" - -jake@^10.8.5: - version "10.9.2" - resolved "https://registry.yarnpkg.com/jake/-/jake-10.9.2.tgz#6ae487e6a69afec3a5e167628996b59f35ae2b7f" - integrity sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA== - dependencies: - async "^3.2.3" - chalk "^4.0.2" - filelist "^1.0.4" - minimatch "^3.1.2" - -jest-changed-files@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-29.7.0.tgz#1c06d07e77c78e1585d020424dedc10d6e17ac3a" - integrity sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w== - dependencies: - execa "^5.0.0" - jest-util "^29.7.0" - p-limit "^3.1.0" - -jest-circus@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-29.7.0.tgz#b6817a45fcc835d8b16d5962d0c026473ee3668a" - integrity sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw== - dependencies: - "@jest/environment" "^29.7.0" - "@jest/expect" "^29.7.0" - "@jest/test-result" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - chalk "^4.0.0" - co "^4.6.0" - dedent "^1.0.0" - is-generator-fn "^2.0.0" - jest-each "^29.7.0" - jest-matcher-utils "^29.7.0" - jest-message-util "^29.7.0" - jest-runtime "^29.7.0" - jest-snapshot "^29.7.0" - jest-util "^29.7.0" - p-limit "^3.1.0" - pretty-format "^29.7.0" - pure-rand "^6.0.0" - slash "^3.0.0" - stack-utils "^2.0.3" - -jest-cli@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-29.7.0.tgz#5592c940798e0cae677eec169264f2d839a37995" - integrity sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg== - dependencies: - "@jest/core" "^29.7.0" - "@jest/test-result" "^29.7.0" - "@jest/types" "^29.6.3" - chalk "^4.0.0" - create-jest "^29.7.0" - exit "^0.1.2" - import-local "^3.0.2" - jest-config "^29.7.0" - jest-util "^29.7.0" - jest-validate "^29.7.0" - yargs "^17.3.1" - -jest-config@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-29.7.0.tgz#bcbda8806dbcc01b1e316a46bb74085a84b0245f" - integrity sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ== - dependencies: - "@babel/core" "^7.11.6" - "@jest/test-sequencer" "^29.7.0" - "@jest/types" "^29.6.3" - babel-jest "^29.7.0" - chalk "^4.0.0" - ci-info "^3.2.0" - deepmerge "^4.2.2" - glob "^7.1.3" - graceful-fs "^4.2.9" - jest-circus "^29.7.0" - jest-environment-node "^29.7.0" - jest-get-type "^29.6.3" - jest-regex-util "^29.6.3" - jest-resolve "^29.7.0" - jest-runner "^29.7.0" - jest-util "^29.7.0" - jest-validate "^29.7.0" - micromatch "^4.0.4" - parse-json "^5.2.0" - pretty-format "^29.7.0" - slash "^3.0.0" - strip-json-comments "^3.1.1" - -jest-diff@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-29.7.0.tgz#017934a66ebb7ecf6f205e84699be10afd70458a" - integrity sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw== - dependencies: - chalk "^4.0.0" - diff-sequences "^29.6.3" - jest-get-type "^29.6.3" - pretty-format "^29.7.0" - -jest-docblock@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-29.7.0.tgz#8fddb6adc3cdc955c93e2a87f61cfd350d5d119a" - integrity sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g== - dependencies: - detect-newline "^3.0.0" - -jest-each@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-29.7.0.tgz#162a9b3f2328bdd991beaabffbb74745e56577d1" - integrity sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ== - dependencies: - "@jest/types" "^29.6.3" - chalk "^4.0.0" - jest-get-type "^29.6.3" - jest-util "^29.7.0" - pretty-format "^29.7.0" - -jest-environment-jsdom@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz#d206fa3551933c3fd519e5dfdb58a0f5139a837f" - integrity sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA== - dependencies: - "@jest/environment" "^29.7.0" - "@jest/fake-timers" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/jsdom" "^20.0.0" - "@types/node" "*" - jest-mock "^29.7.0" - jest-util "^29.7.0" - jsdom "^20.0.0" - -jest-environment-node@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-29.7.0.tgz#0b93e111dda8ec120bc8300e6d1fb9576e164376" - integrity sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw== - dependencies: - "@jest/environment" "^29.7.0" - "@jest/fake-timers" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - jest-mock "^29.7.0" - jest-util "^29.7.0" - -jest-get-type@^29.6.3: - version "29.6.3" - resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.6.3.tgz#36f499fdcea197c1045a127319c0481723908fd1" - integrity sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw== - -jest-haste-map@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-29.7.0.tgz#3c2396524482f5a0506376e6c858c3bbcc17b104" - integrity sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA== - dependencies: - "@jest/types" "^29.6.3" - "@types/graceful-fs" "^4.1.3" - "@types/node" "*" - anymatch "^3.0.3" - fb-watchman "^2.0.0" - graceful-fs "^4.2.9" - jest-regex-util "^29.6.3" - jest-util "^29.7.0" - jest-worker "^29.7.0" - micromatch "^4.0.4" - walker "^1.0.8" - optionalDependencies: - fsevents "^2.3.2" - -jest-leak-detector@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz#5b7ec0dadfdfec0ca383dc9aa016d36b5ea4c728" - integrity sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw== - dependencies: - jest-get-type "^29.6.3" - pretty-format "^29.7.0" - -jest-matcher-utils@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz#ae8fec79ff249fd592ce80e3ee474e83a6c44f12" - integrity sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g== - dependencies: - chalk "^4.0.0" - jest-diff "^29.7.0" - jest-get-type "^29.6.3" - pretty-format "^29.7.0" - -jest-message-util@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-29.7.0.tgz#8bc392e204e95dfe7564abbe72a404e28e51f7f3" - integrity sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w== - dependencies: - "@babel/code-frame" "^7.12.13" - "@jest/types" "^29.6.3" - "@types/stack-utils" "^2.0.0" - chalk "^4.0.0" - graceful-fs "^4.2.9" - micromatch "^4.0.4" - pretty-format "^29.7.0" - slash "^3.0.0" - stack-utils "^2.0.3" - -jest-mock@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-29.7.0.tgz#4e836cf60e99c6fcfabe9f99d017f3fdd50a6347" - integrity sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw== - dependencies: - "@jest/types" "^29.6.3" - "@types/node" "*" - jest-util "^29.7.0" - -jest-pnp-resolver@^1.2.2: - version "1.2.3" - resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz#930b1546164d4ad5937d5540e711d4d38d4cad2e" - integrity sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w== - -jest-regex-util@^29.6.3: - version "29.6.3" - resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-29.6.3.tgz#4a556d9c776af68e1c5f48194f4d0327d24e8a52" - integrity sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg== - -jest-resolve-dependencies@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz#1b04f2c095f37fc776ff40803dc92921b1e88428" - integrity sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA== - dependencies: - jest-regex-util "^29.6.3" - jest-snapshot "^29.7.0" - -jest-resolve@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-29.7.0.tgz#64d6a8992dd26f635ab0c01e5eef4399c6bcbc30" - integrity sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA== - dependencies: - chalk "^4.0.0" - graceful-fs "^4.2.9" - jest-haste-map "^29.7.0" - jest-pnp-resolver "^1.2.2" - jest-util "^29.7.0" - jest-validate "^29.7.0" - resolve "^1.20.0" - resolve.exports "^2.0.0" - slash "^3.0.0" - -jest-runner@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-29.7.0.tgz#809af072d408a53dcfd2e849a4c976d3132f718e" - integrity sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ== - dependencies: - "@jest/console" "^29.7.0" - "@jest/environment" "^29.7.0" - "@jest/test-result" "^29.7.0" - "@jest/transform" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - chalk "^4.0.0" - emittery "^0.13.1" - graceful-fs "^4.2.9" - jest-docblock "^29.7.0" - jest-environment-node "^29.7.0" - jest-haste-map "^29.7.0" - jest-leak-detector "^29.7.0" - jest-message-util "^29.7.0" - jest-resolve "^29.7.0" - jest-runtime "^29.7.0" - jest-util "^29.7.0" - jest-watcher "^29.7.0" - jest-worker "^29.7.0" - p-limit "^3.1.0" - source-map-support "0.5.13" - -jest-runtime@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-29.7.0.tgz#efecb3141cf7d3767a3a0cc8f7c9990587d3d817" - integrity sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ== - dependencies: - "@jest/environment" "^29.7.0" - "@jest/fake-timers" "^29.7.0" - "@jest/globals" "^29.7.0" - "@jest/source-map" "^29.6.3" - "@jest/test-result" "^29.7.0" - "@jest/transform" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - chalk "^4.0.0" - cjs-module-lexer "^1.0.0" - collect-v8-coverage "^1.0.0" - glob "^7.1.3" - graceful-fs "^4.2.9" - jest-haste-map "^29.7.0" - jest-message-util "^29.7.0" - jest-mock "^29.7.0" - jest-regex-util "^29.6.3" - jest-resolve "^29.7.0" - jest-snapshot "^29.7.0" - jest-util "^29.7.0" - slash "^3.0.0" - strip-bom "^4.0.0" - -jest-snapshot@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-29.7.0.tgz#c2c574c3f51865da1bb329036778a69bf88a6be5" - integrity sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw== - dependencies: - "@babel/core" "^7.11.6" - "@babel/generator" "^7.7.2" - "@babel/plugin-syntax-jsx" "^7.7.2" - "@babel/plugin-syntax-typescript" "^7.7.2" - "@babel/types" "^7.3.3" - "@jest/expect-utils" "^29.7.0" - "@jest/transform" "^29.7.0" - "@jest/types" "^29.6.3" - babel-preset-current-node-syntax "^1.0.0" - chalk "^4.0.0" - expect "^29.7.0" - graceful-fs "^4.2.9" - jest-diff "^29.7.0" - jest-get-type "^29.6.3" - jest-matcher-utils "^29.7.0" - jest-message-util "^29.7.0" - jest-util "^29.7.0" - natural-compare "^1.4.0" - pretty-format "^29.7.0" - semver "^7.5.3" - -jest-util@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-29.7.0.tgz#23c2b62bfb22be82b44de98055802ff3710fc0bc" - integrity sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA== - dependencies: - "@jest/types" "^29.6.3" - "@types/node" "*" - chalk "^4.0.0" - ci-info "^3.2.0" - graceful-fs "^4.2.9" - picomatch "^2.2.3" - -jest-validate@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.7.0.tgz#7bf705511c64da591d46b15fce41400d52147d9c" - integrity sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw== - dependencies: - "@jest/types" "^29.6.3" - camelcase "^6.2.0" - chalk "^4.0.0" - jest-get-type "^29.6.3" - leven "^3.1.0" - pretty-format "^29.7.0" - -jest-watcher@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-29.7.0.tgz#7810d30d619c3a62093223ce6bb359ca1b28a2f2" - integrity sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g== - dependencies: - "@jest/test-result" "^29.7.0" - "@jest/types" "^29.6.3" - "@types/node" "*" - ansi-escapes "^4.2.1" - chalk "^4.0.0" - emittery "^0.13.1" - jest-util "^29.7.0" - string-length "^4.0.1" - -jest-worker@^27.4.5: - version "27.5.1" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" - integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== - dependencies: - "@types/node" "*" - merge-stream "^2.0.0" - supports-color "^8.0.0" - -jest-worker@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-29.7.0.tgz#acad073acbbaeb7262bd5389e1bcf43e10058d4a" - integrity sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw== - dependencies: - "@types/node" "*" - jest-util "^29.7.0" - merge-stream "^2.0.0" - supports-color "^8.0.0" - -jest@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/jest/-/jest-29.7.0.tgz#994676fc24177f088f1c5e3737f5697204ff2613" - integrity sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw== - dependencies: - "@jest/core" "^29.7.0" - "@jest/types" "^29.6.3" - import-local "^3.0.2" - jest-cli "^29.7.0" - -js-base64@3.7.7: - version "3.7.7" - resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-3.7.7.tgz#e51b84bf78fbf5702b9541e2cb7bfcb893b43e79" - integrity sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw== - -js-tokens@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" - integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== - -js-yaml@^3.13.1: - version "3.14.2" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.2.tgz#77485ce1dd7f33c061fd1b16ecea23b55fcb04b0" - integrity sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg== - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -jsdom@^20.0.0: - version "20.0.3" - resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-20.0.3.tgz#886a41ba1d4726f67a8858028c99489fed6ad4db" - integrity sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ== - dependencies: - abab "^2.0.6" - acorn "^8.8.1" - acorn-globals "^7.0.0" - cssom "^0.5.0" - cssstyle "^2.3.0" - data-urls "^3.0.2" - decimal.js "^10.4.2" - domexception "^4.0.0" - escodegen "^2.0.0" - form-data "^4.0.0" - html-encoding-sniffer "^3.0.0" - http-proxy-agent "^5.0.0" - https-proxy-agent "^5.0.1" - is-potential-custom-element-name "^1.0.1" - nwsapi "^2.2.2" - parse5 "^7.1.1" - saxes "^6.0.0" - symbol-tree "^3.2.4" - tough-cookie "^4.1.2" - w3c-xmlserializer "^4.0.0" - webidl-conversions "^7.0.0" - whatwg-encoding "^2.0.0" - whatwg-mimetype "^3.0.0" - whatwg-url "^11.0.0" - ws "^8.11.0" - xml-name-validator "^4.0.0" - -jsesc@^3.0.2: - version "3.1.0" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-3.1.0.tgz#74d335a234f67ed19907fdadfac7ccf9d409825d" - integrity sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA== - -json-parse-even-better-errors@^2.3.0, json-parse-even-better-errors@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" - integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== - -json-schema-traverse@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" - integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== - -json5@^2.2.3: - version "2.2.3" - resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" - integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== - -kleur@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" - integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== - -leven@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2" - integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A== - -lines-and-columns@^1.1.6: - version "1.2.4" - resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" - integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== - -loader-runner@^4.2.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" - integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== - -locate-path@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" - integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== - dependencies: - p-locate "^4.1.0" - -lodash.memoize@^4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe" - integrity sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag== - -lru-cache@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" - integrity sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w== - dependencies: - yallist "^3.0.2" - -make-dir@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-4.0.0.tgz#c3c2307a771277cd9638305f915c29ae741b614e" - integrity sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw== - dependencies: - semver "^7.5.3" - -make-error@^1.3.6: - version "1.3.6" - resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" - integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== - -makeerror@1.0.12: - version "1.0.12" - resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.12.tgz#3e5dd2079a82e812e983cc6610c4a2cb0eaa801a" - integrity sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg== - dependencies: - tmpl "1.0.5" - -math-intrinsics@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9" - integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g== - -merge-stream@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" - integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== - -micromatch@^4.0.0, micromatch@^4.0.4: - version "4.0.8" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" - integrity sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA== - dependencies: - braces "^3.0.3" - picomatch "^2.3.1" - -mime-db@1.52.0: - version "1.52.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" - integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== - -mime-types@^2.1.12, mime-types@^2.1.27: - version "2.1.35" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" - integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== - dependencies: - mime-db "1.52.0" - -mimic-fn@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" - integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== - -minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== - dependencies: - brace-expansion "^1.1.7" - -minimatch@^5.0.1: - version "5.1.6" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" - integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== - dependencies: - brace-expansion "^2.0.1" - -ms@^2.1.3: - version "2.1.3" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" - integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== - -natural-compare@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" - integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== - -neo-async@^2.6.2: - version "2.6.2" - resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" - integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== - -node-fetch@^2.7.0: - version "2.7.0" - resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d" - integrity sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A== - dependencies: - whatwg-url "^5.0.0" - -node-int64@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" - integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== - -node-releases@^2.0.19: - version "2.0.19" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.19.tgz#9e445a52950951ec4d177d843af370b411caf314" - integrity sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw== - -normalize-path@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - -npm-run-path@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" - integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== - dependencies: - path-key "^3.0.0" - -nwsapi@^2.2.2: - version "2.2.20" - resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.20.tgz#22e53253c61e7b0e7e93cef42c891154bcca11ef" - integrity sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA== - -object-inspect@^1.13.3: - version "1.13.4" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" - integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew== - -once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== - dependencies: - wrappy "1" - -onetime@^5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" - integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== - dependencies: - mimic-fn "^2.1.0" - -p-limit@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" - integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== - dependencies: - p-try "^2.0.0" - -p-limit@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" - integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== - dependencies: - yocto-queue "^0.1.0" - -p-locate@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" - integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== - dependencies: - p-limit "^2.2.0" - -p-try@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" - integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== - -parse-json@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" - integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg== - dependencies: - "@babel/code-frame" "^7.0.0" - error-ex "^1.3.1" - json-parse-even-better-errors "^2.3.0" - lines-and-columns "^1.1.6" - -parse5@^7.0.0, parse5@^7.1.1: - version "7.3.0" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-7.3.0.tgz#d7e224fa72399c7a175099f45fc2ad024b05ec05" - integrity sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw== - dependencies: - entities "^6.0.0" - -path-exists@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" - integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg== - -path-key@^3.0.0, path-key@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" - integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== - -path-parse@^1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" - integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== - -picocolors@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" - integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== - -picomatch@^2.0.4, picomatch@^2.2.3, picomatch@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" - integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== - -pirates@^4.0.4: - version "4.0.7" - resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.7.tgz#643b4a18c4257c8a65104b73f3049ce9a0a15e22" - integrity sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA== - -pkg-dir@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" - integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== - dependencies: - find-up "^4.0.0" - -prettier@^3.4.2: - version "3.6.1" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.6.1.tgz#cc3bce21c09a477b1e987b76ce9663925d86ae44" - integrity sha512-5xGWRa90Sp2+x1dQtNpIpeOQpTDBs9cZDmA/qs2vDNN2i18PdapqY7CmBeyLlMuGqXJRIOPaCaVZTLNQRWUH/A== - -pretty-format@^29.0.0, pretty-format@^29.7.0: - version "29.7.0" - resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-29.7.0.tgz#ca42c758310f365bfa71a0bda0a807160b776812" - integrity sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ== - dependencies: - "@jest/schemas" "^29.6.3" - ansi-styles "^5.0.0" - react-is "^18.0.0" - -process@^0.11.10: - version "0.11.10" - resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" - integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== - -prompts@^2.0.1: - version "2.4.2" - resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069" - integrity sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q== - dependencies: - kleur "^3.0.3" - sisteransi "^1.0.5" - -psl@^1.1.33: - version "1.15.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.15.0.tgz#bdace31896f1d97cec6a79e8224898ce93d974c6" - integrity sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w== - dependencies: - punycode "^2.3.1" - -punycode@^2.1.1, punycode@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" - integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== - -pure-rand@^6.0.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2" - integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA== - -qs@^6.13.1: - version "6.14.0" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.14.0.tgz#c63fa40680d2c5c941412a0e899c89af60c0a930" - integrity sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w== - dependencies: - side-channel "^1.1.0" - -querystringify@^2.1.1: - version "2.2.0" - resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.2.0.tgz#3345941b4153cb9d082d8eee4cda2016a9aef7f6" - integrity sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ== - -randombytes@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" - integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== - dependencies: - safe-buffer "^5.1.0" - -react-is@^18.0.0: - version "18.3.1" - resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e" - integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg== - -readable-stream@^4.5.2: - version "4.7.0" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-4.7.0.tgz#cedbd8a1146c13dfff8dab14068028d58c15ac91" - integrity sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg== - dependencies: - abort-controller "^3.0.0" - buffer "^6.0.3" - events "^3.3.0" - process "^0.11.10" - string_decoder "^1.3.0" - -require-directory@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" - integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q== - -require-from-string@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" - integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== - -requires-port@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" - integrity sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ== - -resolve-cwd@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" - integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== - dependencies: - resolve-from "^5.0.0" - -resolve-from@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" - integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== - -resolve.exports@^2.0.0: - version "2.0.3" - resolved "https://registry.yarnpkg.com/resolve.exports/-/resolve.exports-2.0.3.tgz#41955e6f1b4013b7586f873749a635dea07ebe3f" - integrity sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A== - -resolve@^1.20.0: - version "1.22.10" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.10.tgz#b663e83ffb09bbf2386944736baae803029b8b39" - integrity sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w== - dependencies: - is-core-module "^2.16.0" - path-parse "^1.0.7" - supports-preserve-symlinks-flag "^1.0.0" - -safe-buffer@^5.1.0, safe-buffer@~5.2.0: - version "5.2.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" - integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== - -"safer-buffer@>= 2.1.2 < 3.0.0": - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== - -saxes@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/saxes/-/saxes-6.0.0.tgz#fe5b4a4768df4f14a201b1ba6a65c1f3d9988cc5" - integrity sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA== - dependencies: - xmlchars "^2.2.0" - -schema-utils@^4.3.0, schema-utils@^4.3.2: - version "4.3.2" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-4.3.2.tgz#0c10878bf4a73fd2b1dfd14b9462b26788c806ae" - integrity sha512-Gn/JaSk/Mt9gYubxTtSn/QCV4em9mpAPiR1rqy/Ocu19u/G9J5WWdNoUT4SiV6mFC3y6cxyFcFwdzPM3FgxGAQ== - dependencies: - "@types/json-schema" "^7.0.9" - ajv "^8.9.0" - ajv-formats "^2.1.1" - ajv-keywords "^5.1.0" - -semver@^6.3.0, semver@^6.3.1: - version "6.3.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" - integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== - -semver@^7.3.4, semver@^7.5.3, semver@^7.5.4, semver@^7.7.2: - version "7.7.2" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58" - integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA== - -serialize-javascript@^6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.2.tgz#defa1e055c83bf6d59ea805d8da862254eb6a6c2" - integrity sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g== - dependencies: - randombytes "^2.1.0" - -shebang-command@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" - integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== - dependencies: - shebang-regex "^3.0.0" - -shebang-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" - integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== - -side-channel-list@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad" - integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA== - dependencies: - es-errors "^1.3.0" - object-inspect "^1.13.3" - -side-channel-map@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/side-channel-map/-/side-channel-map-1.0.1.tgz#d6bb6b37902c6fef5174e5f533fab4c732a26f42" - integrity sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA== - dependencies: - call-bound "^1.0.2" - es-errors "^1.3.0" - get-intrinsic "^1.2.5" - object-inspect "^1.13.3" - -side-channel-weakmap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz#11dda19d5368e40ce9ec2bdc1fb0ecbc0790ecea" - integrity sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A== - dependencies: - call-bound "^1.0.2" - es-errors "^1.3.0" - get-intrinsic "^1.2.5" - object-inspect "^1.13.3" - side-channel-map "^1.0.1" - -side-channel@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9" - integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw== - dependencies: - es-errors "^1.3.0" - object-inspect "^1.13.3" - side-channel-list "^1.0.0" - side-channel-map "^1.0.1" - side-channel-weakmap "^1.0.2" - -signal-exit@^3.0.3, signal-exit@^3.0.7: - version "3.0.7" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" - integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== - -sisteransi@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" - integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg== - -slash@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" - integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== - -source-map-support@0.5.13: - version "0.5.13" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932" - integrity sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map-support@~0.5.20: - version "0.5.21" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" - integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -source-map@^0.7.4: - version "0.7.4" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.4.tgz#a9bbe705c9d8846f4e08ff6765acf0f1b0898656" - integrity sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA== - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g== - -stack-utils@^2.0.3: - version "2.0.6" - resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-2.0.6.tgz#aaf0748169c02fc33c8232abccf933f54a1cc34f" - integrity sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ== - dependencies: - escape-string-regexp "^2.0.0" - -string-length@^4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" - integrity sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ== - dependencies: - char-regex "^1.0.2" - strip-ansi "^6.0.0" - -string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: - version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - -string_decoder@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" - integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== - dependencies: - safe-buffer "~5.2.0" - -strip-ansi@^6.0.0, strip-ansi@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - -strip-bom@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" - integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== - -strip-final-newline@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" - integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== - -strip-json-comments@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" - integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== - -supports-color@^7.1.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" - integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== - dependencies: - has-flag "^4.0.0" - -supports-color@^8.0.0: - version "8.1.1" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" - integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== - dependencies: - has-flag "^4.0.0" - -supports-preserve-symlinks-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" - integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== - -symbol-tree@^3.2.4: - version "3.2.4" - resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" - integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== - -tapable@^2.1.1, tapable@^2.2.0: - version "2.2.2" - resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.2.tgz#ab4984340d30cb9989a490032f086dbb8b56d872" - integrity sha512-Re10+NauLTMCudc7T5WLFLAwDhQ0JWdrMK+9B2M8zR5hRExKmsRDCBA7/aV/pNJFltmBFO5BAMlQFi/vq3nKOg== - -terser-webpack-plugin@^5.3.11: - version "5.3.14" - resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.14.tgz#9031d48e57ab27567f02ace85c7d690db66c3e06" - integrity sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw== - dependencies: - "@jridgewell/trace-mapping" "^0.3.25" - jest-worker "^27.4.5" - schema-utils "^4.3.0" - serialize-javascript "^6.0.2" - terser "^5.31.1" - -terser@^5.31.1: - version "5.43.1" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.43.1.tgz#88387f4f9794ff1a29e7ad61fb2932e25b4fdb6d" - integrity sha512-+6erLbBm0+LROX2sPXlUYx/ux5PyE9K/a92Wrt6oA+WDAoFTdpHE5tCYCI5PNzq2y8df4rA+QgHLJuR4jNymsg== - dependencies: - "@jridgewell/source-map" "^0.3.3" - acorn "^8.14.0" - commander "^2.20.0" - source-map-support "~0.5.20" - -test-exclude@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" - integrity sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w== - dependencies: - "@istanbuljs/schema" "^0.1.2" - glob "^7.1.4" - minimatch "^3.0.4" - -tmpl@1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.5.tgz#8683e0b902bb9c20c4f726e3c0b69f36518c07cc" - integrity sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw== - -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - -tough-cookie@^4.1.2: - version "4.1.4" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.1.4.tgz#945f1461b45b5a8c76821c33ea49c3ac192c1b36" - integrity sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag== - dependencies: - psl "^1.1.33" - punycode "^2.1.1" - universalify "^0.2.0" - url-parse "^1.5.3" - -tr46@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-3.0.0.tgz#555c4e297a950617e8eeddef633c87d4d9d6cbf9" - integrity sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA== - dependencies: - punycode "^2.1.1" - -tr46@~0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" - integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw== - -ts-jest@^29.1.1: - version "29.4.0" - resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.4.0.tgz#bef0ee98d94c83670af7462a1617bf2367a83740" - integrity sha512-d423TJMnJGu80/eSgfQ5w/R+0zFJvdtTxwtF9KzFFunOpSeD+79lHJQIiAhluJoyGRbvj9NZJsl9WjCUo0ND7Q== - dependencies: - bs-logger "^0.2.6" - ejs "^3.1.10" - fast-json-stable-stringify "^2.1.0" - json5 "^2.2.3" - lodash.memoize "^4.1.2" - make-error "^1.3.6" - semver "^7.7.2" - type-fest "^4.41.0" - yargs-parser "^21.1.1" - -ts-loader@^9.5.1: - version "9.5.2" - resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-9.5.2.tgz#1f3d7f4bb709b487aaa260e8f19b301635d08020" - integrity sha512-Qo4piXvOTWcMGIgRiuFa6nHNm+54HbYaZCKqc9eeZCLRy3XqafQgwX2F7mofrbJG3g7EEb+lkiR+z2Lic2s3Zw== - dependencies: - chalk "^4.1.0" - enhanced-resolve "^5.0.0" - micromatch "^4.0.0" - semver "^7.3.4" - source-map "^0.7.4" - -type-detect@4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" - integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== - -type-fest@^0.21.3: - version "0.21.3" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37" - integrity sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w== - -type-fest@^4.41.0: - version "4.41.0" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.41.0.tgz#6ae1c8e5731273c2bf1f58ad39cbae2c91a46c58" - integrity sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA== - -typescript@~5.7.2: - version "5.7.3" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.7.3.tgz#919b44a7dbb8583a9b856d162be24a54bf80073e" - integrity sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw== - -undici-types@~5.26.4: - version "5.26.5" - resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" - integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== - -undici-types@~7.8.0: - version "7.8.0" - resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.8.0.tgz#de00b85b710c54122e44fbfd911f8d70174cd294" - integrity sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw== - -universalify@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.2.0.tgz#6451760566fa857534745ab1dde952d1b1761be0" - integrity sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg== - -update-browserslist-db@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz#348377dd245216f9e7060ff50b15a1b740b75420" - integrity sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw== - dependencies: - escalade "^3.2.0" - picocolors "^1.1.1" - -url-join@4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/url-join/-/url-join-4.0.1.tgz#b642e21a2646808ffa178c4c5fda39844e12cde7" - integrity sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA== - -url-parse@^1.5.3: - version "1.5.10" - resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.10.tgz#9d3c2f736c1d75dd3bd2be507dcc111f1e2ea9c1" - integrity sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ== - dependencies: - querystringify "^2.1.1" - requires-port "^1.0.0" - -v8-to-istanbul@^9.0.1: - version "9.3.0" - resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz#b9572abfa62bd556c16d75fdebc1a411d5ff3175" - integrity sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA== - dependencies: - "@jridgewell/trace-mapping" "^0.3.12" - "@types/istanbul-lib-coverage" "^2.0.1" - convert-source-map "^2.0.0" - -w3c-xmlserializer@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz#aebdc84920d806222936e3cdce408e32488a3073" - integrity sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw== - dependencies: - xml-name-validator "^4.0.0" - -walker@^1.0.8: - version "1.0.8" - resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f" - integrity sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ== - dependencies: - makeerror "1.0.12" - -watchpack@^2.4.1: - version "2.4.4" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.4.tgz#473bda72f0850453da6425081ea46fc0d7602947" - integrity sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA== - dependencies: - glob-to-regexp "^0.4.1" - graceful-fs "^4.1.2" - -webidl-conversions@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" - integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ== - -webidl-conversions@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-7.0.0.tgz#256b4e1882be7debbf01d05f0aa2039778ea080a" - integrity sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g== - -webpack-sources@^3.2.3: - version "3.3.3" - resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.3.3.tgz#d4bf7f9909675d7a070ff14d0ef2a4f3c982c723" - integrity sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg== - -webpack@^5.97.1: - version "5.99.9" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.99.9.tgz#d7de799ec17d0cce3c83b70744b4aedb537d8247" - integrity sha512-brOPwM3JnmOa+7kd3NsmOUOwbDAj8FT9xDsG3IW0MgbN9yZV7Oi/s/+MNQ/EcSMqw7qfoRyXPoeEWT8zLVdVGg== - dependencies: - "@types/eslint-scope" "^3.7.7" - "@types/estree" "^1.0.6" - "@types/json-schema" "^7.0.15" - "@webassemblyjs/ast" "^1.14.1" - "@webassemblyjs/wasm-edit" "^1.14.1" - "@webassemblyjs/wasm-parser" "^1.14.1" - acorn "^8.14.0" - browserslist "^4.24.0" - chrome-trace-event "^1.0.2" - enhanced-resolve "^5.17.1" - es-module-lexer "^1.2.1" - eslint-scope "5.1.1" - events "^3.2.0" - glob-to-regexp "^0.4.1" - graceful-fs "^4.2.11" - json-parse-even-better-errors "^2.3.1" - loader-runner "^4.2.0" - mime-types "^2.1.27" - neo-async "^2.6.2" - schema-utils "^4.3.2" - tapable "^2.1.1" - terser-webpack-plugin "^5.3.11" - watchpack "^2.4.1" - webpack-sources "^3.2.3" - -whatwg-encoding@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz#e7635f597fd87020858626805a2729fa7698ac53" - integrity sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg== - dependencies: - iconv-lite "0.6.3" - -whatwg-mimetype@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz#5fa1a7623867ff1af6ca3dc72ad6b8a4208beba7" - integrity sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q== - -whatwg-url@^11.0.0: - version "11.0.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-11.0.0.tgz#0a849eebb5faf2119b901bb76fd795c2848d4018" - integrity sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ== - dependencies: - tr46 "^3.0.0" - webidl-conversions "^7.0.0" - -whatwg-url@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" - integrity sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw== - dependencies: - tr46 "~0.0.3" - webidl-conversions "^3.0.0" - -which@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" - integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== - dependencies: - isexe "^2.0.0" - -wrap-ansi@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" - integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== - -write-file-atomic@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-4.0.2.tgz#a9df01ae5b77858a027fd2e80768ee433555fcfd" - integrity sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg== - dependencies: - imurmurhash "^0.1.4" - signal-exit "^3.0.7" - -ws@^8.11.0: - version "8.18.2" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.2.tgz#42738b2be57ced85f46154320aabb51ab003705a" - integrity sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ== - -xml-name-validator@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-4.0.0.tgz#79a006e2e63149a8600f15430f0a4725d1524835" - integrity sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw== - -xmlchars@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" - integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== - -y18n@^5.0.5: - version "5.0.8" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" - integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== - -yallist@^3.0.2: - version "3.1.1" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.1.1.tgz#dbb7daf9bfd8bac9ab45ebf602b8cbad0d5d08fd" - integrity sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g== - -yargs-parser@^21.1.1: - version "21.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" - integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== - -yargs@^17.3.1: - version "17.7.2" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.2.tgz#991df39aca675a192b816e1e0363f9d75d2aa269" - integrity sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w== - dependencies: - cliui "^8.0.1" - escalade "^3.1.1" - get-caller-file "^2.0.5" - require-directory "^2.1.1" - string-width "^4.2.3" - y18n "^5.0.5" - yargs-parser "^21.1.1" - -yocto-queue@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" - integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==