diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index d0e7b34118ad..2a68d8777080 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -2466,7 +2466,7 @@ packages: version: 0.0.0 '@rush-temp/ai-document-intelligence@file:projects/ai-document-intelligence.tgz': - resolution: {integrity: sha512-rK979Zu3i9HdmjhkPAgXOzd0NeXbFrY3YZVRjpjV2wogivrRPGkZZzbNRYCJ7jJbjdFmyOW0xaVddvmfvbqYuw==, tarball: file:projects/ai-document-intelligence.tgz} + resolution: {integrity: sha512-J8yhU3GdfISHJHRoDuseuqONoiPgMX3KIJUz4QS+hQqywxhyvstIC+3AHgD0ANGRlAylt6BbDT1P7MS+QRE3YQ==, tarball: file:projects/ai-document-intelligence.tgz} version: 0.0.0 '@rush-temp/ai-document-translator@file:projects/ai-document-translator.tgz': @@ -9969,15 +9969,15 @@ snapshots: '@rush-temp/ai-document-intelligence@file:projects/ai-document-intelligence.tgz(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2))(vite@5.4.11(@types/node@22.7.9))': dependencies: + '@microsoft/api-extractor': 7.48.0(@types/node@18.19.68) '@types/node': 18.19.68 - '@vitest/browser': 2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.6.3)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8) + '@vitest/browser': 2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.7.2)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8) '@vitest/coverage-istanbul': 2.1.8(vitest@2.1.8) dotenv: 16.4.7 eslint: 9.17.0 playwright: 1.49.1 - prettier: 3.4.2 tslib: 2.8.1 - typescript: 5.6.3 + typescript: 5.7.2 vitest: 2.1.8(@types/node@18.19.68)(@vitest/browser@2.1.8)(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2)) transitivePeerDependencies: - '@edge-runtime/vm' @@ -20546,6 +20546,27 @@ snapshots: - utf-8-validate - vite + '@vitest/browser@2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.7.2)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8)': + dependencies: + '@testing-library/dom': 10.4.0 + '@testing-library/user-event': 14.5.2(@testing-library/dom@10.4.0) + '@vitest/mocker': 2.1.8(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2))(vite@5.4.11(@types/node@22.7.9)) + '@vitest/utils': 2.1.8 + magic-string: 0.30.15 + msw: 2.6.8(@types/node@18.19.68)(typescript@5.7.2) + sirv: 3.0.0 + tinyrainbow: 1.2.0 + vitest: 2.1.8(@types/node@18.19.68)(@vitest/browser@2.1.8)(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2)) + ws: 8.18.0 + optionalDependencies: + playwright: 1.49.1 + transitivePeerDependencies: + - '@types/node' + - bufferutil + - typescript + - utf-8-validate + - vite + '@vitest/browser@2.1.8(@types/node@22.7.9)(playwright@1.49.1)(typescript@5.6.3)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8)': dependencies: '@testing-library/dom': 10.4.0 @@ -23116,6 +23137,31 @@ snapshots: transitivePeerDependencies: - '@types/node' + msw@2.6.8(@types/node@18.19.68)(typescript@5.7.2): + dependencies: + '@bundled-es-modules/cookie': 2.0.1 + '@bundled-es-modules/statuses': 1.0.1 + '@bundled-es-modules/tough-cookie': 0.1.6 + '@inquirer/confirm': 5.1.0(@types/node@18.19.68) + '@mswjs/interceptors': 0.37.3 + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/until': 2.1.0 + '@types/cookie': 0.6.0 + '@types/statuses': 2.0.5 + chalk: 4.1.2 + graphql: 16.9.0 + headers-polyfill: 4.0.3 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + strict-event-emitter: 0.5.1 + type-fest: 4.30.1 + yargs: 17.7.2 + optionalDependencies: + typescript: 5.7.2 + transitivePeerDependencies: + - '@types/node' + msw@2.6.8(@types/node@22.7.9)(typescript@5.6.3): dependencies: '@bundled-es-modules/cookie': 2.0.1 @@ -24475,7 +24521,7 @@ snapshots: resolve-import: 1.4.6 rimraf: 5.0.10 sync-content: 1.0.2 - typescript: 5.6.3 + typescript: 5.7.2 walk-up-path: 3.0.1 tshy@2.0.1: @@ -24489,7 +24535,7 @@ snapshots: resolve-import: 1.4.6 rimraf: 5.0.10 sync-content: 1.0.2 - typescript: 5.6.3 + typescript: 5.7.2 walk-up-path: 3.0.1 tslib@2.8.1: {} diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md b/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md index 8fb51ce69f32..c24698907524 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md +++ b/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md @@ -1,27 +1,114 @@ # Release History -## 1.0.0 (Unreleased) +## 1.0.0 (2024-12-16) ### Features Added -- Exports method `streamToUint8Array` to support converting a `NodeJS.ReadableStream` to a `Uint8Array`. This is necessary to read the pdf and png responses from the results of an analysis. - ```js +- Adds `streamToUint8Array`, a convenience function that buffers a `NodeJS.ReadableStream` in a `Uint8Array`. It can be used to read the pdf and png responses from the results of an analysis. + + ```ts + import DocumentIntelligence from "@azure-rest/ai-document-intelligence"; + import { streamToUint8Array } from "@azure-rest/ai-document-intelligence"; + + const client = DocumentIntelligence("", { + key: "", + }); + + // Do analysis on you document and get the resultId, figureId + // Example for the figures api that provides an image output - const output = await client - .path( - "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}", - "prebuilt-layout", - operationId, - figureId, - ) - .get() - .asNodeStream(); - - if (output.status !== "200" || !output.body) { - throw new Error("The response was unexpected."); - } + const output = await client + .path( + "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}", + "prebuilt-layout", + resultId, + figureId + ) + .get() + .asNodeStream(); // output.body would be NodeJS.ReadableStream + + if (output.status !== "200" || !output.body) { + throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body."); + } + + const imageData = await streamToUint8Array(output.body); + fs.promises.writeFile(`./figures/${figureId}.png`, imageData); // Or you can consume the NodeJS.ReadableStream directly ``` +- Adds `parseResultIdFromResponse`, a convenience function that extracts the `operationId` from the batch analysis response. + + ```js + // Example + const initialResponse = await client + .path("/documentModels/{modelId}:analyzeBatch", "prebuilt-layout") + .post({ + contentType: "application/json", + body: { + azureBlobSource: { + containerUrl: batchTrainingFilesContainerUrl(), + }, + resultContainerUrl: batchTrainingFilesResultContainerUrl(), + resultPrefix: "result", + }, + }); + + if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; + } + const batchResultId = parseResultIdFromResponse(initialResponse); + + const response = await client + .path( + "/documentModels/{modelId}/analyzeBatchResults/{resultId}", + "prebuilt-layout", + batchResultId + ) + .get(); + ``` + +- Changes the following interfaces as follows: + + - `AnalyzeBatchDocumentsBodyParam`: + - Updates `body` to be required. + - `AnalyzeBatchOperationOutput`: + - Adds `resultId`. + - `AnalyzeDocumentBodyParam`: + - Changes `body` from optional to required. + - `DocumentClassifierDetailsOutput`: + - Adds `modifiedDateTime`. + - `DocumentModelDetailsOutput`: + - Adds `modifiedDateTime`. + +- Introduces new interfaces to define query parameters for document analysis requests, allowing customizable `style` and `explode` options: + - **AnalyzeBatchDocumentsFeaturesQueryParam**: Accepts DocumentAnalysisFeature[] values. + - **AnalyzeBatchDocumentsOutputQueryParam**: Accepts AnalyzeOutputOption[] values. + - **AnalyzeBatchDocumentsQueryFieldsQueryParam**: Accepts string[] values. + - **AnalyzeDocumentFeaturesQueryParam**: Accepts DocumentAnalysisFeature[] values. + - **AnalyzeDocumentFromStreamFeaturesQueryParam**: Accepts DocumentAnalysisFeature[] values. + +### Breaking Changes + +- Removes the `poller.getOperationId()` for a given polling operation. Use `parseResultIdFromResponse` to extract the `operationId` directly. +- `getLongRunningPoller` function is not async anymore, do not `await` on it. + +### Other Changes + +The following types are renamed + +- `CopyAuthorization` to `ModelCopyAuthorization` +- `ErrorResponseOutput` to `DocumentIntelligenceErrorResponseOutput` +- `ErrorModelOutput` to `DocumentIntelligenceErrorOutput` +- `InnerErrorOutput` to `DocumentIntelligenceInnerErrorOutput` +- `WarningOutput` to `DocumentIntelligenceWarningOutput` +- `ContentFormat` to `DocumentContentFormat` +- `ContentFormatOutput` to `DocumentContentFormatOutput` +- `OperationDetailsOutputParent` to `DocumentIntelligenceOperationDetailsOutputParent` +- `OperationDetailsOutput` to `DocumentIntelligenceOperationDetailsOutput` +- `OperationStatusOutput` to `DocumentIntelligenceOperationStatusOutput` +- `ResourceDetailsOutput` to `DocumentIntelligenceResourceDetailsOutput` +- `PagedOperationDetailsOutput` to `PagedDocumentIntelligenceOperationDetailsOutput` +- `GetResourceInfo` to `GetResourceDetails` + ## 1.0.0-beta.3 (2024-08-20) ### Features Added diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/README.md b/sdk/documentintelligence/ai-document-intelligence-rest/README.md index 7f6e954883a7..fd0b172320a5 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/README.md +++ b/sdk/documentintelligence/ai-document-intelligence-rest/README.md @@ -15,15 +15,13 @@ Key links: - [Changelog](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md) - [Migration Guide from Form Recognizer](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest/MIGRATION-FR_v4-DI_v1.md) -> This version of the client library defaults to the `"2024-07-31-preview"` version of the service. +> This version of the client library defaults to the `"2024-11-30"` version of the service. This table shows the relationship between SDK versions and supported API versions of the service: | SDK version | Supported API version of service | | ------------ | -------------------------------- | -| 1.0.0-beta.3 | 2024-07-31-preview | -| 1.0.0-beta.2 | 2024-02-29-preview | -| 1.0.0-beta.1 | 2023-10-31-preview | +| 1.0.0 | 2024-11-30 | > Please rely on the older `@azure/ai-form-recognizer` library through the older service API versions for retired models, such as `"prebuilt-businessCard"` and `"prebuilt-document"`. For more information, see [Changelog](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest/CHANGELOG.md). @@ -31,9 +29,7 @@ The below table describes the relationship of each client and its supported API | Service API version | Supported clients | Package | | ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- | -| 2024-07-31-preview | DocumentIntelligenceClient | `@azure-rest/ai-document-intelligence` version `1.0.0-beta.3` | -| 2024-02-29-preview | DocumentIntelligenceClient | `@azure-rest/ai-document-intelligence` version `1.0.0-beta.2` | -| 2023-10-31-preview | DocumentIntelligenceClient | `@azure-rest/ai-document-intelligence` version `1.0.0-beta.1` | +| 2024-11-30 | DocumentIntelligenceClient | `@azure-rest/ai-document-intelligence` version `1.0.0` | | 2023-07-31 | DocumentAnalysisClient and DocumentModelAdministrationClient | `@azure/ai-form-recognizer` version `^5.0.0` | | 2022-08-01 | DocumentAnalysisClient and DocumentModelAdministrationClient | `@azure/ai-form-recognizer` version `^4.0.0` | @@ -77,7 +73,7 @@ import DocumentIntelligence from "@azure-rest/ai-document-intelligence"; const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], - new DefaultAzureCredential(), + new DefaultAzureCredential() ); ``` @@ -139,7 +135,7 @@ import { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } -const poller = await getLongRunningPoller(client, initialResponse); +const poller = getLongRunningPoller(client, initialResponse); const result = (await poller.pollUntilDone()).body as AnalyzeResultOperationOutput; console.log(result); // { @@ -156,6 +152,42 @@ console.log(result); // } ``` +## Batch analysis + +```ts +import { parseResultIdFromResponse, isUnexpected } from "@azure-rest/ai-document-intelligence"; + +// 1. Analyze a batch of documents +const initialResponse = await client + .path("/documentModels/{modelId}:analyzeBatch", "prebuilt-layout") + .post({ + contentType: "application/json", + body: { + azureBlobSource: { + containerUrl: batchTrainingFilesContainerUrl(), + }, + resultContainerUrl: batchTrainingFilesResultContainerUrl(), + resultPrefix: "result", + }, + }); + +if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; +} +const resultId = parseResultIdFromResponse(initialResponse); +console.log("resultId: ", resultId); + +// (Optional) You can poll for the batch analysis result but be aware that a job may take unexpectedly long time, and polling could incur additional costs. +// const poller = getLongRunningPoller(client, initialResponse); +// await poller.pollUntilDone(); + +// 2. At a later time, you can retrieve the operation result using the resultId +const output = await client + .path("/documentModels/{modelId}/analyzeResults/{resultId}", "prebuilt-layout", resultId) + .get(); +console.log(output); +``` + ### Markdown content format Supports output with Markdown content format along with the default plain _text_. For now, this is only supported for "prebuilt-layout". Markdown content format is deemed a more friendly format for LLM consumption in a chat or automation use scenario. @@ -246,7 +278,7 @@ const initialResponse = await client.path("/documentClassifiers:build").post({ if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } -const poller = await getLongRunningPoller(client, initialResponse); +const poller = getLongRunningPoller(client, initialResponse); const response = (await poller.pollUntilDone()) .body as DocumentClassifierBuildOperationDetailsOutput; console.log(response); @@ -267,6 +299,98 @@ console.log(response); // } ``` +## Get the generated PDF output from document analysis + +```ts +const filePath = path.join(ASSET_PATH, "layout-pageobject.pdf"); + +const base64Source = await fs.readFile(filePath, { encoding: "base64" }); + +const initialResponse = await client + .path("/documentModels/{modelId}:analyze", "prebuilt-read") + .post({ + contentType: "application/json", + body: { + base64Source, + }, + queryParameters: { output: ["pdf"] }, + }); + +if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; +} + +const poller = getLongRunningPoller(client, initialResponse); + +await poller.pollUntilDone(); + +const output = await client + .path( + "/documentModels/{modelId}/analyzeResults/{resultId}/pdf", + "prebuilt-read", + parseResultIdFromResponse(initialResponse) + ) + .get() + .asNodeStream(); // output.body would be NodeJS.ReadableStream + +if (output.status !== "200" || !output.body) { + throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body."); +} + +const pdfData = await streamToUint8Array(output.body); +fs.promises.writeFile(`./output.pdf`, pdfData); +// Or you can consume the NodeJS.ReadableStream directly +``` + +## Get the generated cropped image of specified figure from document analysis + +```ts +const filePath = path.join(ASSET_PATH, "layout-pageobject.pdf"); + +const base64Source = fs.readFileSync(filePath, { encoding: "base64" }); + +const initialResponse = await client + .path("/documentModels/{modelId}:analyze", "prebuilt-layout") + .post({ + contentType: "application/json", + body: { + base64Source, + }, + queryParameters: { output: ["figures"] }, + }); + +if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; +} + +const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); + +const result = (await poller.pollUntilDone()).body as AnalyzeResultOperationOutput; +const figures = result.analyzeResult?.figures; +assert.isArray(figures); +assert.isNotEmpty(figures?.[0]); +const figureId = figures?.[0].id || ""; +assert.isDefined(figureId); + +const output = await client + .path( + "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}", + "prebuilt-layout", + parseResultIdFromResponse(initialResponse), + figureId + ) + .get() + .asNodeStream(); // output.body would be NodeJS.ReadableStream + +if (output.status !== "200" || !output.body) { + throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body."); +} + +const imageData = await streamToUint8Array(output.body); +fs.promises.writeFile(`./figures/${figureId}.png`, imageData); +// Or you can consume the NodeJS.ReadableStream directly +``` + ## Get Info ```ts diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/api-extractor.json b/sdk/documentintelligence/ai-document-intelligence-rest/api-extractor.json index 6a70a0a1f069..569b4b8dba2c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/api-extractor.json +++ b/sdk/documentintelligence/ai-document-intelligence-rest/api-extractor.json @@ -6,7 +6,7 @@ "dtsRollup": { "enabled": true, "untrimmedFilePath": "", - "publicTrimmedFilePath": "./types/ai-document-intelligence.d.ts" + "publicTrimmedFilePath": "./dist/ai-document-intelligence.d.ts" }, "messages": { "tsdocMessageReporting": { "default": { "logLevel": "none" } }, diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/assets.json b/sdk/documentintelligence/ai-document-intelligence-rest/assets.json index ff651b11c442..667016ece17a 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/assets.json +++ b/sdk/documentintelligence/ai-document-intelligence-rest/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "js", "TagPrefix": "js/documentintelligence/ai-document-intelligence-rest", - "Tag": "js/documentintelligence/ai-document-intelligence-rest_c52f06c699" + "Tag": "js/documentintelligence/ai-document-intelligence-rest_77b0b5eb27" } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/karma.conf.js b/sdk/documentintelligence/ai-document-intelligence-rest/karma.conf.js deleted file mode 100644 index 4fdf26c79ac0..000000000000 --- a/sdk/documentintelligence/ai-document-intelligence-rest/karma.conf.js +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// https://github.com/karma-runner/karma-chrome-launcher -process.env.CHROME_BIN = require("puppeteer").executablePath(); -require("dotenv").config(); -const { relativeRecordingsPath } = require("@azure-tools/test-recorder"); -process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); - -module.exports = function (config) { - config.set({ - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: "./", - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ["source-map-support", "mocha"], - - plugins: [ - "karma-mocha", - "karma-mocha-reporter", - "karma-chrome-launcher", - "karma-firefox-launcher", - "karma-env-preprocessor", - "karma-coverage", - "karma-sourcemap-loader", - "karma-junit-reporter", - "karma-source-map-support", - ], - - // list of files / patterns to load in the browser - files: [ - "dist-test/index.browser.js", - { - pattern: "dist-test/index.browser.js.map", - type: "html", - included: false, - served: true, - }, - ], - - // list of files / patterns to exclude - exclude: [], - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - "**/*.js": ["sourcemap", "env"], - // IMPORTANT: COMMENT following line if you want to debug in your browsers!! - // Preprocess source file to calculate code coverage, however this will make source file unreadable - // "dist-test/index.js": ["coverage"] - }, - - envPreprocessor: [ - "TEST_MODE", - "ENDPOINT", - "AZURE_CLIENT_SECRET", - "AZURE_CLIENT_ID", - "AZURE_TENANT_ID", - "SUBSCRIPTION_ID", - "RECORDINGS_RELATIVE_PATH", - ], - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ["mocha", "coverage", "junit"], - - coverageReporter: { - // specify a common output directory - dir: "coverage-browser/", - reporters: [ - { type: "json", subdir: ".", file: "coverage.json" }, - { type: "lcovonly", subdir: ".", file: "lcov.info" }, - { type: "html", subdir: "html" }, - { type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" }, - ], - }, - - junitReporter: { - outputDir: "", // results will be saved as $outputDir/$browserName.xml - outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile - suite: "", // suite will become the package name attribute in xml testsuite element - useBrowserName: false, // add browser name to report and classes names - nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element - classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element - properties: {}, // key value pair of properties to add to the section of the report - }, - - // web server port - port: 9876, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - // --no-sandbox allows our tests to run in Linux without having to change the system. - // --disable-web-security allows us to authenticate from the browser without having to write tests using interactive auth, which would be far more complex. - browsers: ["ChromeHeadlessNoSandbox"], - customLaunchers: { - ChromeHeadlessNoSandbox: { - base: "ChromeHeadless", - flags: ["--no-sandbox", "--disable-web-security"], - }, - }, - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: 1, - - browserNoActivityTimeout: 60000000, - browserDisconnectTimeout: 10000, - browserDisconnectTolerance: 3, - - client: { - mocha: { - // change Karma's debug.html to the mocha web reporter - reporter: "html", - timeout: "600000", - }, - }, - }); -}; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/package.json b/sdk/documentintelligence/ai-document-intelligence-rest/package.json index 303c50776813..8005c8e2cf59 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/package.json +++ b/sdk/documentintelligence/ai-document-intelligence-rest/package.json @@ -8,6 +8,7 @@ "sideEffects": false, "autoPublish": false, "tshy": { + "project": "tsconfig.src.json", "exports": { "./package.json": "./package.json", ".": "./src/index.ts" @@ -20,17 +21,14 @@ "browser", "react-native" ], - "selfLink": false, - "project": "./tsconfig.src.json" + "selfLink": false }, "type": "module", "keywords": [ "node", "azure", "cloud", - "typescript", - "browser", - "isomorphic" + "typescript" ], "author": "Microsoft Corporation", "license": "MIT", @@ -46,6 +44,7 @@ "bugs": { "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest/README.md", "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", "//metadata": { "constantPaths": [ @@ -56,55 +55,53 @@ ] }, "dependencies": { - "@azure-rest/core-client": "^2.1.0", - "@azure/abort-controller": "^2.1.2", - "@azure/core-auth": "^1.6.0", - "@azure/core-lro": "^3.0.0", - "@azure/core-paging": "^1.5.0", - "@azure/core-rest-pipeline": "^1.5.0", - "@azure/logger": "^1.0.0", - "tslib": "^2.6.2" + "@azure-rest/core-client": "^2.3.1", + "@azure/core-auth": "^1.9.0", + "@azure/core-rest-pipeline": "^1.18.1", + "@azure/logger": "^1.1.4", + "tslib": "^2.8.1", + "@azure/core-lro": "^3.1.0" }, "devDependencies": { - "@azure-tools/test-credential": "^2.0.0", - "@azure-tools/test-recorder": "^4.0.0", - "@azure/core-util": "^1.0.0", - "@azure/dev-tool": "^1.0.0", - "@azure/eslint-plugin-azure-sdk": "^3.0.0", - "@azure/identity": "^4.2.1", + "@azure/abort-controller": "^2.1.2", + "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", "@types/node": "^18.0.0", + "eslint": "^9.9.0", + "typescript": "~5.7.2", + "@azure/identity": "^4.2.1", "@vitest/browser": "^2.0.5", "@vitest/coverage-istanbul": "^2.0.5", - "dotenv": "^16.0.0", - "eslint": "^9.9.0", "playwright": "^1.41.2", - "prettier": "^3.2.5", - "typescript": "~5.6.2", - "vitest": "^2.0.5" + "vitest": "^2.0.5", + "@azure-tools/test-credential": "^2.0.0", + "@azure-tools/test-recorder": "^4.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0" }, "scripts": { - "build": "npm run clean && dev-tool run build-package && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", - "build:samples": "dev-tool samples publish --force", - "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", - "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\"", - "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", - "execute:samples": "dev-tool samples run samples-dev", + "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz", "extract-api": "dev-tool run vendored rimraf review && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", - "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\"", - "generate:client": "echo skipped", - "integration-test": "npm run integration-test:node && npm run integration-test:browser", - "integration-test:browser": "echo skipped", - "integration-test:node": "echo skipped", + "pack": "npm pack 2>&1", "lint": "eslint package.json api-extractor.json src test", "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", - "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", - "pack": "npm pack 2>&1", - "test": "npm run clean && dev-tool run build-package && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", - "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", - "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", "unit-test": "npm run unit-test:node && npm run unit-test:browser", "unit-test:browser": "echo skipped", - "unit-test:node": "dev-tool run test:vitest", + "unit-test:node": "dev-tool run test:vitest --test-proxy-debug", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "integration-test:browser": "echo skipped", + "integration-test:node": "dev-tool run test:vitest --esm", + "build:samples": "echo skipped", + "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "execute:samples": "echo skipped", + "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"samples-dev/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "generate:client": "echo skipped", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", + "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", + "build": "npm run clean && dev-tool run build-package && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && dev-tool run build-package && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", "update-snippets": "echo skipped" }, "exports": { diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/review/ai-document-intelligence.api.md b/sdk/documentintelligence/ai-document-intelligence-rest/review/ai-document-intelligence.api.md index 5bfc1b8048ad..73db7904c269 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/review/ai-document-intelligence.api.md +++ b/sdk/documentintelligence/ai-document-intelligence-rest/review/ai-document-intelligence.api.md @@ -4,17 +4,13 @@ ```ts -import type { AbortSignalLike } from '@azure/abort-controller'; -import type { CancelOnProgress } from '@azure/core-lro'; import type { Client } from '@azure-rest/core-client'; import type { ClientOptions } from '@azure-rest/core-client'; -import type { CreateHttpPollerOptions } from '@azure/core-lro'; import type { HttpResponse } from '@azure-rest/core-client'; import type { KeyCredential } from '@azure/core-auth'; import type { OperationState } from '@azure/core-lro'; -import type { Paged } from '@azure/core-paging'; -import type { PagedAsyncIterableIterator } from '@azure/core-paging'; import type { PathUncheckedResponse } from '@azure-rest/core-client'; +import type { PollerLike } from '@azure/core-lro'; import type { RawHttpHeaders } from '@azure/core-rest-pipeline'; import type { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; import type { RequestParameters } from '@azure-rest/core-client'; @@ -61,17 +57,24 @@ export interface AnalyzeBatchDocuments202Response extends HttpResponse { // @public (undocumented) export interface AnalyzeBatchDocumentsBodyParam { - body?: AnalyzeBatchDocumentsRequest; + body: AnalyzeBatchDocumentsRequest; } // @public (undocumented) export interface AnalyzeBatchDocumentsDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } +// @public +export interface AnalyzeBatchDocumentsFeaturesQueryParam { + explode: false; + style: "form"; + value: DocumentAnalysisFeature[]; +} + // @public export interface AnalyzeBatchDocumentsLogicalResponse extends HttpResponse { // (undocumented) @@ -83,9 +86,23 @@ export interface AnalyzeBatchDocumentsMediaTypesParam { contentType: "application/json"; } +// @public +export interface AnalyzeBatchDocumentsOutputQueryParam { + explode: false; + style: "form"; + value: AnalyzeOutputOption[]; +} + // @public (undocumented) export type AnalyzeBatchDocumentsParameters = AnalyzeBatchDocumentsQueryParam & AnalyzeBatchDocumentsMediaTypesParam & AnalyzeBatchDocumentsBodyParam & RequestParameters; +// @public +export interface AnalyzeBatchDocumentsQueryFieldsQueryParam { + explode: false; + style: "form"; + value: string[]; +} + // @public (undocumented) export interface AnalyzeBatchDocumentsQueryParam { // (undocumented) @@ -94,12 +111,12 @@ export interface AnalyzeBatchDocumentsQueryParam { // @public (undocumented) export interface AnalyzeBatchDocumentsQueryParamProperties { - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeBatchDocumentsFeaturesQueryParam; locale?: string; - output?: AnalyzeOutputOption[]; - outputContentFormat?: ContentFormat; + output?: AnalyzeOutputOption[] | AnalyzeBatchDocumentsOutputQueryParam; + outputContentFormat?: DocumentContentFormat; pages?: string; - queryFields?: string[]; + queryFields?: string[] | AnalyzeBatchDocumentsQueryFieldsQueryParam; stringIndexType?: StringIndexType; } @@ -114,30 +131,40 @@ export interface AnalyzeBatchDocumentsRequest { // @public export interface AnalyzeBatchOperationDetailOutput { - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; resultUrl?: string; sourceUrl: string; - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; } // @public -export interface AnalyzeBatchResultOperationOutput { +export interface AnalyzeBatchOperationOutput { createdDateTime: string; - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; lastUpdatedDateTime: string; percentCompleted?: number; result?: AnalyzeBatchResultOutput; - status: OperationStatusOutput; + resultId?: string; + status: DocumentIntelligenceOperationStatusOutput; } // @public export interface AnalyzeBatchResultOutput { - details: Array; + details?: Array; failedCount: number; skippedCount: number; succeededCount: number; } +// @public +export interface AnalyzedDocumentOutput { + boundingRegions?: Array; + confidence: number; + docType: string; + fields?: Record; + spans: Array; +} + // @public (undocumented) export interface AnalyzeDocument202Headers { // (undocumented) @@ -155,17 +182,24 @@ export interface AnalyzeDocument202Response extends HttpResponse { // @public (undocumented) export interface AnalyzeDocumentBodyParam { - body?: AnalyzeDocumentRequest; + body: AnalyzeDocumentRequest; } // @public (undocumented) export interface AnalyzeDocumentDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } +// @public +export interface AnalyzeDocumentFeaturesQueryParam { + explode: false; + style: "form"; + value: DocumentAnalysisFeature[]; +} + // @public (undocumented) export interface AnalyzeDocumentFromStream { post(options: AnalyzeDocumentFromStreamParameters): StreamableMethod; @@ -195,11 +229,18 @@ export interface AnalyzeDocumentFromStreamBodyParam { // @public (undocumented) export interface AnalyzeDocumentFromStreamDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } +// @public +export interface AnalyzeDocumentFromStreamFeaturesQueryParam { + explode: false; + style: "form"; + value: DocumentAnalysisFeature[]; +} + // @public export interface AnalyzeDocumentFromStreamLogicalResponse extends HttpResponse { // (undocumented) @@ -211,9 +252,23 @@ export interface AnalyzeDocumentFromStreamMediaTypesParam { contentType: "application/octet-stream" | "application/pdf" | "image/jpeg" | "image/png" | "image/tiff" | "image/bmp" | "image/heif" | "text/html" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } +// @public +export interface AnalyzeDocumentFromStreamOutputQueryParam { + explode: false; + style: "form"; + value: AnalyzeOutputOption[]; +} + // @public (undocumented) export type AnalyzeDocumentFromStreamParameters = AnalyzeDocumentFromStreamQueryParam & AnalyzeDocumentFromStreamMediaTypesParam & AnalyzeDocumentFromStreamBodyParam & RequestParameters; +// @public +export interface AnalyzeDocumentFromStreamQueryFieldsQueryParam { + explode: false; + style: "form"; + value: string[]; +} + // @public (undocumented) export interface AnalyzeDocumentFromStreamQueryParam { // (undocumented) @@ -222,12 +277,12 @@ export interface AnalyzeDocumentFromStreamQueryParam { // @public (undocumented) export interface AnalyzeDocumentFromStreamQueryParamProperties { - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeDocumentFromStreamFeaturesQueryParam; locale?: string; - output?: AnalyzeOutputOption[]; - outputContentFormat?: ContentFormat; + output?: AnalyzeOutputOption[] | AnalyzeDocumentFromStreamOutputQueryParam; + outputContentFormat?: DocumentContentFormat; pages?: string; - queryFields?: string[]; + queryFields?: string[] | AnalyzeDocumentFromStreamQueryFieldsQueryParam; stringIndexType?: StringIndexType; } @@ -242,9 +297,23 @@ export interface AnalyzeDocumentMediaTypesParam { contentType: "application/json"; } +// @public +export interface AnalyzeDocumentOutputQueryParam { + explode: false; + style: "form"; + value: AnalyzeOutputOption[]; +} + // @public (undocumented) export type AnalyzeDocumentParameters = AnalyzeDocumentQueryParam & AnalyzeDocumentMediaTypesParam & AnalyzeDocumentBodyParam & RequestParameters; +// @public +export interface AnalyzeDocumentQueryFieldsQueryParam { + explode: false; + style: "form"; + value: string[]; +} + // @public (undocumented) export interface AnalyzeDocumentQueryParam { // (undocumented) @@ -253,12 +322,12 @@ export interface AnalyzeDocumentQueryParam { // @public (undocumented) export interface AnalyzeDocumentQueryParamProperties { - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeDocumentFeaturesQueryParam; locale?: string; - output?: AnalyzeOutputOption[]; - outputContentFormat?: ContentFormat; + output?: AnalyzeOutputOption[] | AnalyzeDocumentOutputQueryParam; + outputContentFormat?: DocumentContentFormat; pages?: string; - queryFields?: string[]; + queryFields?: string[] | AnalyzeDocumentQueryFieldsQueryParam; stringIndexType?: StringIndexType; } @@ -269,23 +338,23 @@ export interface AnalyzeDocumentRequest { } // @public -export type AnalyzeOutputOption = string; - -// @public -export interface AnalyzeResultOperationOutput { +export interface AnalyzeOperationOutput { analyzeResult?: AnalyzeResultOutput; createdDateTime: string; - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; lastUpdatedDateTime: string; - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; } +// @public +export type AnalyzeOutputOption = string; + // @public export interface AnalyzeResultOutput { apiVersion: string; content: string; - contentFormat?: ContentFormatOutput; - documents?: Array; + contentFormat?: DocumentContentFormatOutput; + documents?: Array; figures?: Array; keyValuePairs?: Array; languages?: Array; @@ -296,7 +365,7 @@ export interface AnalyzeResultOutput { stringIndexType: StringIndexTypeOutput; styles?: Array; tables?: Array; - warnings?: Array; + warnings?: Array; } // @public (undocumented) @@ -320,7 +389,7 @@ export interface AuthorizeClassifierCopyBodyParam { // @public (undocumented) export interface AuthorizeClassifierCopyDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -350,7 +419,7 @@ export interface AuthorizeModelCopy { // @public export interface AuthorizeModelCopy200Response extends HttpResponse { // (undocumented) - body: CopyAuthorizationOutput; + body: ModelCopyAuthorizationOutput; // (undocumented) status: "200"; } @@ -363,7 +432,7 @@ export interface AuthorizeModelCopyBodyParam { // @public (undocumented) export interface AuthorizeModelCopyDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -429,7 +498,7 @@ export interface BuildClassifierBodyParam { // @public (undocumented) export interface BuildClassifierDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -492,7 +561,7 @@ export interface BuildModelBodyParam { // @public (undocumented) export interface BuildModelDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -563,7 +632,7 @@ export interface ClassifyDocumentBodyParam { // @public (undocumented) export interface ClassifyDocumentDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -597,7 +666,7 @@ export interface ClassifyDocumentFromStreamBodyParam { // @public (undocumented) export interface ClassifyDocumentFromStreamDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -700,7 +769,7 @@ export interface ComposeModelBodyParam { // @public (undocumented) export interface ComposeModelDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -714,38 +783,12 @@ export interface ComposeModelLogicalResponse extends HttpResponse { // @public (undocumented) export type ComposeModelParameters = ComposeModelBodyParam & RequestParameters; -// @public -export type ContentFormat = string; - -// @public -export type ContentFormatOutput = string; - // @public export type ContentSourceKind = string; // @public export type ContentSourceKindOutput = string; -// @public -export interface CopyAuthorization { - accessToken: string; - expirationDateTime: Date | string; - targetModelId: string; - targetModelLocation: string; - targetResourceId: string; - targetResourceRegion: string; -} - -// @public -export interface CopyAuthorizationOutput { - accessToken: string; - expirationDateTime: string; - targetModelId: string; - targetModelLocation: string; - targetResourceId: string; - targetResourceRegion: string; -} - // @public (undocumented) export interface CopyClassifierTo { post(options: CopyClassifierToParameters): StreamableMethod; @@ -774,7 +817,7 @@ export interface CopyClassifierToBodyParam { // @public (undocumented) export interface CopyClassifierToDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -810,13 +853,13 @@ export interface CopyModelTo202Response extends HttpResponse { // @public (undocumented) export interface CopyModelToBodyParam { - body: CopyAuthorization; + body: ModelCopyAuthorization; } // @public (undocumented) export interface CopyModelToDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -847,6 +890,40 @@ export interface CustomDocumentModelsDetailsOutput { limit: number; } +// @public +export interface DeleteAnalyzeBatchResult204Response extends HttpResponse { + // (undocumented) + status: "204"; +} + +// @public (undocumented) +export interface DeleteAnalyzeBatchResultDefaultResponse extends HttpResponse { + // (undocumented) + body: DocumentIntelligenceErrorResponseOutput; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type DeleteAnalyzeBatchResultParameters = RequestParameters; + +// @public +export interface DeleteAnalyzeResult204Response extends HttpResponse { + // (undocumented) + status: "204"; +} + +// @public (undocumented) +export interface DeleteAnalyzeResultDefaultResponse extends HttpResponse { + // (undocumented) + body: DocumentIntelligenceErrorResponseOutput; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type DeleteAnalyzeResultParameters = RequestParameters; + // @public (undocumented) export interface DeleteClassifier204Headers { "x-ms-client-request-id"?: string; @@ -863,7 +940,7 @@ export interface DeleteClassifier204Response extends HttpResponse { // @public (undocumented) export interface DeleteClassifierDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -898,7 +975,7 @@ export interface DeleteModel204Response extends HttpResponse { // @public (undocumented) export interface DeleteModelDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -950,13 +1027,13 @@ export interface DocumentCaptionOutput { } // @public -export interface DocumentClassifierBuildOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentClassifierBuildOperationDetailsOutput extends DocumentIntelligenceOperationDetailsOutputParent { kind: "documentClassifierBuild"; result?: DocumentClassifierDetailsOutput; } // @public -export interface DocumentClassifierCopyToOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentClassifierCopyToOperationDetailsOutput extends DocumentIntelligenceOperationDetailsOutputParent { kind: "documentClassifierCopyTo"; result?: DocumentClassifierDetailsOutput; } @@ -970,9 +1047,16 @@ export interface DocumentClassifierDetailsOutput { description?: string; docTypes: Record; expirationDateTime?: string; - warnings?: Array; + readonly modifiedDateTime?: string; + warnings?: Array; } +// @public +export type DocumentContentFormat = string; + +// @public +export type DocumentContentFormatOutput = string; + // @public export interface DocumentFieldOutput { boundingRegions?: Array; @@ -1031,6 +1115,12 @@ export interface DocumentFigureOutput { spans: Array; } +// @public +export type DocumentFontStyleOutput = string; + +// @public +export type DocumentFontWeightOutput = string; + // @public export interface DocumentFootnoteOutput { boundingRegions?: Array; @@ -1061,6 +1151,60 @@ export interface DocumentIntelligenceClientOptions extends ClientOptions { apiVersion?: string; } +// @public +export interface DocumentIntelligenceErrorOutput { + code: string; + details?: Array; + innererror?: DocumentIntelligenceInnerErrorOutput; + message: string; + target?: string; +} + +// @public +export interface DocumentIntelligenceErrorResponseOutput { + error: DocumentIntelligenceErrorOutput; +} + +// @public +export interface DocumentIntelligenceInnerErrorOutput { + code?: string; + innererror?: DocumentIntelligenceInnerErrorOutput; + message?: string; +} + +// @public +export type DocumentIntelligenceOperationDetailsOutput = DocumentIntelligenceOperationDetailsOutputParent | DocumentModelBuildOperationDetailsOutput | DocumentModelComposeOperationDetailsOutput | DocumentModelCopyToOperationDetailsOutput | DocumentClassifierCopyToOperationDetailsOutput | DocumentClassifierBuildOperationDetailsOutput; + +// @public +export interface DocumentIntelligenceOperationDetailsOutputParent { + apiVersion?: string; + createdDateTime: string; + error?: DocumentIntelligenceErrorOutput; + // (undocumented) + kind: OperationKindOutput; + lastUpdatedDateTime: string; + operationId: string; + percentCompleted?: number; + resourceLocation: string; + status: DocumentIntelligenceOperationStatusOutput; + tags?: Record; +} + +// @public +export type DocumentIntelligenceOperationStatusOutput = string; + +// @public +export interface DocumentIntelligenceResourceDetailsOutput { + customDocumentModels: CustomDocumentModelsDetailsOutput; +} + +// @public +export interface DocumentIntelligenceWarningOutput { + code: string; + message: string; + target?: string; +} + // @public export interface DocumentKeyValueElementOutput { boundingRegions?: Array; @@ -1090,19 +1234,19 @@ export interface DocumentLineOutput { } // @public -export interface DocumentModelBuildOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelBuildOperationDetailsOutput extends DocumentIntelligenceOperationDetailsOutputParent { kind: "documentModelBuild"; result?: DocumentModelDetailsOutput; } // @public -export interface DocumentModelComposeOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelComposeOperationDetailsOutput extends DocumentIntelligenceOperationDetailsOutputParent { kind: "documentModelCompose"; result?: DocumentModelDetailsOutput; } // @public -export interface DocumentModelCopyToOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelCopyToOperationDetailsOutput extends DocumentIntelligenceOperationDetailsOutputParent { kind: "documentModelCopyTo"; result?: DocumentModelDetailsOutput; } @@ -1119,19 +1263,11 @@ export interface DocumentModelDetailsOutput { readonly docTypes?: Record; readonly expirationDateTime?: string; modelId: string; + readonly modifiedDateTime?: string; split?: SplitModeOutput; tags?: Record; readonly trainingHours?: number; - readonly warnings?: Array; -} - -// @public -export interface DocumentOutput { - boundingRegions?: Array; - confidence: number; - docType: string; - fields?: Record; - spans: Array; + readonly warnings?: Array; } // @public @@ -1188,8 +1324,8 @@ export interface DocumentStyleOutput { backgroundColor?: string; color?: string; confidence: number; - fontStyle?: FontStyleOutput; - fontWeight?: FontWeightOutput; + fontStyle?: DocumentFontStyleOutput; + fontWeight?: DocumentFontWeightOutput; isHandwritten?: boolean; similarFontFamily?: string; spans: Array; @@ -1256,35 +1392,16 @@ export interface DocumentWordOutput { span: DocumentSpanOutput; } -// @public -export interface ErrorModelOutput { - code: string; - details?: Array; - innererror?: InnerErrorOutput; - message: string; - target?: string; -} - -// @public -export interface ErrorResponseOutput { - error: ErrorModelOutput; -} - -// @public -export type FontStyleOutput = string; - -// @public -export type FontWeightOutput = string; - // @public (undocumented) export interface GetAnalyzeBatchResult { + delete(options?: DeleteAnalyzeBatchResultParameters): StreamableMethod; get(options?: GetAnalyzeBatchResultParameters): StreamableMethod; } // @public export interface GetAnalyzeBatchResult200Response extends HttpResponse { // (undocumented) - body: AnalyzeBatchResultOperationOutput; + body: AnalyzeBatchOperationOutput; // (undocumented) status: "200"; } @@ -1292,7 +1409,7 @@ export interface GetAnalyzeBatchResult200Response extends HttpResponse { // @public (undocumented) export interface GetAnalyzeBatchResultDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1302,13 +1419,14 @@ export type GetAnalyzeBatchResultParameters = RequestParameters; // @public (undocumented) export interface GetAnalyzeResult { + delete(options?: DeleteAnalyzeResultParameters): StreamableMethod; get(options?: GetAnalyzeResultParameters): StreamableMethod; } // @public export interface GetAnalyzeResult200Response extends HttpResponse { // (undocumented) - body: AnalyzeResultOperationOutput; + body: AnalyzeOperationOutput; // (undocumented) status: "200"; } @@ -1316,7 +1434,7 @@ export interface GetAnalyzeResult200Response extends HttpResponse { // @public (undocumented) export interface GetAnalyzeResultDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1343,7 +1461,7 @@ export interface GetAnalyzeResultFigure200Response extends HttpResponse { // @public (undocumented) export interface GetAnalyzeResultFigureDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1376,7 +1494,7 @@ export interface GetAnalyzeResultPdf200Response extends HttpResponse { // @public (undocumented) export interface GetAnalyzeResultPdfDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1411,7 +1529,7 @@ export interface GetClassifier200Response extends HttpResponse { // @public (undocumented) export interface GetClassifierDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1438,7 +1556,7 @@ export interface GetClassifyResult { // @public export interface GetClassifyResult200Response extends HttpResponse { // (undocumented) - body: AnalyzeResultOperationOutput; + body: AnalyzeOperationOutput; // (undocumented) status: "200"; } @@ -1446,7 +1564,7 @@ export interface GetClassifyResult200Response extends HttpResponse { // @public (undocumented) export interface GetClassifyResultDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1472,7 +1590,7 @@ export interface GetDocumentClassifierBuildOperation200Response extends HttpResp // @public (undocumented) export interface GetDocumentClassifierBuildOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1509,7 +1627,7 @@ export interface GetDocumentClassifierCopyToOperation200Response extends HttpRes // @public (undocumented) export interface GetDocumentClassifierCopyToOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1556,7 +1674,7 @@ export interface GetDocumentModelBuildOperation200Response extends HttpResponse // @public (undocumented) export interface GetDocumentModelBuildOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1593,7 +1711,7 @@ export interface GetDocumentModelComposeOperation200Response extends HttpRespons // @public (undocumented) export interface GetDocumentModelComposeOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1630,7 +1748,7 @@ export interface GetDocumentModelCopyToOperation200Response extends HttpResponse // @public (undocumented) export interface GetDocumentModelCopyToOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1650,28 +1768,34 @@ export interface GetDocumentModelCopyToOperationHeaders { export type GetDocumentModelCopyToOperationParameters = GetDocumentModelCopyToOperationHeaderParam & RequestParameters; // @public -export function getLongRunningPoller(client: Client, initialResponse: AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: BuildModel202Response | BuildModelDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: BuildModel202Response | BuildModelDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: ComposeModel202Response | ComposeModelDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: ComposeModel202Response | ComposeModelDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: CopyModelTo202Response | CopyModelToDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: CopyModelTo202Response | CopyModelToDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: BuildClassifier202Response | BuildClassifierDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: BuildClassifier202Response | BuildClassifierDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: CopyClassifierTo202Response | CopyClassifierToDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: CopyClassifierTo202Response | CopyClassifierToDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: AnalyzeDocumentFromStream202Response | AnalyzeDocumentFromStreamDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: AnalyzeDocumentFromStream202Response | AnalyzeDocumentFromStreamDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; // @public (undocumented) -export function getLongRunningPoller(client: Client, initialResponse: ClassifyDocumentFromStream202Response | ClassifyDocumentFromStreamDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; +export function getLongRunningPoller(client: Client, initialResponse: ClassifyDocumentFromStream202Response | ClassifyDocumentFromStreamDefaultResponse, options?: GetLongRunningPollerOptions): PollerLike, TResult>; + +// @public +export interface GetLongRunningPollerOptions { + intervalInMs?: number; + restoreFrom?: string; +} // @public (undocumented) export interface GetModel { @@ -1697,7 +1821,7 @@ export interface GetModel200Response extends HttpResponse { // @public (undocumented) export interface GetModelDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1724,7 +1848,7 @@ export interface GetOperation200Headers { // @public export interface GetOperation200Response extends HttpResponse { // (undocumented) - body: OperationDetailsOutput; + body: DocumentIntelligenceOperationDetailsOutput; // (undocumented) headers: RawHttpHeaders & GetOperation200Headers; // (undocumented) @@ -1734,7 +1858,7 @@ export interface GetOperation200Response extends HttpResponse { // @public (undocumented) export interface GetOperationDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1754,41 +1878,34 @@ export interface GetOperationHeaders { export type GetOperationParameters = GetOperationHeaderParam & RequestParameters; // @public -export type GetPage = (pageLink: string, maxPageSize?: number) => Promise<{ +export type GetPage = (pageLink: string) => Promise<{ page: TPage; nextPageLink?: string; }>; // @public (undocumented) -export interface GetResourceInfo { - get(options?: GetResourceInfoParameters): StreamableMethod; +export interface GetResourceDetails { + get(options?: GetResourceDetailsParameters): StreamableMethod; } // @public -export interface GetResourceInfo200Response extends HttpResponse { +export interface GetResourceDetails200Response extends HttpResponse { // (undocumented) - body: ResourceDetailsOutput; + body: DocumentIntelligenceResourceDetailsOutput; // (undocumented) status: "200"; } // @public (undocumented) -export interface GetResourceInfoDefaultResponse extends HttpResponse { +export interface GetResourceDetailsDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } // @public (undocumented) -export type GetResourceInfoParameters = RequestParameters; - -// @public -export interface InnerErrorOutput { - code?: string; - innererror?: InnerErrorOutput; - message?: string; -} +export type GetResourceDetailsParameters = RequestParameters; // @public (undocumented) export function isUnexpected(response: ListOperations200Response | ListOperationsDefaultResponse): response is ListOperationsDefaultResponse; @@ -1812,11 +1929,14 @@ export function isUnexpected(response: GetDocumentClassifierBuildOperation200Res export function isUnexpected(response: GetOperation200Response | GetOperationDefaultResponse): response is GetOperationDefaultResponse; // @public (undocumented) -export function isUnexpected(response: GetResourceInfo200Response | GetResourceInfoDefaultResponse): response is GetResourceInfoDefaultResponse; +export function isUnexpected(response: GetResourceDetails200Response | GetResourceDetailsDefaultResponse): response is GetResourceDetailsDefaultResponse; // @public (undocumented) export function isUnexpected(response: GetAnalyzeResult200Response | GetAnalyzeResultDefaultResponse): response is GetAnalyzeResultDefaultResponse; +// @public (undocumented) +export function isUnexpected(response: DeleteAnalyzeResult204Response | DeleteAnalyzeResultDefaultResponse): response is DeleteAnalyzeResultDefaultResponse; + // @public (undocumented) export function isUnexpected(response: GetAnalyzeResultPdf200Response | GetAnalyzeResultPdfDefaultResponse): response is GetAnalyzeResultPdfDefaultResponse; @@ -1832,9 +1952,15 @@ export function isUnexpected(response: AnalyzeDocument202Response | AnalyzeDocum // @public (undocumented) export function isUnexpected(response: GetAnalyzeBatchResult200Response | GetAnalyzeBatchResultDefaultResponse): response is GetAnalyzeBatchResultDefaultResponse; +// @public (undocumented) +export function isUnexpected(response: DeleteAnalyzeBatchResult204Response | DeleteAnalyzeBatchResultDefaultResponse): response is DeleteAnalyzeBatchResultDefaultResponse; + // @public (undocumented) export function isUnexpected(response: AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsLogicalResponse | AnalyzeBatchDocumentsDefaultResponse): response is AnalyzeBatchDocumentsDefaultResponse; +// @public (undocumented) +export function isUnexpected(response: ListAnalyzeBatchResults200Response | ListAnalyzeBatchResultsDefaultResponse): response is ListAnalyzeBatchResultsDefaultResponse; + // @public (undocumented) export function isUnexpected(response: GetModel200Response | GetModelDefaultResponse): response is GetModelDefaultResponse; @@ -1886,6 +2012,30 @@ export function isUnexpected(response: CopyClassifierTo202Response | CopyClassif // @public export type LengthUnitOutput = string; +// @public (undocumented) +export interface ListAnalyzeBatchResults { + get(options?: ListAnalyzeBatchResultsParameters): StreamableMethod; +} + +// @public +export interface ListAnalyzeBatchResults200Response extends HttpResponse { + // (undocumented) + body: PagedAnalyzeBatchOperationOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface ListAnalyzeBatchResultsDefaultResponse extends HttpResponse { + // (undocumented) + body: DocumentIntelligenceErrorResponseOutput; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type ListAnalyzeBatchResultsParameters = RequestParameters; + // @public (undocumented) export interface ListClassifiers { get(options?: ListClassifiersParameters): StreamableMethod; @@ -1909,7 +2059,7 @@ export interface ListClassifiers200Response extends HttpResponse { // @public (undocumented) export interface ListClassifiersDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1951,7 +2101,7 @@ export interface ListModels200Response extends HttpResponse { // @public (undocumented) export interface ListModelsDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -1983,7 +2133,7 @@ export interface ListOperations200Headers { // @public export interface ListOperations200Response extends HttpResponse { // (undocumented) - body: PagedOperationDetailsOutput; + body: PagedDocumentIntelligenceOperationDetailsOutput; // (undocumented) headers: RawHttpHeaders & ListOperations200Headers; // (undocumented) @@ -1993,7 +2143,7 @@ export interface ListOperations200Response extends HttpResponse { // @public (undocumented) export interface ListOperationsDefaultResponse extends HttpResponse { // (undocumented) - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; // (undocumented) status: string; } @@ -2013,37 +2163,63 @@ export interface ListOperationsHeaders { export type ListOperationsParameters = ListOperationsHeaderParam & RequestParameters; // @public -export type OperationDetailsOutput = OperationDetailsOutputParent | DocumentModelBuildOperationDetailsOutput | DocumentModelComposeOperationDetailsOutput | DocumentModelCopyToOperationDetailsOutput | DocumentClassifierCopyToOperationDetailsOutput | DocumentClassifierBuildOperationDetailsOutput; +export interface ModelCopyAuthorization { + accessToken: string; + expirationDateTime: Date | string; + targetModelId: string; + targetModelLocation: string; + targetResourceId: string; + targetResourceRegion: string; +} // @public -export interface OperationDetailsOutputParent { - apiVersion?: string; - createdDateTime: string; - error?: ErrorModelOutput; - // (undocumented) - kind: OperationKindOutput; - lastUpdatedDateTime: string; - operationId: string; - percentCompleted?: number; - resourceLocation: string; - status: OperationStatusOutput; - tags?: Record; +export interface ModelCopyAuthorizationOutput { + accessToken: string; + expirationDateTime: string; + targetModelId: string; + targetModelLocation: string; + targetResourceId: string; + targetResourceRegion: string; } // @public export type OperationKindOutput = string; // @public -export type OperationStatusOutput = string; +export interface PagedAnalyzeBatchOperationOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedDocumentClassifierDetailsOutput = Paged; +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} // @public -export type PagedDocumentModelDetailsOutput = Paged; +export interface PagedDocumentClassifierDetailsOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedOperationDetailsOutput = Paged; +export interface PagedDocumentIntelligenceOperationDetailsOutput { + nextLink?: string; + value: Array; +} + +// @public +export interface PagedDocumentModelDetailsOutput { + nextLink?: string; + value: Array; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} // @public export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; @@ -2064,21 +2240,24 @@ export interface PagingOptions { export type ParagraphRoleOutput = string; // @public -export interface ResourceDetailsOutput { - customDocumentModels: CustomDocumentModelsDetailsOutput; -} +export function parseResultIdFromResponse(initialResponse: { + headers: { + "operation-location": string; + }; +}): string; // @public (undocumented) export interface Routes { (path: "/operations"): ListOperations; (path: "/operations/{operationId}", operationId: string): GetDocumentModelBuildOperation; - (path: "/info"): GetResourceInfo; + (path: "/info"): GetResourceDetails; (path: "/documentModels/{modelId}/analyzeResults/{resultId}", modelId: string, resultId: string): GetAnalyzeResult; (path: "/documentModels/{modelId}/analyzeResults/{resultId}/pdf", modelId: string, resultId: string): GetAnalyzeResultPdf; (path: "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}", modelId: string, resultId: string, figureId: string): GetAnalyzeResultFigure; (path: "/documentModels/{modelId}:analyze", modelId: string): AnalyzeDocumentFromStream; (path: "/documentModels/{modelId}/analyzeBatchResults/{resultId}", modelId: string, resultId: string): GetAnalyzeBatchResult; (path: "/documentModels/{modelId}:analyzeBatch", modelId: string): AnalyzeBatchDocuments; + (path: "/documentModels/{modelId}/analyzeBatchResults", modelId: string): ListAnalyzeBatchResults; (path: "/documentModels/{modelId}", modelId: string): GetModel; (path: "/documentModels:build"): BuildModel; (path: "/documentModels:compose"): ComposeModel; @@ -2094,29 +2273,6 @@ export interface Routes { (path: "/documentClassifiers/{classifierId}:copyTo", classifierId: string): CopyClassifierTo; } -// @public -export interface SimplePollerLike, TResult> { - getOperationId(): string; - getOperationState(): TState; - getResult(): TResult | undefined; - isDone(): boolean; - // @deprecated - isStopped(): boolean; - onProgress(callback: (state: TState) => void): CancelOnProgress; - poll(options?: { - abortSignal?: AbortSignalLike; - }): Promise; - pollUntilDone(pollOptions?: { - abortSignal?: AbortSignalLike; - }): Promise; - serialize(): Promise; - // @deprecated - stopPolling(): void; - submitted(): Promise; - // @deprecated - toString(): string; -} - // @public export type SplitMode = string; @@ -2132,13 +2288,6 @@ export type StringIndexType = string; // @public export type StringIndexTypeOutput = string; -// @public -export interface WarningOutput { - code: string; - message: string; - target?: string; -} - // (No @packageDocumentation comment for this package) ``` diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeDocumentByModelId.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeDocumentByModelId.ts index ac70505c598a..412f8b4cd4ec 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeDocumentByModelId.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeDocumentByModelId.ts @@ -8,7 +8,11 @@ * @summary analyze a document using a model by ID */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -16,25 +20,24 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) - const modelId = process.env.DOCUMENT_INTELLIGENCE_CUSTOM_MODEL_ID || "";// "prebuilt-layout"; - - const initialResponse = await client - .path("/documentModels/{modelId}:analyze", modelId) - .post({ - contentType: "application/json", - body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - }, - queryParameters: { locale: "en-IN" }, - }); + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); + const modelId = process.env.DOCUMENT_INTELLIGENCE_CUSTOM_MODEL_ID || ""; // "prebuilt-layout"; + + const initialResponse = await client.path("/documentModels/{modelId}:analyze", modelId).post({ + contentType: "application/json", + body: { + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, + queryParameters: { locale: "en-IN" }, + }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -46,7 +49,7 @@ async function main() { console.log( "Extracted document:", document.docType, - `(confidence: ${document.confidence || ""})` + `(confidence: ${document.confidence || ""})`, ); console.log("Fields:", document.fields); } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeIdentityDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeIdentityDocument.ts index 37df16bc9b66..f36f4877b514 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeIdentityDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeIdentityDocument.ts @@ -14,7 +14,11 @@ * @azsdk-skip-javascript */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -22,7 +26,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-idDocument") @@ -38,10 +43,9 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -54,10 +58,10 @@ async function main() { if (document.docType === "idDocument.driverLicense") { // For the sake of the example, we'll only show a few of the fields that are produced. console.log("Extracted a Driver License:"); - console.log(document.fields) + console.log(document.fields); } else if (document.docType === "idDocument.passport") { console.log("Extracted a Passport:"); - console.log(document.fields) + console.log(document.fields); } else { // The only reason this would happen is if the client library's schema for the prebuilt identity document model is // out of date, and a new document type has been introduced. diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeInvoice.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeInvoice.ts index ed2ce320051d..e3f39430535b 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeInvoice.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeInvoice.ts @@ -13,16 +13,20 @@ * @azsdk-skip-javascript */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { - const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-invoice") @@ -30,16 +34,16 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to an invoice image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/sample_invoice.jpg", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/sample_invoice.jpg", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -48,7 +52,6 @@ async function main() { throw new Error("Expected at least one document in the result."); } - // Use of PrebuiltModels.Receipt above (rather than the raw model ID), adds strong typing of the model's output if (document) { console.log(document.fields); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceipt.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceipt.ts index 8f0eaeae8bc7..e68d6aab3275 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceipt.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceipt.ts @@ -13,7 +13,11 @@ * @azsdk-skip-javascript */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-receipt") @@ -29,23 +34,21 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to a receipt image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const document = documents && documents[0]; - - // Use of PrebuiltModels.Receipt above (rather than the raw model ID), as it adds strong typing of the model's output if (document) { console.log(document.fields); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceiptByModelId.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceiptByModelId.ts index c8fc574766e9..ec88ecb37416 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceiptByModelId.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeReceiptByModelId.ts @@ -14,7 +14,11 @@ * @summary use the "prebuilt-receipt" model ID to extract data from a receipt document (weakly-typed) */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -22,7 +26,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-receipt") @@ -30,18 +35,18 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to a receipt image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); poller.onProgress((state) => console.log("Operation:", state.result, state.status)); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeW2TaxForm.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeW2TaxForm.ts index 261e0eb6011d..7992dc13b971 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeW2TaxForm.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/analyzeW2TaxForm.ts @@ -13,7 +13,11 @@ * @azsdk-skip-javascript */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import fs from "fs"; import path from "path"; @@ -23,7 +27,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const filePath = fs.readFileSync(path.join(".", "assets", "w2", "w2-single.png")); @@ -42,10 +47,9 @@ async function main() { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const document = documents?.[0]; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildClassifier.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildClassifier.ts index 9358f1110f00..bd588fe7a180 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildClassifier.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildClassifier.ts @@ -13,7 +13,11 @@ * @summary build a classifier from a training data set */ -import DocumentIntelligence, { DocumentClassifierBuildOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentClassifierBuildOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const random = Date.now().toString(); const modelId = @@ -49,21 +54,20 @@ async function main() { }, }, }, - } + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const classifier = ( - (await (poller).pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput ).result; if (!classifier) { throw new Error("Expected a DocumentClassifierDetailsOutput response."); } - console.log("Classifier ID:", classifier.classifierId); console.log("Description:", classifier.description); console.log("Created:", classifier.createdDateTime); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildModel.ts index c6edbc8d4c3b..e33c05a9e8c3 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/buildModel.ts @@ -13,7 +13,11 @@ * @summary build a model with a single document type from a training data set */ -import DocumentIntelligence, { DocumentModelBuildOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelBuildOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const random = Date.now().toString(); const modelId = (process.env.CUSTOM_MODEL_ID || "") + random.substring(random.length - 6); @@ -33,7 +38,7 @@ async function main() { buildMode: "template", modelId, azureBlobSource: { - containerUrl: trainingDataSasUrl + containerUrl: trainingDataSasUrl, }, }, }); @@ -42,9 +47,8 @@ async function main() { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse); - const model = ( - (await (await poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput - ).result; + const model = ((await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput) + .result; if (!model) { throw new Error("Expected a DocumentModelDetailsOutput response."); } @@ -58,7 +62,7 @@ async function main() { console.log("Document Types:"); for (const [docType, { description, fieldSchema: schema }] of Object.entries( - model.docTypes || {} + model.docTypes || {}, )) { console.log(`- Name: "${docType}"`); console.log(` Description: "${description}"`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/classifyDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/classifyDocument.ts index ad6ba315f0e3..74da4718ec41 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/classifyDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/classifyDocument.ts @@ -7,7 +7,11 @@ * @summary use a custom classifier to classify a document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -15,7 +19,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const documentUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/Invoice_1.pdf"; @@ -33,10 +38,9 @@ async function main() { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; if (analyzeResult?.documents === undefined || analyzeResult.documents.length === 0) { throw new Error("Failed to extract any documents."); @@ -44,7 +48,7 @@ async function main() { for (const document of analyzeResult.documents) { console.log( - `Extracted a document with type '${document.docType}' on page ${document.boundingRegions?.[0].pageNumber} (confidence: ${document.confidence})` + `Extracted a document with type '${document.docType}' on page ${document.boundingRegions?.[0].pageNumber} (confidence: ${document.confidence})`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/composeModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/composeModel.ts index 5efd520d392a..e54b96687e81 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/composeModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/composeModel.ts @@ -12,7 +12,12 @@ * @azsdk-weight 60 */ -import DocumentIntelligence, { DocumentModelBuildOperationDetailsOutput, DocumentModelComposeOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelBuildOperationDetailsOutput, + DocumentModelComposeOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -20,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // This object will hold the SAS-encoded URLs to containers that hold // different types of purchase order documents and their labels. @@ -43,28 +49,27 @@ async function main() { const random = Date.now().toString(); const modelIds = await Promise.all( - Object.entries(purchaseOrderSasUrls) - .map(async ([kind, sasUrl]) => { - const modelId = kind + "ComponentModel" + random.substring(random.length - 6); - const initialResponse = await client.path("/documentModels:build").post({ - body: { - buildMode: "template", - modelId: modelId, - azureBlobSource: { - containerUrl: sasUrl, - }, + Object.entries(purchaseOrderSasUrls).map(async ([kind, sasUrl]) => { + const modelId = kind + "ComponentModel" + random.substring(random.length - 6); + const initialResponse = await client.path("/documentModels:build").post({ + body: { + buildMode: "template", + modelId: modelId, + azureBlobSource: { + containerUrl: sasUrl, }, - }); - if (isUnexpected(initialResponse)) { - throw initialResponse.body.error; - } - const poller = await getLongRunningPoller(client, initialResponse); - const { docTypes } = ( - (await (poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput - ).result!; - - return docTypes; - }) + }, + }); + if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; + } + const poller = getLongRunningPoller(client, initialResponse); + const { docTypes } = ( + (await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput + ).result!; + + return docTypes; + }), ); // Finally, create the composed model. @@ -74,22 +79,22 @@ async function main() { const initialResponse = await client.path("/documentModels:compose").post({ body: { modelId: composedModelId, - description: "A composed model that classifies purchase order documents and extracts data from them.", + description: + "A composed model that classifies purchase order documents and extracts data from them.", classifierId: "classifierId", // Add the appropriate classifier ID here docTypes: { model1: modelIds[0]!.modelId, model2: modelIds[1]!.modelId }, - } + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const composedModel = ( - (await (poller).pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput ).result!; - console.log("Model ID:", composedModel.modelId); console.log("Description:", composedModel.description); console.log("Created:", composedModel.createdDateTime); @@ -99,7 +104,7 @@ async function main() { console.log("Document Types:"); for (const [docType, { description, fieldSchema: schema }] of Object.entries( - composedModel.docTypes || {} + composedModel.docTypes || {}, )) { console.log(`- Name: "${docType}"`); console.log(` Description: "${description}"`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/copyModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/copyModel.ts index 2da44e98c499..770ca9369fc1 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/copyModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/copyModel.ts @@ -8,13 +8,16 @@ * @summary copy a model from one resource to another */ -import DocumentIntelligence, { DocumentModelCopyToOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelCopyToOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { - const random = Date.now().toString(); const destinationModelId = (process.env.CUSTOM_MODEL_ID || "") + random.substring(random.length - 6); @@ -23,7 +26,8 @@ async function main() { // const destinationClient = new DocumentModelAdministrationClient(endpoint, credential); const destinationClient = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // const authorization = await destinationClient.getCopyAuthorization(destinationModelId); const targetAuth = await destinationClient.path("/documentModels:authorizeCopy").post({ body: { @@ -37,9 +41,9 @@ async function main() { const sourceModelId = process.env.COPY_SOURCE_MODEL_ID || ""; // Then, the source resource can initiate the copy operation. - const sourceClient = DocumentIntelligence( - sourceEndpoint, - { key: process.env.DOCUMENT_INTELLIGENCE_SOURCE_API_KEY || "" }) + const sourceClient = DocumentIntelligence(sourceEndpoint, { + key: process.env.DOCUMENT_INTELLIGENCE_SOURCE_API_KEY || "", + }); const copyInitResponse = await sourceClient .path("/documentModels/{modelId}:copyTo", sourceModelId) @@ -52,7 +56,7 @@ async function main() { } const copyPoller = getLongRunningPoller(sourceClient, copyInitResponse); const model = ( - (await (await copyPoller).pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput + (await copyPoller.pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput ).result!; console.log("Model ID:", model.modelId); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/extractLayout.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/extractLayout.ts index 6b94c2622512..dbef977c700e 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/extractLayout.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/extractLayout.ts @@ -10,8 +10,11 @@ * @azsdk-skip-javascript */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; - +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -19,15 +22,17 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-layout") .post({ contentType: "application/json", body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", + }, }); if (isUnexpected(initialResponse)) { @@ -35,9 +40,8 @@ async function main() { } const poller = getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -50,7 +54,7 @@ async function main() { console.log("- Page", page.pageNumber, `(unit: ${page.unit})`); console.log(` ${page.width}x${page.height}, angle: ${page.angle}`); console.log( - ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words` + ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words`, ); if (page.lines && page.lines.length > 0) { @@ -69,7 +73,7 @@ async function main() { console.log("Tables:"); for (const table of tables) { console.log( - `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)` + `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getClassifier.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getClassifier.ts index 1a6352dba334..485c036f598c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getClassifier.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getClassifier.ts @@ -16,7 +16,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const classifierId = process.env.CUSTOM_CLASSIFIER_ID ?? ""; const classifier = await client.path("/documentClassifiers/{classifierId}", classifierId).get(); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getInfo.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getInfo.ts index b5644db43610..0bb24c9015dc 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getInfo.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getInfo.ts @@ -16,13 +16,14 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const info = await client.path("/info").get(); if (isUnexpected(info)) { throw info.body.error; } console.log( - `Custom document models: ${info.body.customDocumentModels.count} of ${info.body.customDocumentModels.limit}` + `Custom document models: ${info.body.customDocumentModels.count} of ${info.body.customDocumentModels.limit}`, ); } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getModel.ts index 1ca43511e8c0..83ee41f56905 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/getModel.ts @@ -16,7 +16,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // The model ID to query. This can be any model ID, not just a custom model, so for example // the following sample uses `"prebuilt-idDocument"`, but you can change it to any model ID diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/listModels.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/listModels.ts index eb081a1ce61a..da0439c2078c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/listModels.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/listModels.ts @@ -15,8 +15,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) - + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const response = await client.path("/documentModels").get(); if (isUnexpected(response)) { @@ -29,7 +29,7 @@ async function main() { console.log(" Description: ", model.description || ""); // The model summary does not include `docTypes`, so we must additionally call `getModel` to retrieve them - const detailedModel = (await client.path("/documentModels/{modelId}", model.modelId).get()); + const detailedModel = await client.path("/documentModels/{modelId}", model.modelId).get(); if (isUnexpected(detailedModel)) { throw detailedModel.body.error; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/readDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/readDocument.ts index 440c4e16040c..165fe439f147 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/readDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples-dev/readDocument.ts @@ -7,7 +7,11 @@ * @summary use the prebuilt "read" model to extract information about the text content of a document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -15,14 +19,16 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-read") .post({ contentType: "application/json", body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", }, queryParameters: { features: ["barcodes"] }, }); @@ -30,11 +36,9 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; - + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; // The "prebuilt-read" model (`beginReadDocument` method) only extracts information about the textual content of the // document, such as page text elements and information about the language of the text. @@ -42,7 +46,6 @@ async function main() { const languages = analyzeResult?.languages; const styles = analyzeResult?.styles; - if (!pages || pages.length <= 0) { console.log("No pages were extracted from the document."); } else { @@ -51,7 +54,7 @@ async function main() { console.log("- Page", page.pageNumber, `(unit: ${page.unit})`); console.log(` ${page.width}x${page.height}, angle: ${page.angle}`); console.log( - ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words` + ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words`, ); if (page.lines && page.lines.length > 0) { @@ -70,7 +73,7 @@ async function main() { console.log("Languages:"); for (const languageEntry of languages) { console.log( - `- Found language: ${languageEntry.locale} (confidence: ${languageEntry.confidence})` + `- Found language: ${languageEntry.locale} (confidence: ${languageEntry.confidence})`, ); } } @@ -81,7 +84,7 @@ async function main() { console.log("Styles:"); for (const style of styles) { console.log( - `- Handwritten: ${style.isHandwritten ? "yes" : "no"} (confidence=${style.confidence})` + `- Handwritten: ${style.isHandwritten ? "yes" : "no"} (confidence=${style.confidence})`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/README.md b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/README.md similarity index 89% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/README.md rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/README.md index aac9eaa2d9c5..53fd226463e2 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/README.md +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/README.md @@ -1,4 +1,4 @@ -# Azure Document Intelligence Rest Client client library samples for JavaScript (Beta) +# Azure Document Intelligence Rest Client client library samples for JavaScript These sample programs show how to use the JavaScript client libraries for Azure Document Intelligence Rest Client in some common scenarios. @@ -53,20 +53,19 @@ npx dev-tool run vendored cross-env DOCUMENT_INTELLIGENCE_ENDPOINT=" console.log("Operation:", state.result, state.status)); const analyzeResult = (await poller.pollUntilDone()).body.analyzeResult; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildClassifier.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildClassifier.js similarity index 97% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildClassifier.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildClassifier.js index ed481b8012aa..785a74054264 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildClassifier.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildClassifier.js @@ -56,7 +56,7 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const classifier = (await poller.pollUntilDone()).body.result; if (!classifier) { throw new Error("Expected a DocumentClassifierDetailsOutput response."); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildModel.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildModel.js similarity index 95% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildModel.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildModel.js index bbc03c07d574..ca022f664a3e 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/buildModel.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/buildModel.js @@ -43,7 +43,7 @@ async function main() { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse); - const model = (await (await poller).pollUntilDone()).body.result; + const model = (await poller.pollUntilDone()).body.result; if (!model) { throw new Error("Expected a DocumentModelDetailsOutput response."); } @@ -64,7 +64,10 @@ async function main() { // For simplicity, this example will only show top-level field names console.log(" Fields:"); - + if (!schema) { + console.log(" "); + continue; + } for (const [fieldName, fieldSchema] of Object.entries(schema)) { console.log(` - "${fieldName}" (${fieldSchema.type})`); console.log(` ${fieldSchema.description || ""}`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/classifyDocument.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/classifyDocument.js similarity index 96% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/classifyDocument.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/classifyDocument.js index 07f3b4365304..ea437c33e10c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/classifyDocument.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/classifyDocument.js @@ -34,7 +34,7 @@ async function main() { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const analyzeResult = (await poller.pollUntilDone()).body.analyzeResult; if (analyzeResult?.documents === undefined || analyzeResult.documents.length === 0) { diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/composeModel.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/composeModel.js similarity index 78% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/composeModel.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/composeModel.js index 59f97ac3dd1d..1f944304d8f0 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/composeModel.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/composeModel.js @@ -43,29 +43,25 @@ async function main() { const random = Date.now().toString(); const modelIds = await Promise.all( - Object.entries(purchaseOrderSasUrls) - .map(async ([kind, sasUrl]) => { - const modelId = kind + "ComponentModel" + random.substring(random.length - 6); - const initialResponse = await client.path("/documentModels:build").post({ - body: { - buildMode: "template", - modelId: modelId, - azureBlobSource: { - containerUrl: sasUrl, - }, + Object.entries(purchaseOrderSasUrls).map(async ([kind, sasUrl]) => { + const modelId = kind + "ComponentModel" + random.substring(random.length - 6); + const initialResponse = await client.path("/documentModels:build").post({ + body: { + buildMode: "template", + modelId: modelId, + azureBlobSource: { + containerUrl: sasUrl, }, - }); - if (isUnexpected(initialResponse)) { - throw initialResponse.body.error; - } - const poller = await getLongRunningPoller(client, initialResponse); - const model = (await poller.pollUntilDone()).body.result; - - return model; - }) - .map(async (model) => { - return { modelId: (await model).modelId }; - }), + }, + }); + if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; + } + const poller = getLongRunningPoller(client, initialResponse); + const { docTypes } = (await poller.pollUntilDone()).body.result; + + return docTypes; + }), ); // Finally, create the composed model. @@ -74,17 +70,18 @@ async function main() { const initialResponse = await client.path("/documentModels:compose").post({ body: { + modelId: composedModelId, description: "A composed model that classifies purchase order documents and extracts data from them.", - componentModels: modelIds, - modelId: composedModelId, + classifierId: "classifierId", // Add the appropriate classifier ID here + docTypes: { model1: modelIds[0].modelId, model2: modelIds[1].modelId }, }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const composedModel = (await poller.pollUntilDone()).body.result; @@ -104,6 +101,10 @@ async function main() { // For simplicity, this example will only show top-level field names console.log(" Fields:"); + if (!schema) { + console.log(" "); + continue; + } for (const [fieldName, fieldSchema] of Object.entries(schema)) { console.log(` - "${fieldName}" (${fieldSchema.type})`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/copyModel.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/copyModel.js similarity index 97% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/copyModel.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/copyModel.js index e729fa10de76..b53a0b337781 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/copyModel.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/copyModel.js @@ -51,7 +51,7 @@ async function main() { throw copyInitResponse.body.error; } const copyPoller = getLongRunningPoller(sourceClient, copyInitResponse); - const model = (await (await copyPoller).pollUntilDone()).body.result; + const model = (await copyPoller.pollUntilDone()).body.result; console.log("Model ID:", model.modelId); console.log("Description:", model.description); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getClassifier.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getClassifier.js similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getClassifier.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getClassifier.js diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getInfo.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getInfo.js similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getInfo.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getInfo.js diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getModel.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getModel.js similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/getModel.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/getModel.js diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/listModels.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/listModels.js similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/listModels.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/listModels.js diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/package.json b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/package.json similarity index 77% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/package.json rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/package.json index c89c769c0df8..14c233086d7f 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/package.json +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/package.json @@ -1,8 +1,8 @@ { - "name": "@azure-samples/ai-document-intelligence-js-beta", + "name": "@azure-samples/ai-document-intelligence-js", "private": true, "version": "1.0.0", - "description": "Azure Document Intelligence Rest Client client library samples for JavaScript (Beta)", + "description": "Azure Document Intelligence Rest Client client library samples for JavaScript", "engines": { "node": ">=18.0.0" }, @@ -15,9 +15,7 @@ "node", "azure", "cloud", - "typescript", - "browser", - "isomorphic" + "typescript" ], "author": "Microsoft Corporation", "license": "MIT", @@ -26,7 +24,7 @@ }, "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest", "dependencies": { - "@azure-rest/ai-document-intelligence": "next", + "@azure-rest/ai-document-intelligence": "latest", "dotenv": "latest" } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/readDocument.js b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/readDocument.js similarity index 97% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/readDocument.js rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/readDocument.js index 5b300c136e3b..4a6cf9b000c7 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/readDocument.js +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/readDocument.js @@ -32,7 +32,7 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const analyzeResult = (await poller.pollUntilDone()).body.analyzeResult; // The "prebuilt-read" model (`beginReadDocument` method) only extracts information about the textual content of the diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/sample.env b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/sample.env similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/javascript/sample.env rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/javascript/sample.env diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/README.md b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/README.md similarity index 88% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/README.md rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/README.md index a1204d02ebde..96788bbd719e 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/README.md +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/README.md @@ -1,4 +1,4 @@ -# Azure Document Intelligence Rest Client client library samples for TypeScript (Beta) +# Azure Document Intelligence Rest Client client library samples for TypeScript These sample programs show how to use the TypeScript client libraries for Azure Document Intelligence Rest Client in some common scenarios. @@ -70,26 +70,25 @@ npx dev-tool run vendored cross-env DOCUMENT_INTELLIGENCE_ENDPOINT="=18.0.0" }, @@ -19,9 +19,7 @@ "node", "azure", "cloud", - "typescript", - "browser", - "isomorphic" + "typescript" ], "author": "Microsoft Corporation", "license": "MIT", @@ -30,7 +28,7 @@ }, "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/documentintelligence/ai-document-intelligence-rest", "dependencies": { - "@azure-rest/ai-document-intelligence": "next", + "@azure-rest/ai-document-intelligence": "latest", "dotenv": "latest" }, "devDependencies": { diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/sample.env b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/sample.env similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/sample.env rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/sample.env diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeDocumentByModelId.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeDocumentByModelId.ts similarity index 57% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeDocumentByModelId.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeDocumentByModelId.ts index ac70505c598a..412f8b4cd4ec 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeDocumentByModelId.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeDocumentByModelId.ts @@ -8,7 +8,11 @@ * @summary analyze a document using a model by ID */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -16,25 +20,24 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) - const modelId = process.env.DOCUMENT_INTELLIGENCE_CUSTOM_MODEL_ID || "";// "prebuilt-layout"; - - const initialResponse = await client - .path("/documentModels/{modelId}:analyze", modelId) - .post({ - contentType: "application/json", - body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - }, - queryParameters: { locale: "en-IN" }, - }); + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); + const modelId = process.env.DOCUMENT_INTELLIGENCE_CUSTOM_MODEL_ID || ""; // "prebuilt-layout"; + + const initialResponse = await client.path("/documentModels/{modelId}:analyze", modelId).post({ + contentType: "application/json", + body: { + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, + queryParameters: { locale: "en-IN" }, + }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -46,7 +49,7 @@ async function main() { console.log( "Extracted document:", document.docType, - `(confidence: ${document.confidence || ""})` + `(confidence: ${document.confidence || ""})`, ); console.log("Fields:", document.fields); } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeIdentityDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeIdentityDocument.ts similarity index 86% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeIdentityDocument.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeIdentityDocument.ts index 02c576dd08aa..ab0639a10fb3 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeIdentityDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeIdentityDocument.ts @@ -13,7 +13,11 @@ * @summary extract data from an identity document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-idDocument") @@ -37,10 +42,9 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -53,10 +57,10 @@ async function main() { if (document.docType === "idDocument.driverLicense") { // For the sake of the example, we'll only show a few of the fields that are produced. console.log("Extracted a Driver License:"); - console.log(document.fields) + console.log(document.fields); } else if (document.docType === "idDocument.passport") { console.log("Extracted a Passport:"); - console.log(document.fields) + console.log(document.fields); } else { // The only reason this would happen is if the client library's schema for the prebuilt identity document model is // out of date, and a new document type has been introduced. diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeInvoice.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeInvoice.ts similarity index 76% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeInvoice.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeInvoice.ts index 314b3777e4c3..7e7fd88764ff 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeInvoice.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeInvoice.ts @@ -12,16 +12,20 @@ * @summary extract data from an invoice document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { - const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-invoice") @@ -29,16 +33,16 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to an invoice image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/sample_invoice.jpg", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/sample_invoice.jpg", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -47,7 +51,6 @@ async function main() { throw new Error("Expected at least one document in the result."); } - // Use of PrebuiltModels.Receipt above (rather than the raw model ID), adds strong typing of the model's output if (document) { console.log(document.fields); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceipt.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceipt.ts similarity index 75% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceipt.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceipt.ts index 41cb9a422796..a4e6d2b9ac37 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceipt.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceipt.ts @@ -12,7 +12,11 @@ * @summary extract data from a receipt document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -20,7 +24,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-receipt") @@ -28,23 +33,21 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to a receipt image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const document = documents && documents[0]; - - // Use of PrebuiltModels.Receipt above (rather than the raw model ID), as it adds strong typing of the model's output if (document) { console.log(document.fields); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceiptByModelId.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceiptByModelId.ts similarity index 78% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceiptByModelId.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceiptByModelId.ts index c8fc574766e9..ec88ecb37416 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeReceiptByModelId.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeReceiptByModelId.ts @@ -14,7 +14,11 @@ * @summary use the "prebuilt-receipt" model ID to extract data from a receipt document (weakly-typed) */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -22,7 +26,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-receipt") @@ -30,18 +35,18 @@ async function main() { contentType: "application/json", body: { // The Document Intelligence service will access the following URL to a receipt image and extract data from it - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png", + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); poller.onProgress((state) => console.log("Operation:", state.result, state.status)); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeW2TaxForm.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeW2TaxForm.ts similarity index 82% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeW2TaxForm.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeW2TaxForm.ts index c2d1e7f65e47..e41b07dda043 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/analyzeW2TaxForm.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/analyzeW2TaxForm.ts @@ -12,7 +12,11 @@ * @summary extract data from a United States W2 tax document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import fs from "fs"; import path from "path"; @@ -22,7 +26,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const filePath = fs.readFileSync(path.join(".", "assets", "w2", "w2-single.png")); @@ -41,10 +46,9 @@ async function main() { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const document = documents?.[0]; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildClassifier.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildClassifier.ts similarity index 87% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildClassifier.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildClassifier.ts index 9358f1110f00..bd588fe7a180 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildClassifier.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildClassifier.ts @@ -13,7 +13,11 @@ * @summary build a classifier from a training data set */ -import DocumentIntelligence, { DocumentClassifierBuildOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentClassifierBuildOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const random = Date.now().toString(); const modelId = @@ -49,21 +54,20 @@ async function main() { }, }, }, - } + }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const classifier = ( - (await (poller).pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput ).result; if (!classifier) { throw new Error("Expected a DocumentClassifierDetailsOutput response."); } - console.log("Classifier ID:", classifier.classifierId); console.log("Description:", classifier.description); console.log("Created:", classifier.createdDateTime); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildModel.ts similarity index 85% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildModel.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildModel.ts index a50eaa0e4a3e..e33c05a9e8c3 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/buildModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/buildModel.ts @@ -13,7 +13,11 @@ * @summary build a model with a single document type from a training data set */ -import DocumentIntelligence, { DocumentModelBuildOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelBuildOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -21,7 +25,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const random = Date.now().toString(); const modelId = (process.env.CUSTOM_MODEL_ID || "") + random.substring(random.length - 6); @@ -33,7 +38,7 @@ async function main() { buildMode: "template", modelId, azureBlobSource: { - containerUrl: trainingDataSasUrl + containerUrl: trainingDataSasUrl, }, }, }); @@ -42,9 +47,8 @@ async function main() { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse); - const model = ( - (await (await poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput - ).result; + const model = ((await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput) + .result; if (!model) { throw new Error("Expected a DocumentModelDetailsOutput response."); } @@ -58,14 +62,17 @@ async function main() { console.log("Document Types:"); for (const [docType, { description, fieldSchema: schema }] of Object.entries( - model.docTypes || {} + model.docTypes || {}, )) { console.log(`- Name: "${docType}"`); console.log(` Description: "${description}"`); // For simplicity, this example will only show top-level field names console.log(" Fields:"); - + if (!schema) { + console.log(" "); + continue; + } for (const [fieldName, fieldSchema] of Object.entries(schema)) { console.log(` - "${fieldName}" (${fieldSchema.type})`); console.log(` ${fieldSchema.description || ""}`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/classifyDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/classifyDocument.ts similarity index 80% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/classifyDocument.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/classifyDocument.ts index ad6ba315f0e3..74da4718ec41 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/classifyDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/classifyDocument.ts @@ -7,7 +7,11 @@ * @summary use a custom classifier to classify a document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -15,7 +19,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const documentUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/Invoice_1.pdf"; @@ -33,10 +38,9 @@ async function main() { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; if (analyzeResult?.documents === undefined || analyzeResult.documents.length === 0) { throw new Error("Failed to extract any documents."); @@ -44,7 +48,7 @@ async function main() { for (const document of analyzeResult.documents) { console.log( - `Extracted a document with type '${document.docType}' on page ${document.boundingRegions?.[0].pageNumber} (confidence: ${document.confidence})` + `Extracted a document with type '${document.docType}' on page ${document.boundingRegions?.[0].pageNumber} (confidence: ${document.confidence})`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/composeModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/composeModel.ts similarity index 67% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/composeModel.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/composeModel.ts index 5e1044f9cf49..65670b65b62c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/composeModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/composeModel.ts @@ -11,7 +11,12 @@ * @summary create a composed model from several individual labeled models */ -import DocumentIntelligence, { DocumentModelBuildOperationDetailsOutput, DocumentModelComposeOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelBuildOperationDetailsOutput, + DocumentModelComposeOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -19,7 +24,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // This object will hold the SAS-encoded URLs to containers that hold // different types of purchase order documents and their labels. @@ -42,29 +48,27 @@ async function main() { const random = Date.now().toString(); const modelIds = await Promise.all( - Object.entries(purchaseOrderSasUrls) - .map(async ([kind, sasUrl]) => { - const modelId = kind + "ComponentModel" + random.substring(random.length - 6); - const initialResponse = await client.path("/documentModels:build").post({ - body: { - buildMode: "template", - modelId: modelId, - azureBlobSource: { - containerUrl: sasUrl, - }, + Object.entries(purchaseOrderSasUrls).map(async ([kind, sasUrl]) => { + const modelId = kind + "ComponentModel" + random.substring(random.length - 6); + const initialResponse = await client.path("/documentModels:build").post({ + body: { + buildMode: "template", + modelId: modelId, + azureBlobSource: { + containerUrl: sasUrl, }, - }); - if (isUnexpected(initialResponse)) { - throw initialResponse.body.error; - } - const poller = await getLongRunningPoller(client, initialResponse); - const model = ( - (await (poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput - ).result!; - - return model; - }) - .map(async (model) => { return { modelId: (await model).modelId } }) + }, + }); + if (isUnexpected(initialResponse)) { + throw initialResponse.body.error; + } + const poller = getLongRunningPoller(client, initialResponse); + const { docTypes } = ( + (await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput + ).result!; + + return docTypes; + }), ); // Finally, create the composed model. @@ -73,23 +77,23 @@ async function main() { const initialResponse = await client.path("/documentModels:compose").post({ body: { - description: "A composed model that classifies purchase order documents and extracts data from them.", - componentModels: modelIds, modelId: composedModelId, - + description: + "A composed model that classifies purchase order documents and extracts data from them.", + classifierId: "classifierId", // Add the appropriate classifier ID here + docTypes: { model1: modelIds[0]!.modelId, model2: modelIds[1]!.modelId }, }, }); if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); + const poller = getLongRunningPoller(client, initialResponse); const composedModel = ( - (await (poller).pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput ).result!; - console.log("Model ID:", composedModel.modelId); console.log("Description:", composedModel.description); console.log("Created:", composedModel.createdDateTime); @@ -99,13 +103,17 @@ async function main() { console.log("Document Types:"); for (const [docType, { description, fieldSchema: schema }] of Object.entries( - composedModel.docTypes || {} + composedModel.docTypes || {}, )) { console.log(`- Name: "${docType}"`); console.log(` Description: "${description}"`); // For simplicity, this example will only show top-level field names console.log(" Fields:"); + if (!schema) { + console.log(" "); + continue; + } for (const [fieldName, fieldSchema] of Object.entries(schema)) { console.log(` - "${fieldName}" (${fieldSchema.type})`); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/copyModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/copyModel.ts similarity index 83% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/copyModel.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/copyModel.ts index 2da44e98c499..770ca9369fc1 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/copyModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/copyModel.ts @@ -8,13 +8,16 @@ * @summary copy a model from one resource to another */ -import DocumentIntelligence, { DocumentModelCopyToOperationDetailsOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + DocumentModelCopyToOperationDetailsOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { - const random = Date.now().toString(); const destinationModelId = (process.env.CUSTOM_MODEL_ID || "") + random.substring(random.length - 6); @@ -23,7 +26,8 @@ async function main() { // const destinationClient = new DocumentModelAdministrationClient(endpoint, credential); const destinationClient = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // const authorization = await destinationClient.getCopyAuthorization(destinationModelId); const targetAuth = await destinationClient.path("/documentModels:authorizeCopy").post({ body: { @@ -37,9 +41,9 @@ async function main() { const sourceModelId = process.env.COPY_SOURCE_MODEL_ID || ""; // Then, the source resource can initiate the copy operation. - const sourceClient = DocumentIntelligence( - sourceEndpoint, - { key: process.env.DOCUMENT_INTELLIGENCE_SOURCE_API_KEY || "" }) + const sourceClient = DocumentIntelligence(sourceEndpoint, { + key: process.env.DOCUMENT_INTELLIGENCE_SOURCE_API_KEY || "", + }); const copyInitResponse = await sourceClient .path("/documentModels/{modelId}:copyTo", sourceModelId) @@ -52,7 +56,7 @@ async function main() { } const copyPoller = getLongRunningPoller(sourceClient, copyInitResponse); const model = ( - (await (await copyPoller).pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput + (await copyPoller.pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput ).result!; console.log("Model ID:", model.modelId); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/extractLayout.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/extractLayout.ts similarity index 80% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/extractLayout.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/extractLayout.ts index ea4cb0a9a5d5..e6db2580ca7f 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/extractLayout.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/extractLayout.ts @@ -9,8 +9,11 @@ * @summary use the prebuilt layout model to extract basic document elements only */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; - +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -18,15 +21,17 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-layout") .post({ contentType: "application/json", body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", - } + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", + }, }); if (isUnexpected(initialResponse)) { @@ -34,9 +39,8 @@ async function main() { } const poller = getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -49,7 +53,7 @@ async function main() { console.log("- Page", page.pageNumber, `(unit: ${page.unit})`); console.log(` ${page.width}x${page.height}, angle: ${page.angle}`); console.log( - ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words` + ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words`, ); if (page.lines && page.lines.length > 0) { @@ -68,7 +72,7 @@ async function main() { console.log("Tables:"); for (const table of tables) { console.log( - `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)` + `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getClassifier.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getClassifier.ts similarity index 98% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getClassifier.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getClassifier.ts index 1a6352dba334..485c036f598c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getClassifier.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getClassifier.ts @@ -16,7 +16,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const classifierId = process.env.CUSTOM_CLASSIFIER_ID ?? ""; const classifier = await client.path("/documentClassifiers/{classifierId}", classifierId).get(); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getInfo.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getInfo.ts similarity index 94% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getInfo.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getInfo.ts index b5644db43610..0bb24c9015dc 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getInfo.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getInfo.ts @@ -16,13 +16,14 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const info = await client.path("/info").get(); if (isUnexpected(info)) { throw info.body.error; } console.log( - `Custom document models: ${info.body.customDocumentModels.count} of ${info.body.customDocumentModels.limit}` + `Custom document models: ${info.body.customDocumentModels.count} of ${info.body.customDocumentModels.limit}`, ); } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getModel.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getModel.ts similarity index 99% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getModel.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getModel.ts index 1ca43511e8c0..83ee41f56905 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/getModel.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/getModel.ts @@ -16,7 +16,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); // The model ID to query. This can be any model ID, not just a custom model, so for example // the following sample uses `"prebuilt-idDocument"`, but you can change it to any model ID diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/listModels.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/listModels.ts similarity index 92% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/listModels.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/listModels.ts index eb081a1ce61a..da0439c2078c 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/listModels.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/listModels.ts @@ -15,8 +15,8 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) - + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const response = await client.path("/documentModels").get(); if (isUnexpected(response)) { @@ -29,7 +29,7 @@ async function main() { console.log(" Description: ", model.description || ""); // The model summary does not include `docTypes`, so we must additionally call `getModel` to retrieve them - const detailedModel = (await client.path("/documentModels/{modelId}", model.modelId).get()); + const detailedModel = await client.path("/documentModels/{modelId}", model.modelId).get(); if (isUnexpected(detailedModel)) { throw detailedModel.body.error; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/readDocument.ts b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/readDocument.ts similarity index 80% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/readDocument.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/readDocument.ts index 440c4e16040c..165fe439f147 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/src/readDocument.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/src/readDocument.ts @@ -7,7 +7,11 @@ * @summary use the prebuilt "read" model to extract information about the text content of a document */ -import DocumentIntelligence, { AnalyzeResultOperationOutput, getLongRunningPoller, isUnexpected } from "@azure-rest/ai-document-intelligence"; +import DocumentIntelligence, { + AnalyzeResultOperationOutput, + getLongRunningPoller, + isUnexpected, +} from "@azure-rest/ai-document-intelligence"; import * as dotenv from "dotenv"; dotenv.config(); @@ -15,14 +19,16 @@ dotenv.config(); async function main() { const client = DocumentIntelligence( process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"] || "", - { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }) + { key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"] || "" }, + ); const initialResponse = await client .path("/documentModels/{modelId}:analyze", "prebuilt-read") .post({ contentType: "application/json", body: { - urlSource: "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", + urlSource: + "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf", }, queryParameters: { features: ["barcodes"] }, }); @@ -30,11 +36,9 @@ async function main() { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; - + const poller = getLongRunningPoller(client, initialResponse); + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeResultOperationOutput) + .analyzeResult; // The "prebuilt-read" model (`beginReadDocument` method) only extracts information about the textual content of the // document, such as page text elements and information about the language of the text. @@ -42,7 +46,6 @@ async function main() { const languages = analyzeResult?.languages; const styles = analyzeResult?.styles; - if (!pages || pages.length <= 0) { console.log("No pages were extracted from the document."); } else { @@ -51,7 +54,7 @@ async function main() { console.log("- Page", page.pageNumber, `(unit: ${page.unit})`); console.log(` ${page.width}x${page.height}, angle: ${page.angle}`); console.log( - ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words` + ` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words`, ); if (page.lines && page.lines.length > 0) { @@ -70,7 +73,7 @@ async function main() { console.log("Languages:"); for (const languageEntry of languages) { console.log( - `- Found language: ${languageEntry.locale} (confidence: ${languageEntry.confidence})` + `- Found language: ${languageEntry.locale} (confidence: ${languageEntry.confidence})`, ); } } @@ -81,7 +84,7 @@ async function main() { console.log("Styles:"); for (const style of styles) { console.log( - `- Handwritten: ${style.isHandwritten ? "yes" : "no"} (confidence=${style.confidence})` + `- Handwritten: ${style.isHandwritten ? "yes" : "no"} (confidence=${style.confidence})`, ); } } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/tsconfig.json b/sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/tsconfig.json similarity index 100% rename from sdk/documentintelligence/ai-document-intelligence-rest/samples/v1-beta/typescript/tsconfig.json rename to sdk/documentintelligence/ai-document-intelligence-rest/samples/v1/typescript/tsconfig.json diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/clientDefinitions.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/clientDefinitions.ts index c336ff164be1..779b9ab23484 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/clientDefinitions.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/clientDefinitions.ts @@ -9,14 +9,17 @@ import type { GetDocumentClassifierCopyToOperationParameters, GetDocumentClassifierBuildOperationParameters, GetOperationParameters, - GetResourceInfoParameters, + GetResourceDetailsParameters, GetAnalyzeResultParameters, + DeleteAnalyzeResultParameters, GetAnalyzeResultPdfParameters, GetAnalyzeResultFigureParameters, AnalyzeDocumentFromStreamParameters, AnalyzeDocumentParameters, GetAnalyzeBatchResultParameters, + DeleteAnalyzeBatchResultParameters, AnalyzeBatchDocumentsParameters, + ListAnalyzeBatchResultsParameters, GetModelParameters, DeleteModelParameters, BuildModelParameters, @@ -49,10 +52,12 @@ import type { GetDocumentClassifierBuildOperationDefaultResponse, GetOperation200Response, GetOperationDefaultResponse, - GetResourceInfo200Response, - GetResourceInfoDefaultResponse, + GetResourceDetails200Response, + GetResourceDetailsDefaultResponse, GetAnalyzeResult200Response, GetAnalyzeResultDefaultResponse, + DeleteAnalyzeResult204Response, + DeleteAnalyzeResultDefaultResponse, GetAnalyzeResultPdf200Response, GetAnalyzeResultPdfDefaultResponse, GetAnalyzeResultFigure200Response, @@ -63,8 +68,12 @@ import type { AnalyzeDocumentDefaultResponse, GetAnalyzeBatchResult200Response, GetAnalyzeBatchResultDefaultResponse, + DeleteAnalyzeBatchResult204Response, + DeleteAnalyzeBatchResultDefaultResponse, AnalyzeBatchDocuments202Response, AnalyzeBatchDocumentsDefaultResponse, + ListAnalyzeBatchResults200Response, + ListAnalyzeBatchResultsDefaultResponse, GetModel200Response, GetModelDefaultResponse, DeleteModel204Response, @@ -146,11 +155,11 @@ export interface GetDocumentModelBuildOperation { ): StreamableMethod; } -export interface GetResourceInfo { +export interface GetResourceDetails { /** Return information about the current resource. */ get( - options?: GetResourceInfoParameters, - ): StreamableMethod; + options?: GetResourceDetailsParameters, + ): StreamableMethod; } export interface GetAnalyzeResult { @@ -158,6 +167,10 @@ export interface GetAnalyzeResult { get( options?: GetAnalyzeResultParameters, ): StreamableMethod; + /** Mark the result of document analysis for deletion. */ + delete( + options?: DeleteAnalyzeResultParameters, + ): StreamableMethod; } export interface GetAnalyzeResultPdf { @@ -192,6 +205,12 @@ export interface GetAnalyzeBatchResult { get( options?: GetAnalyzeBatchResultParameters, ): StreamableMethod; + /** Mark the batch document analysis result for deletion. */ + delete( + options?: DeleteAnalyzeBatchResultParameters, + ): StreamableMethod< + DeleteAnalyzeBatchResult204Response | DeleteAnalyzeBatchResultDefaultResponse + >; } export interface AnalyzeBatchDocuments { @@ -201,6 +220,13 @@ export interface AnalyzeBatchDocuments { ): StreamableMethod; } +export interface ListAnalyzeBatchResults { + /** List batch document analysis results. */ + get( + options?: ListAnalyzeBatchResultsParameters, + ): StreamableMethod; +} + export interface GetModel { /** Gets detailed document model information. */ get( @@ -318,8 +344,8 @@ export interface Routes { /** Resource for '/operations/\{operationId\}' has methods for the following verbs: get */ (path: "/operations/{operationId}", operationId: string): GetDocumentModelBuildOperation; /** Resource for '/info' has methods for the following verbs: get */ - (path: "/info"): GetResourceInfo; - /** Resource for '/documentModels/\{modelId\}/analyzeResults/\{resultId\}' has methods for the following verbs: get */ + (path: "/info"): GetResourceDetails; + /** Resource for '/documentModels/\{modelId\}/analyzeResults/\{resultId\}' has methods for the following verbs: get, delete */ ( path: "/documentModels/{modelId}/analyzeResults/{resultId}", modelId: string, @@ -340,7 +366,7 @@ export interface Routes { ): GetAnalyzeResultFigure; /** Resource for '/documentModels/\{modelId\}:analyze' has methods for the following verbs: post */ (path: "/documentModels/{modelId}:analyze", modelId: string): AnalyzeDocumentFromStream; - /** Resource for '/documentModels/\{modelId\}/analyzeBatchResults/\{resultId\}' has methods for the following verbs: get */ + /** Resource for '/documentModels/\{modelId\}/analyzeBatchResults/\{resultId\}' has methods for the following verbs: get, delete */ ( path: "/documentModels/{modelId}/analyzeBatchResults/{resultId}", modelId: string, @@ -348,6 +374,8 @@ export interface Routes { ): GetAnalyzeBatchResult; /** Resource for '/documentModels/\{modelId\}:analyzeBatch' has methods for the following verbs: post */ (path: "/documentModels/{modelId}:analyzeBatch", modelId: string): AnalyzeBatchDocuments; + /** Resource for '/documentModels/\{modelId\}/analyzeBatchResults' has methods for the following verbs: get */ + (path: "/documentModels/{modelId}/analyzeBatchResults", modelId: string): ListAnalyzeBatchResults; /** Resource for '/documentModels/\{modelId\}' has methods for the following verbs: get, delete */ (path: "/documentModels/{modelId}", modelId: string): GetModel; /** Resource for '/documentModels:build' has methods for the following verbs: post */ diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/documentIntelligence.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/documentIntelligence.ts index 53884360f1cd..11e6a7ee0a6f 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/documentIntelligence.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/documentIntelligence.ts @@ -22,11 +22,11 @@ export interface DocumentIntelligenceClientOptions extends ClientOptions { export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - { apiVersion = "2024-07-31-preview", ...options }: DocumentIntelligenceClientOptions = {}, + { apiVersion = "2024-11-30", ...options }: DocumentIntelligenceClientOptions = {}, ): DocumentIntelligenceClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/documentintelligence`; - const userAgentInfo = `azsdk-js-ai-document-intelligence-rest/1.0.0-beta.1`; + const userAgentInfo = `azsdk-js-ai-document-intelligence-rest/1.0.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/isUnexpected.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/isUnexpected.ts index 472c444bfbc9..3cdb23eabe89 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/isUnexpected.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/isUnexpected.ts @@ -16,10 +16,12 @@ import type { GetDocumentClassifierBuildOperationDefaultResponse, GetOperation200Response, GetOperationDefaultResponse, - GetResourceInfo200Response, - GetResourceInfoDefaultResponse, + GetResourceDetails200Response, + GetResourceDetailsDefaultResponse, GetAnalyzeResult200Response, GetAnalyzeResultDefaultResponse, + DeleteAnalyzeResult204Response, + DeleteAnalyzeResultDefaultResponse, GetAnalyzeResultPdf200Response, GetAnalyzeResultPdfDefaultResponse, GetAnalyzeResultFigure200Response, @@ -32,9 +34,13 @@ import type { AnalyzeDocumentDefaultResponse, GetAnalyzeBatchResult200Response, GetAnalyzeBatchResultDefaultResponse, + DeleteAnalyzeBatchResult204Response, + DeleteAnalyzeBatchResultDefaultResponse, AnalyzeBatchDocuments202Response, AnalyzeBatchDocumentsLogicalResponse, AnalyzeBatchDocumentsDefaultResponse, + ListAnalyzeBatchResults200Response, + ListAnalyzeBatchResultsDefaultResponse, GetModel200Response, GetModelDefaultResponse, DeleteModel204Response, @@ -81,13 +87,16 @@ const responseMap: Record = { "GET /operations/{operationId}": ["200"], "GET /info": ["200"], "GET /documentModels/{modelId}/analyzeResults/{resultId}": ["200"], + "DELETE /documentModels/{modelId}/analyzeResults/{resultId}": ["204"], "GET /documentModels/{modelId}/analyzeResults/{resultId}/pdf": ["200"], "GET /documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}": ["200"], "GET /documentModels/{modelId}:analyze": ["200", "202"], "POST /documentModels/{modelId}:analyze": ["202"], "GET /documentModels/{modelId}/analyzeBatchResults/{resultId}": ["200"], + "DELETE /documentModels/{modelId}/analyzeBatchResults/{resultId}": ["204"], "GET /documentModels/{modelId}:analyzeBatch": ["200", "202"], "POST /documentModels/{modelId}:analyzeBatch": ["202"], + "GET /documentModels/{modelId}/analyzeBatchResults": ["200"], "GET /documentModels/{modelId}": ["200"], "DELETE /documentModels/{modelId}": ["204"], "GET /documentModels:build": ["200", "202"], @@ -143,11 +152,14 @@ export function isUnexpected( response: GetOperation200Response | GetOperationDefaultResponse, ): response is GetOperationDefaultResponse; export function isUnexpected( - response: GetResourceInfo200Response | GetResourceInfoDefaultResponse, -): response is GetResourceInfoDefaultResponse; + response: GetResourceDetails200Response | GetResourceDetailsDefaultResponse, +): response is GetResourceDetailsDefaultResponse; export function isUnexpected( response: GetAnalyzeResult200Response | GetAnalyzeResultDefaultResponse, ): response is GetAnalyzeResultDefaultResponse; +export function isUnexpected( + response: DeleteAnalyzeResult204Response | DeleteAnalyzeResultDefaultResponse, +): response is DeleteAnalyzeResultDefaultResponse; export function isUnexpected( response: GetAnalyzeResultPdf200Response | GetAnalyzeResultPdfDefaultResponse, ): response is GetAnalyzeResultPdfDefaultResponse; @@ -169,12 +181,18 @@ export function isUnexpected( export function isUnexpected( response: GetAnalyzeBatchResult200Response | GetAnalyzeBatchResultDefaultResponse, ): response is GetAnalyzeBatchResultDefaultResponse; +export function isUnexpected( + response: DeleteAnalyzeBatchResult204Response | DeleteAnalyzeBatchResultDefaultResponse, +): response is DeleteAnalyzeBatchResultDefaultResponse; export function isUnexpected( response: | AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsLogicalResponse | AnalyzeBatchDocumentsDefaultResponse, ): response is AnalyzeBatchDocumentsDefaultResponse; +export function isUnexpected( + response: ListAnalyzeBatchResults200Response | ListAnalyzeBatchResultsDefaultResponse, +): response is ListAnalyzeBatchResultsDefaultResponse; export function isUnexpected( response: GetModel200Response | GetModelDefaultResponse, ): response is GetModelDefaultResponse; @@ -251,10 +269,12 @@ export function isUnexpected( | GetDocumentClassifierBuildOperationDefaultResponse | GetOperation200Response | GetOperationDefaultResponse - | GetResourceInfo200Response - | GetResourceInfoDefaultResponse + | GetResourceDetails200Response + | GetResourceDetailsDefaultResponse | GetAnalyzeResult200Response | GetAnalyzeResultDefaultResponse + | DeleteAnalyzeResult204Response + | DeleteAnalyzeResultDefaultResponse | GetAnalyzeResultPdf200Response | GetAnalyzeResultPdfDefaultResponse | GetAnalyzeResultFigure200Response @@ -267,9 +287,13 @@ export function isUnexpected( | AnalyzeDocumentDefaultResponse | GetAnalyzeBatchResult200Response | GetAnalyzeBatchResultDefaultResponse + | DeleteAnalyzeBatchResult204Response + | DeleteAnalyzeBatchResultDefaultResponse | AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsLogicalResponse | AnalyzeBatchDocumentsDefaultResponse + | ListAnalyzeBatchResults200Response + | ListAnalyzeBatchResultsDefaultResponse | GetModel200Response | GetModelDefaultResponse | DeleteModel204Response @@ -317,14 +341,17 @@ export function isUnexpected( | GetDocumentClassifierCopyToOperationDefaultResponse | GetDocumentClassifierBuildOperationDefaultResponse | GetOperationDefaultResponse - | GetResourceInfoDefaultResponse + | GetResourceDetailsDefaultResponse | GetAnalyzeResultDefaultResponse + | DeleteAnalyzeResultDefaultResponse | GetAnalyzeResultPdfDefaultResponse | GetAnalyzeResultFigureDefaultResponse | AnalyzeDocumentFromStreamDefaultResponse | AnalyzeDocumentDefaultResponse | GetAnalyzeBatchResultDefaultResponse + | DeleteAnalyzeBatchResultDefaultResponse | AnalyzeBatchDocumentsDefaultResponse + | ListAnalyzeBatchResultsDefaultResponse | GetModelDefaultResponse | DeleteModelDefaultResponse | BuildModelDefaultResponse diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/models.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/models.ts index b089b1b5a545..1f534a9326f7 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/models.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/models.ts @@ -24,7 +24,7 @@ export interface DocumentTypeDetails { /** * Custom document model build mode. * - * Possible values: "template", "neural", "generative" + * Possible values: "template", "neural" */ buildMode?: DocumentBuildMode; /** Description of the document semantic schema using a JSON Schema style syntax. */ @@ -123,7 +123,7 @@ export interface BuildDocumentModelRequest { /** * Custom document model build mode. * - * Possible values: "template", "neural", "generative" + * Possible values: "template", "neural" */ buildMode: DocumentBuildMode; /** @@ -178,7 +178,7 @@ export interface AuthorizeCopyRequest { * Authorization to copy a document model to the specified target resource and * modelId. */ -export interface CopyAuthorization { +export interface ModelCopyAuthorization { /** ID of the target Azure resource where the document model should be copied to. */ targetResourceId: string; /** @@ -265,7 +265,7 @@ export type DocumentAnalysisFeature = string; export type ContentSourceKind = string; /** Alias for StringIndexType */ export type StringIndexType = string; -/** Alias for ContentFormat */ -export type ContentFormat = string; +/** Alias for DocumentContentFormat */ +export type DocumentContentFormat = string; /** Alias for AnalyzeOutputOption */ export type AnalyzeOutputOption = string; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/outputModels.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/outputModels.ts index 8273ae8968f4..11c75abaeade 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/outputModels.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/outputModels.ts @@ -1,18 +1,24 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Paged } from "@azure/core-paging"; +/** Paged collection of DocumentIntelligenceOperationDetails items */ +export interface PagedDocumentIntelligenceOperationDetailsOutput { + /** The DocumentIntelligenceOperationDetails items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} /** Operation info. */ -export interface OperationDetailsOutputParent { +export interface DocumentIntelligenceOperationDetailsOutputParent { /** Operation ID */ operationId: string; /** * Operation status. notStarted, running, completed, or failed * - * Possible values: "notStarted", "running", "failed", "succeeded", "completed", "canceled" + * Possible values: "notStarted", "running", "failed", "succeeded", "canceled", "skipped" */ - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; /** Operation progress (0-100). */ percentCompleted?: number; /** Date and time (UTC) when the operation was created. */ @@ -26,12 +32,12 @@ export interface OperationDetailsOutputParent { /** List of key-value tag attributes associated with the document model. */ tags?: Record; /** Encountered error. */ - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; kind: OperationKindOutput; } /** The error object. */ -export interface ErrorModelOutput { +export interface DocumentIntelligenceErrorOutput { /** One of a server-defined set of error codes. */ code: string; /** A human-readable representation of the error. */ @@ -39,23 +45,24 @@ export interface ErrorModelOutput { /** The target of the error. */ target?: string; /** An array of details about specific errors that led to this reported error. */ - details?: Array; + details?: Array; /** An object containing more specific information than the current object about the error. */ - innererror?: InnerErrorOutput; + innererror?: DocumentIntelligenceInnerErrorOutput; } /** An object containing more specific information about the error. */ -export interface InnerErrorOutput { +export interface DocumentIntelligenceInnerErrorOutput { /** One of a server-defined set of error codes. */ code?: string; /** A human-readable representation of the error. */ message?: string; /** Inner error. */ - innererror?: InnerErrorOutput; + innererror?: DocumentIntelligenceInnerErrorOutput; } /** Get Operation response object. */ -export interface DocumentModelBuildOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelBuildOperationDetailsOutput + extends DocumentIntelligenceOperationDetailsOutputParent { /** Operation result upon success. */ result?: DocumentModelDetailsOutput; /** Type of operation. */ @@ -72,6 +79,8 @@ export interface DocumentModelDetailsOutput { readonly createdDateTime: string; /** Date and time (UTC) when the document model will expire. */ readonly expirationDateTime?: string; + /** Date and time (UTC) when the document model was last modified. */ + readonly modifiedDateTime?: string; /** API version used to create this document model. */ readonly apiVersion?: string; /** List of key-value tag attributes associated with the document model. */ @@ -79,7 +88,7 @@ export interface DocumentModelDetailsOutput { /** * Custom document model build mode. * - * Possible values: "template", "neural", "generative" + * Possible values: "template", "neural" */ readonly buildMode?: DocumentBuildModeOutput; /** @@ -103,7 +112,7 @@ export interface DocumentModelDetailsOutput { /** Supported document types. */ readonly docTypes?: Record; /** List of warnings encountered while building the model. */ - readonly warnings?: Array; + readonly warnings?: Array; /** Number of V100-equivalent GPU hours consumed for model training. */ readonly trainingHours?: number; } @@ -131,7 +140,7 @@ export interface DocumentTypeDetailsOutput { /** * Custom document model build mode. * - * Possible values: "template", "neural", "generative" + * Possible values: "template", "neural" */ buildMode?: DocumentBuildModeOutput; /** Description of the document semantic schema using a JSON Schema style syntax. */ @@ -169,7 +178,7 @@ export interface DocumentFieldSchemaOutput { } /** The error object. */ -export interface WarningOutput { +export interface DocumentIntelligenceWarningOutput { /** One of a server-defined set of warning codes. */ code: string; /** A human-readable representation of the warning. */ @@ -179,7 +188,8 @@ export interface WarningOutput { } /** Get Operation response object. */ -export interface DocumentModelComposeOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelComposeOperationDetailsOutput + extends DocumentIntelligenceOperationDetailsOutputParent { /** Operation result upon success. */ result?: DocumentModelDetailsOutput; /** Type of operation. */ @@ -187,7 +197,8 @@ export interface DocumentModelComposeOperationDetailsOutput extends OperationDet } /** Get Operation response object. */ -export interface DocumentModelCopyToOperationDetailsOutput extends OperationDetailsOutputParent { +export interface DocumentModelCopyToOperationDetailsOutput + extends DocumentIntelligenceOperationDetailsOutputParent { /** Operation result upon success. */ result?: DocumentModelDetailsOutput; /** Type of operation. */ @@ -196,7 +207,7 @@ export interface DocumentModelCopyToOperationDetailsOutput extends OperationDeta /** Get Operation response object. */ export interface DocumentClassifierCopyToOperationDetailsOutput - extends OperationDetailsOutputParent { + extends DocumentIntelligenceOperationDetailsOutputParent { /** Operation result upon success. */ result?: DocumentClassifierDetailsOutput; /** Type of operation. */ @@ -213,6 +224,8 @@ export interface DocumentClassifierDetailsOutput { createdDateTime: string; /** Date and time (UTC) when the document classifier will expire. */ expirationDateTime?: string; + /** Date and time (UTC) when the document model was last modified. */ + readonly modifiedDateTime?: string; /** API version used to create this document classifier. */ apiVersion: string; /** Base classifierId on top of which the classifier was trained. */ @@ -220,7 +233,7 @@ export interface DocumentClassifierDetailsOutput { /** List of document types to classify against. */ docTypes: Record; /** List of warnings encountered while building the classifier. */ - warnings?: Array; + warnings?: Array; } /** Classifier document type info. */ @@ -247,7 +260,7 @@ export interface ClassifierDocumentTypeDetailsOutput { /** Get Operation response object. */ export interface DocumentClassifierBuildOperationDetailsOutput - extends OperationDetailsOutputParent { + extends DocumentIntelligenceOperationDetailsOutputParent { /** Operation result upon success. */ result?: DocumentClassifierDetailsOutput; /** Type of operation. */ @@ -255,13 +268,13 @@ export interface DocumentClassifierBuildOperationDetailsOutput } /** Error response object. */ -export interface ErrorResponseOutput { +export interface DocumentIntelligenceErrorResponseOutput { /** Error info. */ - error: ErrorModelOutput; + error: DocumentIntelligenceErrorOutput; } /** General information regarding the current resource. */ -export interface ResourceDetailsOutput { +export interface DocumentIntelligenceResourceDetailsOutput { /** Details regarding custom document models. */ customDocumentModels: CustomDocumentModelsDetailsOutput; } @@ -275,19 +288,19 @@ export interface CustomDocumentModelsDetailsOutput { } /** Status and result of the analyze operation. */ -export interface AnalyzeResultOperationOutput { +export interface AnalyzeOperationOutput { /** * Operation status. notStarted, running, succeeded, or failed * - * Possible values: "notStarted", "running", "failed", "succeeded", "completed", "canceled" + * Possible values: "notStarted", "running", "failed", "succeeded", "canceled", "skipped" */ - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; /** Date and time (UTC) when the analyze operation was submitted. */ createdDateTime: string; /** Date and time (UTC) when the status was last updated. */ lastUpdatedDateTime: string; /** Encountered error during document analysis. */ - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; /** Document analysis result. */ analyzeResult?: AnalyzeResultOutput; } @@ -309,7 +322,7 @@ export interface AnalyzeResultOutput { * * Possible values: "text", "markdown" */ - contentFormat?: ContentFormatOutput; + contentFormat?: DocumentContentFormatOutput; /** * Concatenate string representation of all textual and visual elements in reading * order. @@ -332,9 +345,9 @@ export interface AnalyzeResultOutput { /** Detected languages. */ languages?: Array; /** Extracted documents. */ - documents?: Array; + documents?: Array; /** List of warnings encountered. */ - warnings?: Array; + warnings?: Array; } /** Content and layout elements extracted from a page from the input. */ @@ -655,13 +668,13 @@ export interface DocumentStyleOutput { * * Possible values: "normal", "italic" */ - fontStyle?: FontStyleOutput; + fontStyle?: DocumentFontStyleOutput; /** * Font weight. * * Possible values: "normal", "bold" */ - fontWeight?: FontWeightOutput; + fontWeight?: DocumentFontWeightOutput; /** Foreground color in #rrggbb hexadecimal format. */ color?: string; /** Background color in #rrggbb hexadecimal format.. */ @@ -689,7 +702,7 @@ export interface DocumentLanguageOutput { } /** An object describing the location and semantic content of a document. */ -export interface DocumentOutput { +export interface AnalyzedDocumentOutput { /** Document type. */ docType: string; /** Bounding regions covering the document. */ @@ -804,13 +817,15 @@ export interface AddressValueOutput { } /** Status and result of the analyze batch operation. */ -export interface AnalyzeBatchResultOperationOutput { +export interface AnalyzeBatchOperationOutput { + /** Analyze batch operation result ID. */ + resultId?: string; /** - * Operation status. notStarted, running, completed, or failed + * Operation status. notStarted, running, succeeded, or failed * - * Possible values: "notStarted", "running", "failed", "succeeded", "completed", "canceled" + * Possible values: "notStarted", "running", "failed", "succeeded", "canceled", "skipped" */ - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; /** Date and time (UTC) when the operation was submitted. */ createdDateTime: string; /** Date and time (UTC) when the status was last updated. */ @@ -818,7 +833,7 @@ export interface AnalyzeBatchResultOperationOutput { /** Operation progress (0-100). */ percentCompleted?: number; /** Encountered error during batch document analysis. */ - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; /** Batch document analysis result. */ result?: AnalyzeBatchResultOutput; } @@ -832,7 +847,7 @@ export interface AnalyzeBatchResultOutput { /** Number of documents that completed with status skipped. */ skippedCount: number; /** Operation detail for each document in the batch. */ - details: Array; + details?: Array; } /** Operation detail for a document in a batch analysis. */ @@ -840,22 +855,30 @@ export interface AnalyzeBatchOperationDetailOutput { /** * Analyze status. succeeded, failed, or skipped * - * Possible values: "notStarted", "running", "failed", "succeeded", "completed", "canceled" + * Possible values: "notStarted", "running", "failed", "succeeded", "canceled", "skipped" */ - status: OperationStatusOutput; + status: DocumentIntelligenceOperationStatusOutput; /** URL of the source document. */ sourceUrl: string; /** URL of the analyze result JSON. */ resultUrl?: string; /** Encountered error. */ - error?: ErrorModelOutput; + error?: DocumentIntelligenceErrorOutput; +} + +/** Paged collection of AnalyzeBatchOperation items */ +export interface PagedAnalyzeBatchOperationOutput { + /** The AnalyzeBatchOperation items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; } /** * Authorization to copy a document model to the specified target resource and * modelId. */ -export interface CopyAuthorizationOutput { +export interface ModelCopyAuthorizationOutput { /** ID of the target Azure resource where the document model should be copied to. */ targetResourceId: string; /** @@ -873,6 +896,22 @@ export interface CopyAuthorizationOutput { expirationDateTime: string; } +/** Paged collection of DocumentModelDetails items */ +export interface PagedDocumentModelDetailsOutput { + /** The DocumentModelDetails items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of DocumentClassifierDetails items */ +export interface PagedDocumentClassifierDetailsOutput { + /** The DocumentClassifierDetails items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** * Authorization to copy a document classifier to the specified target resource and * classifierId. @@ -896,17 +935,15 @@ export interface ClassifierCopyAuthorizationOutput { } /** Operation info. */ -export type OperationDetailsOutput = - | OperationDetailsOutputParent +export type DocumentIntelligenceOperationDetailsOutput = + | DocumentIntelligenceOperationDetailsOutputParent | DocumentModelBuildOperationDetailsOutput | DocumentModelComposeOperationDetailsOutput | DocumentModelCopyToOperationDetailsOutput | DocumentClassifierCopyToOperationDetailsOutput | DocumentClassifierBuildOperationDetailsOutput; -/** Paged collection of OperationDetails items */ -export type PagedOperationDetailsOutput = Paged; -/** Alias for OperationStatusOutput */ -export type OperationStatusOutput = string; +/** Alias for DocumentIntelligenceOperationStatusOutput */ +export type DocumentIntelligenceOperationStatusOutput = string; /** Alias for OperationKindOutput */ export type OperationKindOutput = string; /** Alias for DocumentBuildModeOutput */ @@ -921,8 +958,8 @@ export type DocumentAnalysisFeatureOutput = string; export type ContentSourceKindOutput = string; /** Alias for StringIndexTypeOutput */ export type StringIndexTypeOutput = string; -/** Alias for ContentFormatOutput */ -export type ContentFormatOutput = string; +/** Alias for DocumentContentFormatOutput */ +export type DocumentContentFormatOutput = string; /** Alias for LengthUnitOutput */ export type LengthUnitOutput = string; /** Alias for DocumentSelectionMarkStateOutput */ @@ -935,13 +972,9 @@ export type DocumentFormulaKindOutput = string; export type ParagraphRoleOutput = string; /** Alias for DocumentTableCellKindOutput */ export type DocumentTableCellKindOutput = string; -/** Alias for FontStyleOutput */ -export type FontStyleOutput = string; -/** Alias for FontWeightOutput */ -export type FontWeightOutput = string; +/** Alias for DocumentFontStyleOutput */ +export type DocumentFontStyleOutput = string; +/** Alias for DocumentFontWeightOutput */ +export type DocumentFontWeightOutput = string; /** Alias for DocumentSignatureTypeOutput */ export type DocumentSignatureTypeOutput = string; -/** Paged collection of DocumentModelDetails items */ -export type PagedDocumentModelDetailsOutput = Paged; -/** Paged collection of DocumentClassifierDetails items */ -export type PagedDocumentClassifierDetailsOutput = Paged; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/paginateHelper.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/paginateHelper.ts index 5d541b4e406d..9ea946d9d6c5 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/paginateHelper.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/paginateHelper.ts @@ -1,11 +1,148 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { PagedAsyncIterableIterator, PagedResult } from "@azure/core-paging"; -import { getPagedAsyncIterator } from "@azure/core-paging"; import type { Client, PathUncheckedResponse } from "@azure-rest/core-client"; import { createRestError } from "@azure-rest/core-client"; +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, + TLink = string, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + (((settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken as unknown as TLink | undefined, + }); + }) as unknown as (settings?: TPageSettings) => AsyncIterableIterator), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: TLink; + } = {}, +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage(pageLink ?? pagedResult.firstPageLink); + if (!response) { + return; + } + yield response.page; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield response.page; + } +} + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +} + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings?: TPageSettings) => AsyncIterableIterator; +} + +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult { + /** + * Link to the first page of results. + */ + firstPageLink: TLink; + /** + * A method that returns a page of results. + */ + getPage: (pageLink: TLink) => Promise<{ page: TPage; nextPageLink?: TLink } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: (settings?: TPageSettings) => AsyncIterableIterator; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => unknown[]; +} + /** * Helper type to extract the type of an array */ @@ -14,10 +151,7 @@ export type GetArrayType = T extends Array ? TData : never; /** * The type of a custom function that defines how to get a page and a link to the next one if any. */ -export type GetPage = ( - pageLink: string, - maxPageSize?: number, -) => Promise<{ +export type GetPage = (pageLink: string) => Promise<{ page: TPage; nextPageLink?: string; }>; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/parameters.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/parameters.ts index cd76fb6850be..49dcba7f2e91 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/parameters.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/parameters.ts @@ -6,14 +6,14 @@ import type { RequestParameters } from "@azure-rest/core-client"; import type { StringIndexType, DocumentAnalysisFeature, - ContentFormat, + DocumentContentFormat, AnalyzeOutputOption, AnalyzeDocumentRequest, AnalyzeBatchDocumentsRequest, BuildDocumentModelRequest, ComposeDocumentModelRequest, AuthorizeCopyRequest, - CopyAuthorization, + ModelCopyAuthorization, BuildDocumentClassifierRequest, SplitMode, ClassifyDocumentRequest, @@ -102,10 +102,11 @@ export interface GetOperationHeaderParam { } export type GetOperationParameters = GetOperationHeaderParam & RequestParameters; -export type GetResourceInfoParameters = RequestParameters; +export type GetResourceDetailsParameters = RequestParameters; export type GetAnalyzeResultParameters = RequestParameters; export type GetAnalyzeResultPdfParameters = RequestParameters; export type GetAnalyzeResultFigureParameters = RequestParameters; +export type DeleteAnalyzeResultParameters = RequestParameters; export interface AnalyzeDocumentFromStreamBodyParam { /** @@ -113,11 +114,46 @@ export interface AnalyzeDocumentFromStreamBodyParam { * * Value may contain any sequence of octets */ - body: string | Uint8Array | ReadableStream | NodeJS.ReadableStream; + body: + | string + | Uint8Array + // eslint-disable-next-line n/no-unsupported-features/node-builtins + | ReadableStream + | NodeJS.ReadableStream; +} + +/** This is the wrapper object for the parameter `features` with explode set to false and style set to form. */ +export interface AnalyzeDocumentFromStreamFeaturesQueryParam { + /** Value of the parameter */ + value: DocumentAnalysisFeature[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `queryFields` with explode set to false and style set to form. */ +export interface AnalyzeDocumentFromStreamQueryFieldsQueryParam { + /** Value of the parameter */ + value: string[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `output` with explode set to false and style set to form. */ +export interface AnalyzeDocumentFromStreamOutputQueryParam { + /** Value of the parameter */ + value: AnalyzeOutputOption[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; } export interface AnalyzeDocumentFromStreamQueryParamProperties { - /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ + /** 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; /** * Locale hint for text recognition and document analysis. Value may contain only @@ -131,17 +167,17 @@ export interface AnalyzeDocumentFromStreamQueryParamProperties { */ stringIndexType?: StringIndexType; /** List of optional analysis features. */ - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeDocumentFromStreamFeaturesQueryParam; /** List of additional fields to extract. Ex. "NumberOfGuests,StoreNumber" */ - queryFields?: string[]; + queryFields?: string[] | AnalyzeDocumentFromStreamQueryFieldsQueryParam; /** * Format of the analyze result top-level content. * * Possible values: "text", "markdown" */ - outputContentFormat?: ContentFormat; + outputContentFormat?: DocumentContentFormat; /** Additional outputs to generate during analysis. */ - output?: AnalyzeOutputOption[]; + output?: AnalyzeOutputOption[] | AnalyzeDocumentFromStreamOutputQueryParam; } export interface AnalyzeDocumentFromStreamQueryParam { @@ -171,11 +207,41 @@ export type AnalyzeDocumentFromStreamParameters = AnalyzeDocumentFromStreamQuery export interface AnalyzeDocumentBodyParam { /** Analyze request parameters. */ - body?: AnalyzeDocumentRequest; + body: AnalyzeDocumentRequest; +} + +/** This is the wrapper object for the parameter `features` with explode set to false and style set to form. */ +export interface AnalyzeDocumentFeaturesQueryParam { + /** Value of the parameter */ + value: DocumentAnalysisFeature[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `queryFields` with explode set to false and style set to form. */ +export interface AnalyzeDocumentQueryFieldsQueryParam { + /** Value of the parameter */ + value: string[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `output` with explode set to false and style set to form. */ +export interface AnalyzeDocumentOutputQueryParam { + /** Value of the parameter */ + value: AnalyzeOutputOption[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; } export interface AnalyzeDocumentQueryParamProperties { - /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ + /** 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; /** * Locale hint for text recognition and document analysis. Value may contain only @@ -189,17 +255,17 @@ export interface AnalyzeDocumentQueryParamProperties { */ stringIndexType?: StringIndexType; /** List of optional analysis features. */ - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeDocumentFeaturesQueryParam; /** List of additional fields to extract. Ex. "NumberOfGuests,StoreNumber" */ - queryFields?: string[]; + queryFields?: string[] | AnalyzeDocumentQueryFieldsQueryParam; /** * Format of the analyze result top-level content. * * Possible values: "text", "markdown" */ - outputContentFormat?: ContentFormat; + outputContentFormat?: DocumentContentFormat; /** Additional outputs to generate during analysis. */ - output?: AnalyzeOutputOption[]; + output?: AnalyzeOutputOption[] | AnalyzeDocumentOutputQueryParam; } export interface AnalyzeDocumentQueryParam { @@ -219,11 +285,41 @@ export type GetAnalyzeBatchResultParameters = RequestParameters; export interface AnalyzeBatchDocumentsBodyParam { /** Analyze batch request parameters. */ - body?: AnalyzeBatchDocumentsRequest; + body: AnalyzeBatchDocumentsRequest; +} + +/** This is the wrapper object for the parameter `features` with explode set to false and style set to form. */ +export interface AnalyzeBatchDocumentsFeaturesQueryParam { + /** Value of the parameter */ + value: DocumentAnalysisFeature[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `queryFields` with explode set to false and style set to form. */ +export interface AnalyzeBatchDocumentsQueryFieldsQueryParam { + /** Value of the parameter */ + value: string[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; +} + +/** This is the wrapper object for the parameter `output` with explode set to false and style set to form. */ +export interface AnalyzeBatchDocumentsOutputQueryParam { + /** Value of the parameter */ + value: AnalyzeOutputOption[]; + /** Should we explode the value? */ + explode: false; + /** Style of the value */ + style: "form"; } export interface AnalyzeBatchDocumentsQueryParamProperties { - /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ + /** 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; /** * Locale hint for text recognition and document analysis. Value may contain only @@ -237,17 +333,17 @@ export interface AnalyzeBatchDocumentsQueryParamProperties { */ stringIndexType?: StringIndexType; /** List of optional analysis features. */ - features?: DocumentAnalysisFeature[]; + features?: DocumentAnalysisFeature[] | AnalyzeBatchDocumentsFeaturesQueryParam; /** List of additional fields to extract. Ex. "NumberOfGuests,StoreNumber" */ - queryFields?: string[]; + queryFields?: string[] | AnalyzeBatchDocumentsQueryFieldsQueryParam; /** * Format of the analyze result top-level content. * * Possible values: "text", "markdown" */ - outputContentFormat?: ContentFormat; + outputContentFormat?: DocumentContentFormat; /** Additional outputs to generate during analysis. */ - output?: AnalyzeOutputOption[]; + output?: AnalyzeOutputOption[] | AnalyzeBatchDocumentsOutputQueryParam; } export interface AnalyzeBatchDocumentsQueryParam { @@ -263,6 +359,8 @@ export type AnalyzeBatchDocumentsParameters = AnalyzeBatchDocumentsQueryParam & AnalyzeBatchDocumentsMediaTypesParam & AnalyzeBatchDocumentsBodyParam & RequestParameters; +export type ListAnalyzeBatchResultsParameters = RequestParameters; +export type DeleteAnalyzeBatchResultParameters = RequestParameters; export interface GetModelHeaders { /** An opaque, globally-unique, client-generated string identifier for the request. */ @@ -298,7 +396,7 @@ export type AuthorizeModelCopyParameters = AuthorizeModelCopyBodyParam & Request export interface CopyModelToBodyParam { /** Copy to request parameters. */ - body: CopyAuthorization; + body: ModelCopyAuthorization; } export type CopyModelToParameters = CopyModelToBodyParam & RequestParameters; @@ -371,7 +469,12 @@ export interface ClassifyDocumentFromStreamBodyParam { * * Value may contain any sequence of octets */ - body: string | Uint8Array | ReadableStream | NodeJS.ReadableStream; + body: + | string + | Uint8Array + // eslint-disable-next-line n/no-unsupported-features/node-builtins + | ReadableStream + | NodeJS.ReadableStream; } export interface ClassifyDocumentFromStreamQueryParamProperties { @@ -387,7 +490,7 @@ export interface ClassifyDocumentFromStreamQueryParamProperties { * Possible values: "auto", "none", "perPage" */ split?: SplitMode; - /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ + /** 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; } @@ -434,7 +537,7 @@ export interface ClassifyDocumentQueryParamProperties { * Possible values: "auto", "none", "perPage" */ split?: SplitMode; - /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ + /** 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; } diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/pollingHelper.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/pollingHelper.ts index 026a853d89c2..7fdc195aa52d 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/pollingHelper.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/pollingHelper.ts @@ -4,11 +4,10 @@ import type { Client, HttpResponse } from "@azure-rest/core-client"; import type { AbortSignalLike } from "@azure/abort-controller"; import type { - CancelOnProgress, - CreateHttpPollerOptions, RunningOperation, OperationResponse, OperationState, + PollerLike, } from "@azure/core-lro"; import { createHttpPoller } from "@azure/core-lro"; import type { @@ -37,76 +36,19 @@ import type { CopyClassifierToDefaultResponse, CopyClassifierToLogicalResponse, } from "./responses.js"; -import type { AnalyzeBatchResultOperationOutput } from "./outputModels.js"; /** - * A simple poller that can be used to poll a long running operation. + * Options for `getLongRunningPoller`. */ -export interface SimplePollerLike, TResult> { +export interface GetLongRunningPollerOptions { /** - * Returns true if the poller has finished polling. + * Defines how much time the poller is going to wait before making a new request to the service. */ - isDone(): boolean; + intervalInMs?: number; /** - * Returns the state of the operation. + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ - getOperationState(): TState; - /** - * Returns the id of the operation. - */ - getOperationId(): string; - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult(): TResult | undefined; - /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - */ - poll(options?: { abortSignal?: AbortSignalLike }): Promise; - /** - * Returns a promise that will resolve once the underlying operation is completed. - */ - pollUntilDone(pollOptions?: { abortSignal?: AbortSignalLike }): Promise; - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback: (state: TState) => void): CancelOnProgress; - - /** - * Returns a promise that could be used for serialized version of the poller's operation - * by invoking the operation's serialize method. - */ - serialize(): Promise; - - /** - * Wait the poller to be submitted. - */ - submitted(): Promise; - - /** - * Returns a string representation of the poller's operation. Similar to serialize but returns a string. - * @deprecated Use serialize() instead. - */ - toString(): string; - - /** - * Stops the poller from continuing to poll. Please note this will only stop the client-side polling - * @deprecated Use abortSignal to stop polling instead. - */ - stopPolling(): void; - - /** - * Returns true if the poller is stopped. - * @deprecated Use abortSignal status to track this instead. - */ - isStopped(): boolean; + restoreFrom?: string; } /** @@ -116,58 +58,58 @@ export interface SimplePollerLike, TResul * @param options - Options to set a resume state or custom polling interval. * @returns - A poller object to poll for operation state updates and eventually get the final response. */ -export async function getLongRunningPoller< +export function getLongRunningPoller< TResult extends AnalyzeBatchDocumentsLogicalResponse | AnalyzeBatchDocumentsDefaultResponse, >( client: Client, initialResponse: AnalyzeBatchDocuments202Response | AnalyzeBatchDocumentsDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends BuildModelLogicalResponse | BuildModelDefaultResponse, >( client: Client, initialResponse: BuildModel202Response | BuildModelDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends ComposeModelLogicalResponse | ComposeModelDefaultResponse, >( client: Client, initialResponse: ComposeModel202Response | ComposeModelDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends CopyModelToLogicalResponse | CopyModelToDefaultResponse, >( client: Client, initialResponse: CopyModelTo202Response | CopyModelToDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends BuildClassifierLogicalResponse | BuildClassifierDefaultResponse, >( client: Client, initialResponse: BuildClassifier202Response | BuildClassifierDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends CopyClassifierToLogicalResponse | CopyClassifierToDefaultResponse, >( client: Client, initialResponse: CopyClassifierTo202Response | CopyClassifierToDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends | AnalyzeDocumentFromStreamLogicalResponse | AnalyzeDocumentFromStreamDefaultResponse, >( client: Client, initialResponse: AnalyzeDocumentFromStream202Response | AnalyzeDocumentFromStreamDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller< + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller< TResult extends | ClassifyDocumentFromStreamLogicalResponse | ClassifyDocumentFromStreamDefaultResponse, @@ -176,13 +118,13 @@ export async function getLongRunningPoller< initialResponse: | ClassifyDocumentFromStream202Response | ClassifyDocumentFromStreamDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller( + options?: GetLongRunningPollerOptions, +): PollerLike, TResult>; +export function getLongRunningPoller( client: Client, initialResponse: TResult, - options: CreateHttpPollerOptions> = {}, -): Promise, TResult>> { + options: GetLongRunningPollerOptions = {}, +): PollerLike, TResult> { const abortController = new AbortController(); const poller: RunningOperation = { sendInitialRequest: async () => { @@ -222,74 +164,34 @@ export async function getLongRunningPoller( }, }; - options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; - - const httpPoller = createHttpPoller(poller, { - ...options, - updateState: (state, response) => { - const flatResponse = response.flatResponse; - if (!("body" in flatResponse)) return; - const flatResponseBody = flatResponse.body; - if (!("status" in flatResponseBody && flatResponseBody.status === "completed")) return; - state.status = "succeeded"; - }, - }); - const simplePoller: SimplePollerLike, TResult> = { - isDone() { - return httpPoller.isDone; - }, - isStopped() { - return abortController.signal.aborted; - }, - getOperationState() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return httpPoller.operationState; - }, - getResult() { - return httpPoller.result; - }, - toString() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return JSON.stringify({ - state: httpPoller.operationState, - }); - }, - stopPolling() { - abortController.abort(); - }, - onProgress: httpPoller.onProgress, - poll: httpPoller.poll, - pollUntilDone: httpPoller.pollUntilDone, - serialize: httpPoller.serialize, - submitted: httpPoller.submitted, - getOperationId: () => parseOperationId(initialResponse.headers["operation-location"]), - }; - return simplePoller; + return createHttpPoller(poller, options); } /** * Returns the operation-id from the operation-location header */ -function parseOperationId(operationLocationHeader: string): string { +function parseResultId(operationLocationHeader: string): string { // regex to extract the operation id from the operation-location header with the regex "[^:]+://[^/]+/documentintelligence/.+/([^?/]+)" const regex = /[^:]+:\/\/[^/]+\/documentintelligence\/.+\/([^?/]+)/; const match = operationLocationHeader.match(regex); if (!match) { throw new Error( - `Failed to parse operation id from the operation-location header: ${operationLocationHeader}`, + `Failed to parse result id from the operation-location header: ${operationLocationHeader}`, ); } return match[1]; } +/** + * Returns the operation-id from the initialResponse header + */ +export function parseResultIdFromResponse(initialResponse: { + headers: { "operation-location": string }; +}): string { + const operationLocationHeader = initialResponse.headers["operation-location"]; + return parseResultId(operationLocationHeader); +} + /** * Converts a Rest Client response to a response that the LRO implementation understands * @param response - a rest client http response diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/src/responses.ts b/sdk/documentintelligence/ai-document-intelligence-rest/src/responses.ts index 0ebe9b71afb3..c6c7300b6bc8 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/src/responses.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/src/responses.ts @@ -4,19 +4,20 @@ import type { RawHttpHeaders } from "@azure/core-rest-pipeline"; import type { HttpResponse } from "@azure-rest/core-client"; import type { - PagedOperationDetailsOutput, - ErrorResponseOutput, + PagedDocumentIntelligenceOperationDetailsOutput, + DocumentIntelligenceErrorResponseOutput, DocumentModelBuildOperationDetailsOutput, DocumentModelComposeOperationDetailsOutput, DocumentModelCopyToOperationDetailsOutput, DocumentClassifierCopyToOperationDetailsOutput, DocumentClassifierBuildOperationDetailsOutput, - OperationDetailsOutput, - ResourceDetailsOutput, - AnalyzeResultOperationOutput, - AnalyzeBatchResultOperationOutput, + DocumentIntelligenceOperationDetailsOutput, + DocumentIntelligenceResourceDetailsOutput, + AnalyzeOperationOutput, + AnalyzeBatchOperationOutput, + PagedAnalyzeBatchOperationOutput, DocumentModelDetailsOutput, - CopyAuthorizationOutput, + ModelCopyAuthorizationOutput, PagedDocumentModelDetailsOutput, PagedDocumentClassifierDetailsOutput, DocumentClassifierDetailsOutput, @@ -31,13 +32,13 @@ export interface ListOperations200Headers { /** The request has succeeded. */ export interface ListOperations200Response extends HttpResponse { status: "200"; - body: PagedOperationDetailsOutput; + body: PagedDocumentIntelligenceOperationDetailsOutput; headers: RawHttpHeaders & ListOperations200Headers; } export interface ListOperationsDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetDocumentModelBuildOperation200Headers { @@ -54,7 +55,7 @@ export interface GetDocumentModelBuildOperation200Response extends HttpResponse export interface GetDocumentModelBuildOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetDocumentModelComposeOperation200Headers { @@ -71,7 +72,7 @@ export interface GetDocumentModelComposeOperation200Response extends HttpRespons export interface GetDocumentModelComposeOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetDocumentModelCopyToOperation200Headers { @@ -88,7 +89,7 @@ export interface GetDocumentModelCopyToOperation200Response extends HttpResponse export interface GetDocumentModelCopyToOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetDocumentClassifierCopyToOperation200Headers { @@ -105,7 +106,7 @@ export interface GetDocumentClassifierCopyToOperation200Response extends HttpRes export interface GetDocumentClassifierCopyToOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetDocumentClassifierBuildOperation200Headers { @@ -122,7 +123,7 @@ export interface GetDocumentClassifierBuildOperation200Response extends HttpResp export interface GetDocumentClassifierBuildOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetOperation200Headers { @@ -133,35 +134,35 @@ export interface GetOperation200Headers { /** The request has succeeded. */ export interface GetOperation200Response extends HttpResponse { status: "200"; - body: OperationDetailsOutput; + body: DocumentIntelligenceOperationDetailsOutput; headers: RawHttpHeaders & GetOperation200Headers; } export interface GetOperationDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The request has succeeded. */ -export interface GetResourceInfo200Response extends HttpResponse { +export interface GetResourceDetails200Response extends HttpResponse { status: "200"; - body: ResourceDetailsOutput; + body: DocumentIntelligenceResourceDetailsOutput; } -export interface GetResourceInfoDefaultResponse extends HttpResponse { +export interface GetResourceDetailsDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The request has succeeded. */ export interface GetAnalyzeResult200Response extends HttpResponse { status: "200"; - body: AnalyzeResultOperationOutput; + body: AnalyzeOperationOutput; } export interface GetAnalyzeResultDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetAnalyzeResultPdf200Headers { @@ -179,7 +180,7 @@ export interface GetAnalyzeResultPdf200Response extends HttpResponse { export interface GetAnalyzeResultPdfDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetAnalyzeResultFigure200Headers { @@ -197,7 +198,17 @@ export interface GetAnalyzeResultFigure200Response extends HttpResponse { export interface GetAnalyzeResultFigureDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteAnalyzeResult204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteAnalyzeResultDefaultResponse extends HttpResponse { + status: string; + body: DocumentIntelligenceErrorResponseOutput; } export interface AnalyzeDocumentFromStream202Headers { @@ -214,7 +225,7 @@ export interface AnalyzeDocumentFromStream202Response extends HttpResponse { export interface AnalyzeDocumentFromStreamDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running analyzeDocumentFromStream operation */ @@ -236,7 +247,7 @@ export interface AnalyzeDocument202Response extends HttpResponse { export interface AnalyzeDocumentDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running analyzeDocument operation */ @@ -247,12 +258,12 @@ export interface AnalyzeDocumentLogicalResponse extends HttpResponse { /** The request has succeeded. */ export interface GetAnalyzeBatchResult200Response extends HttpResponse { status: "200"; - body: AnalyzeBatchResultOperationOutput; + body: AnalyzeBatchOperationOutput; } export interface GetAnalyzeBatchResultDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface AnalyzeBatchDocuments202Headers { @@ -269,7 +280,7 @@ export interface AnalyzeBatchDocuments202Response extends HttpResponse { export interface AnalyzeBatchDocumentsDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running analyzeBatchDocuments operation */ @@ -277,6 +288,27 @@ export interface AnalyzeBatchDocumentsLogicalResponse extends HttpResponse { status: "200"; } +/** The request has succeeded. */ +export interface ListAnalyzeBatchResults200Response extends HttpResponse { + status: "200"; + body: PagedAnalyzeBatchOperationOutput; +} + +export interface ListAnalyzeBatchResultsDefaultResponse extends HttpResponse { + status: string; + body: DocumentIntelligenceErrorResponseOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteAnalyzeBatchResult204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteAnalyzeBatchResultDefaultResponse extends HttpResponse { + status: string; + body: DocumentIntelligenceErrorResponseOutput; +} + export interface GetModel200Headers { /** An opaque, globally-unique, client-generated string identifier for the request. */ "x-ms-client-request-id"?: string; @@ -291,7 +323,7 @@ export interface GetModel200Response extends HttpResponse { export interface GetModelDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface BuildModel202Headers { @@ -308,7 +340,7 @@ export interface BuildModel202Response extends HttpResponse { export interface BuildModelDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running buildModel operation */ @@ -330,7 +362,7 @@ export interface ComposeModel202Response extends HttpResponse { export interface ComposeModelDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running composeModel operation */ @@ -341,12 +373,12 @@ export interface ComposeModelLogicalResponse extends HttpResponse { /** The request has succeeded. */ export interface AuthorizeModelCopy200Response extends HttpResponse { status: "200"; - body: CopyAuthorizationOutput; + body: ModelCopyAuthorizationOutput; } export interface AuthorizeModelCopyDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface CopyModelTo202Headers { @@ -363,7 +395,7 @@ export interface CopyModelTo202Response extends HttpResponse { export interface CopyModelToDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running copyModelTo operation */ @@ -385,7 +417,7 @@ export interface ListModels200Response extends HttpResponse { export interface ListModelsDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface DeleteModel204Headers { @@ -401,7 +433,7 @@ export interface DeleteModel204Response extends HttpResponse { export interface DeleteModelDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface BuildClassifier202Headers { @@ -418,7 +450,7 @@ export interface BuildClassifier202Response extends HttpResponse { export interface BuildClassifierDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running buildClassifier operation */ @@ -440,7 +472,7 @@ export interface ListClassifiers200Response extends HttpResponse { export interface ListClassifiersDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface GetClassifier200Headers { @@ -457,7 +489,7 @@ export interface GetClassifier200Response extends HttpResponse { export interface GetClassifierDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface DeleteClassifier204Headers { @@ -473,7 +505,7 @@ export interface DeleteClassifier204Response extends HttpResponse { export interface DeleteClassifierDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface ClassifyDocumentFromStream202Headers { @@ -490,7 +522,7 @@ export interface ClassifyDocumentFromStream202Response extends HttpResponse { export interface ClassifyDocumentFromStreamDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running classifyDocumentFromStream operation */ @@ -512,7 +544,7 @@ export interface ClassifyDocument202Response extends HttpResponse { export interface ClassifyDocumentDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running classifyDocument operation */ @@ -523,12 +555,12 @@ export interface ClassifyDocumentLogicalResponse extends HttpResponse { /** The request has succeeded. */ export interface GetClassifyResult200Response extends HttpResponse { status: "200"; - body: AnalyzeResultOperationOutput; + body: AnalyzeOperationOutput; } export interface GetClassifyResultDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The request has succeeded. */ @@ -539,7 +571,7 @@ export interface AuthorizeClassifierCopy200Response extends HttpResponse { export interface AuthorizeClassifierCopyDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } export interface CopyClassifierTo202Headers { @@ -556,7 +588,7 @@ export interface CopyClassifierTo202Response extends HttpResponse { export interface CopyClassifierToDefaultResponse extends HttpResponse { status: string; - body: ErrorResponseOutput; + body: DocumentIntelligenceErrorResponseOutput; } /** The final response for long-running copyClassifierTo operation */ diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/analysis.spec.ts b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/analysis.spec.ts similarity index 82% rename from sdk/documentintelligence/ai-document-intelligence-rest/test/public/analysis.spec.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/analysis.spec.ts index 1a9fcbf91576..0e7a14b9e4fb 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/analysis.spec.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/analysis.spec.ts @@ -3,8 +3,8 @@ import type { Recorder } from "@azure-tools/test-recorder"; import { assertEnvironmentVariable } from "@azure-tools/test-recorder"; -import { createRecorder, testPollingOptions } from "./utils/recorderUtils.js"; -import DocumentIntelligence from "../../src/documentIntelligence.js"; +import { createRecorder, testPollingOptions } from "../utils/recorderUtils.js"; +import DocumentIntelligence from "../../../src/index.js"; import { assert, describe, beforeEach, afterEach, it } from "vitest"; import { ASSET_PATH, @@ -14,18 +14,23 @@ import { makeTestUrl, isValidPNG, isValidPDF, -} from "./utils/utils.js"; +} from "../utils/utils.js"; import path from "path"; import fs from "fs"; -import type { DocumentIntelligenceClient } from "../../src/clientDefinitions.js"; import type { - AnalyzeResultOperationOutput, + AnalyzeOperationOutput, DocumentBarcodeOutput, DocumentModelBuildOperationDetailsOutput, DocumentModelDetailsOutput, DocumentTableOutput, -} from "../../src/index.js"; -import { getLongRunningPoller, isUnexpected, streamToUint8Array } from "../../src/index.js"; + DocumentIntelligenceClient, +} from "../../../src/index.js"; +import { + getLongRunningPoller, + isUnexpected, + parseResultIdFromResponse, + streamToUint8Array, +} from "../../../src/index.js"; describe("DocumentIntelligenceClient", () => { let recorder: Recorder; @@ -65,9 +70,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -100,9 +104,9 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const paragraphs = analyzeResult?.paragraphs; @@ -135,9 +139,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -167,9 +170,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -200,9 +202,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -229,9 +230,8 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -262,9 +262,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; assert.equal(pages?.[0].pageNumber, 1); assert.isNotEmpty(pages?.[0].selectionMarks); @@ -288,7 +287,7 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput; + (await poller.pollUntilDone()).body as AnalyzeOperationOutput; assert.fail("Expected an exception due to invalid locale."); } catch (ex: any) { assert.ok((ex as Error).message.includes("Invalid argument.")); @@ -310,7 +309,7 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - await (await poller).pollUntilDone(); + await poller.pollUntilDone(); }); it("invalid pages throws", async () => { @@ -330,7 +329,7 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - await (await poller).pollUntilDone(); + await poller.pollUntilDone(); assert.fail("Expected an exception due to invalid pages."); } catch (ex: any) { // Just make sure we didn't get a bad error message @@ -355,9 +354,8 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; @@ -390,9 +388,8 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; @@ -416,9 +413,8 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const pages = analyzeResult?.pages; @@ -460,7 +456,7 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse); const response = ( - (await (await poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput ).result; if (!response) { throw new Error("Expected a DocumentModelDetailsOutput response."); @@ -471,7 +467,6 @@ describe("DocumentIntelligenceClient", () => { return _model; } - it.skip("with selection marks", async () => { const { modelId } = await requireModel(); @@ -491,9 +486,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const pages = analyzeResult?.pages; @@ -530,9 +524,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; assert.isNotEmpty(documents); @@ -560,9 +553,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; assert.isNotEmpty(documents); @@ -588,9 +580,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; assert.isNotEmpty(documents); @@ -614,9 +605,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; assert.isNotEmpty(documents); @@ -641,7 +631,7 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput; + (await poller.pollUntilDone()).body as AnalyzeOperationOutput; }); it("invalid locale throws", async () => { @@ -662,8 +652,6 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } - const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput; assert.fail("Expected an exception due to invalid locale."); } catch (ex: any) { assert.ok((ex as Error).message.includes("Invalid argument.")); @@ -691,9 +679,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -723,9 +710,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const pages = analyzeResult?.pages; const tables = analyzeResult?.tables; @@ -756,8 +742,6 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } - const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput; assert.fail("Expected an exception due to invalid locale."); } catch (ex: any) { assert.ok((ex as Error).message.includes("Invalid argument.")); @@ -785,9 +769,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const receipt = documents?.[0]; @@ -814,9 +797,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const idDocument = documents?.[0]; @@ -867,9 +849,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const w2Naive = documents?.[0]; @@ -900,9 +881,8 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; @@ -911,46 +891,9 @@ describe("DocumentIntelligenceClient", () => { }); describe("batch analysis", function () { - // We only want to create the model once, but because of the recorder's - // precedence, we have to create it in a test, so one test will end up - // recording the entire creation and the other tests will still be able - // to use it - let _model: DocumentModelDetailsOutput | undefined; - let modelId: string; - - async function requireModel(): Promise { - if (!_model) { - // Compute a unique name for the model - modelId = recorder.variable("batch-model", `modelName${getRandomNumber()}`); - const initialResponse = await client.path("/documentModels:build").post({ - body: { - buildMode: "generative", - modelId: modelId, - azureBlobSource: { - containerUrl: batchTrainingFilesContainerUrl(), - }, - }, - }); - if (isUnexpected(initialResponse)) { - throw initialResponse.body.error; - } - const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const response = (await (await poller).pollUntilDone()).body as DocumentModelDetailsOutput; - if (!response) { - throw new Error("Expected a DocumentModelDetailsOutput response."); - } - _model = response; - - assert.equal(_model!.modelId, modelId); - } - - return _model!; - } - - it("batch training", async function () { - const model = await requireModel(); + it("batch analysis", async function () { const initialResponse = await client - .path("/documentModels/{modelId}:analyzeBatch", model.modelId) + .path("/documentModels/{modelId}:analyzeBatch", "prebuilt-layout") .post({ contentType: "application/json", body: { @@ -965,10 +908,24 @@ describe("DocumentIntelligenceClient", () => { if (isUnexpected(initialResponse)) { throw initialResponse.body.error; } - // get the poller + const batchResultId = parseResultIdFromResponse(initialResponse); + const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - // poll until the operation is done - await (await poller).pollUntilDone(); + await poller.pollUntilDone(); + const response = await client + .path( + "/documentModels/{modelId}/analyzeBatchResults/{resultId}", + "prebuilt-layout", + batchResultId, + ) + .get(); + if (isUnexpected(response)) { + throw response.body.error; + } + assert.ok(response.body); + assert.equal(response.body.resultId, batchResultId); + assert.equal(response.body.status, "succeeded"); + assert.equal(response.body.percentCompleted, 100); }); }); @@ -991,16 +948,12 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - + const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); await poller.pollUntilDone(); + const resultId = parseResultIdFromResponse(initialResponse); await client - .path( - "/documentModels/{modelId}/analyzeResults/{resultId}", - "prebuilt-read", - poller.getOperationId(), - ) + .path("/documentModels/{modelId}/analyzeResults/{resultId}", "prebuilt-read", resultId) .get(); }); @@ -1023,16 +976,12 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - + const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); await poller.pollUntilDone(); + const resultId = parseResultIdFromResponse(initialResponse); const output = await client - .path( - "/documentModels/{modelId}/analyzeResults/{resultId}/pdf", - "prebuilt-read", - poller.getOperationId(), - ) + .path("/documentModels/{modelId}/analyzeResults/{resultId}/pdf", "prebuilt-read", resultId) .get() .asNodeStream(); @@ -1063,9 +1012,8 @@ describe("DocumentIntelligenceClient", () => { throw initialResponse.body.error; } - const poller = await getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - - const result = (await poller.pollUntilDone()).body as AnalyzeResultOperationOutput; + const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); + const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput; const figures = result.analyzeResult?.figures; assert.isArray(figures); assert.isNotEmpty(figures?.[0]); @@ -1074,11 +1022,12 @@ describe("DocumentIntelligenceClient", () => { throw new Error("Expected a figure ID."); } + const resultId = parseResultIdFromResponse(initialResponse); const output = await client .path( "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}", "prebuilt-layout", - poller.getOperationId(), + resultId, figureId, ) .get() diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/classifiers.spec.ts b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/classifiers.spec.ts similarity index 87% rename from sdk/documentintelligence/ai-document-intelligence-rest/test/public/classifiers.spec.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/classifiers.spec.ts index b20f9fe8696f..b21f5a57341e 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/classifiers.spec.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/classifiers.spec.ts @@ -3,18 +3,18 @@ import type { Recorder } from "@azure-tools/test-recorder"; import { assertEnvironmentVariable } from "@azure-tools/test-recorder"; -import { createRecorder, testPollingOptions } from "./utils/recorderUtils.js"; -import DocumentIntelligence from "../../src/documentIntelligence.js"; +import { createRecorder, testPollingOptions } from "../utils/recorderUtils.js"; +import DocumentIntelligence from "../../../src/index.js"; import type { Context } from "vitest"; import { assert, describe, beforeEach, afterEach, it } from "vitest"; -import { ASSET_PATH, getRandomNumber, makeTestUrl } from "./utils/utils.js"; -import type { DocumentIntelligenceClient } from "../../src/clientDefinitions.js"; +import { ASSET_PATH, getRandomNumber, makeTestUrl } from "../utils/utils.js"; import type { - AnalyzeResultOperationOutput, + AnalyzeOperationOutput, DocumentClassifierBuildOperationDetailsOutput, DocumentClassifierDetailsOutput, -} from "../../src/index.js"; -import { getLongRunningPoller, isUnexpected } from "../../src/index.js"; + DocumentIntelligenceClient, +} from "../../../src/index.js"; +import { getLongRunningPoller, isUnexpected } from "../../../src/index.js"; import path from "path"; import fs from "fs"; @@ -79,7 +79,7 @@ describe.skip("classifiers", () => { } const poller = getLongRunningPoller(client, initialResponse); const response = ( - (await (await poller).pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput ).result; if (!response) { throw new Error("Expected a DocumentClassifierDetailsOutput response."); @@ -119,9 +119,8 @@ describe.skip("classifiers", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; assert.isNotEmpty(analyzeResult?.documents); assert.oneOf(analyzeResult?.documents![0].docType, ["foo", "bar"]); @@ -153,9 +152,8 @@ describe.skip("classifiers", () => { } const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; assert.isNotEmpty(analyzeResult?.documents); assert.oneOf(analyzeResult?.documents![0].docType, ["foo", "bar"]); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/documentIntelligence.spec.ts b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/documentIntelligence.spec.ts similarity index 85% rename from sdk/documentintelligence/ai-document-intelligence-rest/test/public/documentIntelligence.spec.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/documentIntelligence.spec.ts index 775859daa37a..65ea0c70a327 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/documentIntelligence.spec.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/documentIntelligence.spec.ts @@ -4,13 +4,15 @@ import type { Recorder } from "@azure-tools/test-recorder"; import { assertEnvironmentVariable } from "@azure-tools/test-recorder"; import { createTestCredential } from "@azure-tools/test-credential"; -import { createRecorder } from "./utils/recorderUtils.js"; -import DocumentIntelligence from "../../src/documentIntelligence.js"; +import { createRecorder } from "../utils/recorderUtils.js"; +import DocumentIntelligence from "../../../src/index.js"; import { assert, describe, beforeEach, afterEach, it } from "vitest"; -import { getRandomNumber, containerSasUrl } from "./utils/utils.js"; -import type { DocumentIntelligenceClient } from "../../src/clientDefinitions.js"; -import type { DocumentClassifierBuildOperationDetailsOutput } from "../../src/index.js"; -import { getLongRunningPoller, isUnexpected } from "../../src/index.js"; +import { getRandomNumber, containerSasUrl } from "../utils/utils.js"; +import type { + DocumentIntelligenceClient, + DocumentClassifierBuildOperationDetailsOutput, +} from "../../../src/index.js"; +import { getLongRunningPoller, isUnexpected } from "../../../src/index.js"; describe("DocumentIntelligenceClient", () => { let recorder: Recorder; @@ -87,7 +89,7 @@ describe("DocumentIntelligenceClient", () => { } const poller = getLongRunningPoller(client, initialResponse); const response = ( - (await (await poller).pollUntilDone()).body + (await poller.pollUntilDone()).body ); assert.strictEqual( response.result?.classifierId, diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/training.spec.ts b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/training.spec.ts similarity index 91% rename from sdk/documentintelligence/ai-document-intelligence-rest/test/public/training.spec.ts rename to sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/training.spec.ts index c65c31b51c20..734de3439365 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/training.spec.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/node/training.spec.ts @@ -3,20 +3,20 @@ import type { Recorder } from "@azure-tools/test-recorder"; import { assertEnvironmentVariable, testPollingOptions } from "@azure-tools/test-recorder"; -import { createRecorder } from "./utils/recorderUtils.js"; -import DocumentIntelligence from "../../src/documentIntelligence.js"; +import { createRecorder } from "../utils/recorderUtils.js"; +import DocumentIntelligence from "../../../src/index.js"; import { assert, describe, beforeEach, afterEach, it } from "vitest"; -import { getRandomNumber, containerSasUrl } from "./utils/utils.js"; -import type { DocumentIntelligenceClient } from "../../src/clientDefinitions.js"; +import { getRandomNumber, containerSasUrl } from "../utils/utils.js"; import type { - AnalyzeResultOperationOutput, + AnalyzeOperationOutput, DocumentModelBuildOperationDetailsOutput, DocumentModelComposeOperationDetailsOutput, DocumentModelCopyToOperationDetailsOutput, DocumentModelDetailsOutput, DocumentTypeDetails, -} from "../../src/index.js"; -import { getLongRunningPoller, isUnexpected, paginate } from "../../src/index.js"; + DocumentIntelligenceClient, +} from "../../../src/index.js"; +import { getLongRunningPoller, isUnexpected, paginate } from "../../../src/index.js"; describe("model management", () => { let recorder: Recorder; @@ -77,7 +77,7 @@ describe("model management", () => { } const poller = getLongRunningPoller(client, initialResponse); const response = ( - (await (await poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput ).result; if (!response) { throw new Error("Expected a DocumentModelDetailsOutput response."); @@ -137,9 +137,8 @@ describe("model management", () => { const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: testPollingOptions.updateIntervalInMs, }); - const analyzeResult = ( - (await (await poller).pollUntilDone()).body as AnalyzeResultOperationOutput - ).analyzeResult; + const analyzeResult = ((await poller.pollUntilDone()).body as AnalyzeOperationOutput) + .analyzeResult; const documents = analyzeResult?.documents; const tables = analyzeResult?.tables; @@ -246,7 +245,7 @@ describe("model management", () => { } const poller = getLongRunningPoller(client, initialResponse); const { modelId, docTypes } = ( - (await (await poller).pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput ).result!; assert.equal(modelId, testModelId); @@ -276,7 +275,7 @@ describe("model management", () => { const poller = getLongRunningPoller(client, initialResponse); const composedModel = ( - (await (await poller).pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput + (await poller.pollUntilDone()).body as DocumentModelComposeOperationDetailsOutput ).result!; assert.ok(composedModel.modelId); assert.equal(composedModel.modelId, modelId); @@ -315,8 +314,7 @@ describe("model management", () => { } const trainingPoller = getLongRunningPoller(client, initialResponse); const sourceModel = ( - (await (await trainingPoller).pollUntilDone()) - .body as DocumentModelBuildOperationDetailsOutput + (await trainingPoller.pollUntilDone()).body as DocumentModelBuildOperationDetailsOutput ).result!; assert.equal(sourceModel.modelId, modelId); @@ -342,7 +340,7 @@ describe("model management", () => { } const copyPoller = getLongRunningPoller(client, copyInitResponse); const copyResult = ( - (await (await copyPoller).pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput + (await copyPoller.pollUntilDone()).body as DocumentModelCopyToOperationDetailsOutput ).result!; assert.ok(copyResult, "Expecting valid copy result"); diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/utils/recorderUtils.ts b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/utils/recorderUtils.ts index b9a1b77e8662..e015c7c156bc 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/test/public/utils/recorderUtils.ts +++ b/sdk/documentintelligence/ai-document-intelligence-rest/test/public/utils/recorderUtils.ts @@ -2,7 +2,12 @@ // Licensed under the MIT License. import type { RecorderStartOptions, TestInfo } from "@azure-tools/test-recorder"; -import { Recorder, env, isPlaybackMode } from "@azure-tools/test-recorder"; +import { + Recorder, + assertEnvironmentVariable, + isPlaybackMode, + isRecordMode, +} from "@azure-tools/test-recorder"; const envSetupForPlayback: { [k: string]: string } = { AZURE_CLIENT_ID: "azure_client_id", @@ -34,64 +39,84 @@ export const recorderOptions: RecorderStartOptions = { "AZSDK3496", // $..resourceLocation ], sanitizerOptions: { - generalSanitizers: [ - // endpoints - { - target: env["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"]?.split("/")[2] || "", - value: - envSetupForPlayback["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"].split("/")[2], - }, - { - target: env["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"]?.split("/")[2] || "", - value: envSetupForPlayback["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"].split("/")[2], - }, - { - target: - env["DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL"]?.split("/")[2] || - "", - value: - envSetupForPlayback[ - "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL" - ].split("/")[2], - }, - // sas tokens - { - target: env["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"]?.split("?")[1] || "", - value: - envSetupForPlayback["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"].split("?")[1], - }, - { - target: env["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"]?.split("?")[1] || "", - value: envSetupForPlayback["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"].split("?")[1], - }, - { - target: - env["DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL"]?.split("?")[1] || - "", - value: - envSetupForPlayback[ - "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL" - ].split("?")[1], - }, - { - target: - env["DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL"]?.split("?")[1] || "", - value: - envSetupForPlayback["DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL"].split( - "?", - )[1], - }, - { - target: - env["DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_RESULT_CONTAINER_SAS_URL"]?.split( - "?", - )[1] || "", - value: - envSetupForPlayback[ - "DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_RESULT_CONTAINER_SAS_URL" - ].split("?")[1], - }, - ], + generalSanitizers: isRecordMode() + ? [ + // endpoints + { + target: + assertEnvironmentVariable("DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL")?.split( + "/", + )[2] || "", + value: + envSetupForPlayback["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"].split("/")[2], + }, + { + target: + assertEnvironmentVariable("DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL")?.split( + "/", + )[2] || "", + value: + envSetupForPlayback["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"].split("/")[2], + }, + { + target: + assertEnvironmentVariable( + "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL", + )?.split("/")[2] || "", + value: + envSetupForPlayback[ + "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL" + ].split("/")[2], + }, + // sas tokens + { + target: + assertEnvironmentVariable("DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL")?.split( + "?", + )[1] || "", + value: + envSetupForPlayback["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"].split("?")[1], + }, + { + target: + assertEnvironmentVariable("DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL")?.split( + "?", + )[1] || "", + value: + envSetupForPlayback["DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL"].split("?")[1], + }, + { + target: + assertEnvironmentVariable( + "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL", + )?.split("?")[1] || "", + value: + envSetupForPlayback[ + "DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL" + ].split("?")[1], + }, + { + target: + assertEnvironmentVariable( + "DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL", + )?.split("?")[1] || "", + value: + envSetupForPlayback[ + "DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL" + ].split("?")[1], + }, + { + target: + assertEnvironmentVariable( + "DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_RESULT_CONTAINER_SAS_URL", + )?.split("?")[1] || "", + value: + envSetupForPlayback[ + "DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_RESULT_CONTAINER_SAS_URL" + ].split("?")[1], + }, + ] + : [], }, }; diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/tsp-location.yaml b/sdk/documentintelligence/ai-document-intelligence-rest/tsp-location.yaml index 66ce35132bd2..39eba9bf4311 100644 --- a/sdk/documentintelligence/ai-document-intelligence-rest/tsp-location.yaml +++ b/sdk/documentintelligence/ai-document-intelligence-rest/tsp-location.yaml @@ -1,3 +1,3 @@ directory: specification/ai/DocumentIntelligence -commit: ec2a81edaecf3970e5938936e8256759905163e6 +commit: 67c84bd51ccfca841c39f274b9147347abed3f66 repo: Azure/azure-rest-api-specs diff --git a/sdk/documentintelligence/ai-document-intelligence-rest/vitest.browser.config.ts b/sdk/documentintelligence/ai-document-intelligence-rest/vitest.browser.config.ts deleted file mode 100644 index 5e0dc418cfa2..000000000000 --- a/sdk/documentintelligence/ai-document-intelligence-rest/vitest.browser.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { defineConfig } from "vitest/config"; -import { relativeRecordingsPath } from "@azure-tools/test-recorder"; - -process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); - -export default defineConfig({ - define: { - "process.env": process.env, - }, - test: { - reporters: ["basic", "junit"], - outputFile: { - junit: "test-results.browser.xml", - }, - browser: { - enabled: true, - headless: true, - name: "chromium", - provider: "playwright", - }, - fakeTimers: { - toFake: ["setTimeout", "Date"], - }, - watch: false, - include: ["dist-test/browser/**/*.spec.js"], - coverage: { - include: ["dist-test/browser/**/*.spec.js"], - provider: "istanbul", - reporter: ["text", "json", "html"], - reportsDirectory: "coverage-browser", - }, - testTimeout: 1200000, - }, -}); diff --git a/sdk/documentintelligence/test-resources.bicep b/sdk/documentintelligence/test-resources.bicep index 8b0b87f8f299..a62070ef2b75 100644 --- a/sdk/documentintelligence/test-resources.bicep +++ b/sdk/documentintelligence/test-resources.bicep @@ -62,9 +62,9 @@ resource cognitiveServicesAccount 'Microsoft.CognitiveServices/accounts@2024-04- output DOCUMENT_INTELLIGENCE_ENDPOINT string = cognitiveServicesAccount.properties.endpoint output DOCUMENT_INTELLIGENCE_API_KEY string = listKeys(cognitiveServicesAccount.id, apiVersion).key1 -output DOCUMENT_INTELLIGENCE_TRAINING_DATA_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${trainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, trainingDataSasProperties).serviceSasToken}' +output DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${trainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, trainingDataSasProperties).serviceSasToken}' output DOCUMENT_INTELLIGENCE_TESTING_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${testingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, testingDataSasProperties).serviceSasToken}' -output DOCUMENT_INTELLIGENCE_SELECTION_MARK_DATA_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${selectionMarkTrainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, selectionMarkTrainingDataSasProperties).serviceSasToken}' +output DOCUMENT_INTELLIGENCE_SELECTION_MARK_STORAGE_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${selectionMarkTrainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, selectionMarkTrainingDataSasProperties).serviceSasToken}' output DOCUMENT_INTELLIGENCE_CLASSIFIER_TRAINING_DATA_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${classifierTrainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, classifierTrainingSasProperties).serviceSasToken}' output DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${batchTrainingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, batchTrainingSasProperties).serviceSasToken}' output DOCUMENT_INTELLIGENCE_MULTIPAGE_TRAINING_DATA_CONTAINER_SAS_URL string = '${reference(blobResourceId, storageApiVersion).primaryEndpoints.blob}${multiPageTestingDataContainer}?${listServiceSas(blobResourceId, storageApiVersion, multiPageTestingDataSasProperties).serviceSasToken}'