@azure-rest/onlineexperimentation 1.0.0-alpha.20250613.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +98 -0
  4. package/dist/browser/clientDefinitions.d.ts +30 -0
  5. package/dist/browser/clientDefinitions.js +3 -0
  6. package/dist/browser/extensibleEnums.d.ts +99 -0
  7. package/dist/browser/extensibleEnums.js +106 -0
  8. package/dist/browser/index.d.ts +11 -0
  9. package/dist/browser/index.js +13 -0
  10. package/dist/browser/isUnexpected.d.ts +6 -0
  11. package/dist/browser/isUnexpected.js +72 -0
  12. package/dist/browser/logger.d.ts +1 -0
  13. package/dist/browser/logger.js +4 -0
  14. package/dist/browser/models.d.ts +104 -0
  15. package/dist/browser/models.js +3 -0
  16. package/dist/browser/onlineExperimentationClient.d.ts +15 -0
  17. package/dist/browser/onlineExperimentationClient.js +45 -0
  18. package/dist/browser/outputModels.d.ts +137 -0
  19. package/dist/browser/outputModels.js +3 -0
  20. package/dist/browser/package.json +3 -0
  21. package/dist/browser/paginateHelper.d.ts +67 -0
  22. package/dist/browser/paginateHelper.js +136 -0
  23. package/dist/browser/parameters.d.ts +92 -0
  24. package/dist/browser/parameters.js +3 -0
  25. package/dist/browser/responses.d.ts +113 -0
  26. package/dist/browser/responses.js +3 -0
  27. package/dist/commonjs/clientDefinitions.d.ts +30 -0
  28. package/dist/commonjs/clientDefinitions.js +4 -0
  29. package/dist/commonjs/extensibleEnums.d.ts +99 -0
  30. package/dist/commonjs/extensibleEnums.js +109 -0
  31. package/dist/commonjs/index.d.ts +11 -0
  32. package/dist/commonjs/index.js +33 -0
  33. package/dist/commonjs/isUnexpected.d.ts +6 -0
  34. package/dist/commonjs/isUnexpected.js +75 -0
  35. package/dist/commonjs/logger.d.ts +1 -0
  36. package/dist/commonjs/logger.js +7 -0
  37. package/dist/commonjs/models.d.ts +104 -0
  38. package/dist/commonjs/models.js +4 -0
  39. package/dist/commonjs/onlineExperimentationClient.d.ts +15 -0
  40. package/dist/commonjs/onlineExperimentationClient.js +48 -0
  41. package/dist/commonjs/outputModels.d.ts +137 -0
  42. package/dist/commonjs/outputModels.js +4 -0
  43. package/dist/commonjs/package.json +3 -0
  44. package/dist/commonjs/paginateHelper.d.ts +67 -0
  45. package/dist/commonjs/paginateHelper.js +139 -0
  46. package/dist/commonjs/parameters.d.ts +92 -0
  47. package/dist/commonjs/parameters.js +4 -0
  48. package/dist/commonjs/responses.d.ts +113 -0
  49. package/dist/commonjs/responses.js +4 -0
  50. package/dist/commonjs/tsdoc-metadata.json +11 -0
  51. package/dist/esm/clientDefinitions.d.ts +30 -0
  52. package/dist/esm/clientDefinitions.js +3 -0
  53. package/dist/esm/extensibleEnums.d.ts +99 -0
  54. package/dist/esm/extensibleEnums.js +106 -0
  55. package/dist/esm/index.d.ts +11 -0
  56. package/dist/esm/index.js +13 -0
  57. package/dist/esm/isUnexpected.d.ts +6 -0
  58. package/dist/esm/isUnexpected.js +72 -0
  59. package/dist/esm/logger.d.ts +1 -0
  60. package/dist/esm/logger.js +4 -0
  61. package/dist/esm/models.d.ts +104 -0
  62. package/dist/esm/models.js +3 -0
  63. package/dist/esm/onlineExperimentationClient.d.ts +15 -0
  64. package/dist/esm/onlineExperimentationClient.js +45 -0
  65. package/dist/esm/outputModels.d.ts +137 -0
  66. package/dist/esm/outputModels.js +3 -0
  67. package/dist/esm/package.json +3 -0
  68. package/dist/esm/paginateHelper.d.ts +67 -0
  69. package/dist/esm/paginateHelper.js +136 -0
  70. package/dist/esm/parameters.d.ts +92 -0
  71. package/dist/esm/parameters.js +3 -0
  72. package/dist/esm/responses.d.ts +113 -0
  73. package/dist/esm/responses.js +3 -0
  74. package/dist/react-native/clientDefinitions.d.ts +30 -0
  75. package/dist/react-native/clientDefinitions.js +3 -0
  76. package/dist/react-native/extensibleEnums.d.ts +99 -0
  77. package/dist/react-native/extensibleEnums.js +106 -0
  78. package/dist/react-native/index.d.ts +11 -0
  79. package/dist/react-native/index.js +13 -0
  80. package/dist/react-native/isUnexpected.d.ts +6 -0
  81. package/dist/react-native/isUnexpected.js +72 -0
  82. package/dist/react-native/logger.d.ts +1 -0
  83. package/dist/react-native/logger.js +4 -0
  84. package/dist/react-native/models.d.ts +104 -0
  85. package/dist/react-native/models.js +3 -0
  86. package/dist/react-native/onlineExperimentationClient.d.ts +15 -0
  87. package/dist/react-native/onlineExperimentationClient.js +45 -0
  88. package/dist/react-native/outputModels.d.ts +137 -0
  89. package/dist/react-native/outputModels.js +3 -0
  90. package/dist/react-native/package.json +3 -0
  91. package/dist/react-native/paginateHelper.d.ts +67 -0
  92. package/dist/react-native/paginateHelper.js +136 -0
  93. package/dist/react-native/parameters.d.ts +92 -0
  94. package/dist/react-native/parameters.js +3 -0
  95. package/dist/react-native/responses.d.ts +113 -0
  96. package/dist/react-native/responses.js +3 -0
  97. package/package.json +138 -0
  98. package/review/onlineexperimentation.api.md +612 -0
@@ -0,0 +1,72 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ const responseMap = {
4
+ "GET /experiment-metrics/{experimentMetricId}": ["200"],
5
+ "PATCH /experiment-metrics/{experimentMetricId}": ["200", "201"],
6
+ "DELETE /experiment-metrics/{experimentMetricId}": ["204"],
7
+ "POST /experiment-metrics:validate": ["200"],
8
+ "GET /experiment-metrics": ["200"],
9
+ };
10
+ export function isUnexpected(response) {
11
+ const lroOriginal = response.headers["x-ms-original-url"];
12
+ const url = new URL(lroOriginal ?? response.request.url);
13
+ const method = response.request.method;
14
+ let pathDetails = responseMap[`${method} ${url.pathname}`];
15
+ if (!pathDetails) {
16
+ pathDetails = getParametrizedPathSuccess(method, url.pathname);
17
+ }
18
+ return !pathDetails.includes(response.status);
19
+ }
20
+ function getParametrizedPathSuccess(method, path) {
21
+ const pathParts = path.split("/");
22
+ // Traverse list to match the longest candidate
23
+ // matchedLen: the length of candidate path
24
+ // matchedValue: the matched status code array
25
+ let matchedLen = -1, matchedValue = [];
26
+ // Iterate the responseMap to find a match
27
+ for (const [key, value] of Object.entries(responseMap)) {
28
+ // Extracting the path from the map key which is in format
29
+ // GET /path/foo
30
+ if (!key.startsWith(method)) {
31
+ continue;
32
+ }
33
+ const candidatePath = getPathFromMapKey(key);
34
+ // Get each part of the url path
35
+ const candidateParts = candidatePath.split("/");
36
+ // track if we have found a match to return the values found.
37
+ let found = true;
38
+ for (let i = candidateParts.length - 1, j = pathParts.length - 1; i >= 1 && j >= 1; i--, j--) {
39
+ if (candidateParts[i]?.startsWith("{") && candidateParts[i]?.indexOf("}") !== -1) {
40
+ const start = candidateParts[i].indexOf("}") + 1, end = candidateParts[i]?.length;
41
+ // If the current part of the candidate is a "template" part
42
+ // Try to use the suffix of pattern to match the path
43
+ // {guid} ==> $
44
+ // {guid}:export ==> :export$
45
+ const isMatched = new RegExp(`${candidateParts[i]?.slice(start, end)}`).test(pathParts[j] || "");
46
+ if (!isMatched) {
47
+ found = false;
48
+ break;
49
+ }
50
+ continue;
51
+ }
52
+ // If the candidate part is not a template and
53
+ // the parts don't match mark the candidate as not found
54
+ // to move on with the next candidate path.
55
+ if (candidateParts[i] !== pathParts[j]) {
56
+ found = false;
57
+ break;
58
+ }
59
+ }
60
+ // We finished evaluating the current candidate parts
61
+ // Update the matched value if and only if we found the longer pattern
62
+ if (found && candidatePath.length > matchedLen) {
63
+ matchedLen = candidatePath.length;
64
+ matchedValue = value;
65
+ }
66
+ }
67
+ return matchedValue;
68
+ }
69
+ function getPathFromMapKey(mapKey) {
70
+ const pathStart = mapKey.indexOf("/");
71
+ return mapKey.slice(pathStart);
72
+ }
@@ -0,0 +1 @@
1
+ export declare const logger: import("@azure/logger").AzureLogger;
@@ -0,0 +1,4 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { createClientLogger } from "@azure/logger";
4
+ export const logger = createClientLogger("onlineexperimentation");
@@ -0,0 +1,104 @@
1
+ /** Defines experiment metric metadata and computation details. */
2
+ export interface ExperimentMetric {
3
+ /**
4
+ * Determines whether it is included in experiment analysis.
5
+ *
6
+ * Possible values: "Active", "Inactive"
7
+ */
8
+ lifecycle: LifecycleStage;
9
+ /** A user-friendly display name for the experiment metric shown in reports and dashboards. */
10
+ displayName: string;
11
+ /** A detailed description of the experiment metric. */
12
+ description: string;
13
+ /** Categories associated with the experiment metric. Used for organizing and filtering metrics. */
14
+ categories: string[];
15
+ /**
16
+ * The desired direction for changes in the metric value.
17
+ *
18
+ * Possible values: "Increase", "Decrease", "Neutral"
19
+ */
20
+ desiredDirection: DesiredDirection;
21
+ /** The metric definition specifying how the metric value is calculated from event data. */
22
+ definition: ExperimentMetricDefinition;
23
+ }
24
+ /** The metric definition, which determines how the metric value is calculated from event data. */
25
+ export interface ExperimentMetricDefinitionParent {
26
+ type: string;
27
+ }
28
+ /** The definition of an EventCount metric definition. Counts the occurrences of a specified event. */
29
+ export interface EventCountMetricDefinition extends ExperimentMetricDefinitionParent {
30
+ /** The type of metric. */
31
+ type: "EventCount";
32
+ /** Event to observe. */
33
+ event: ObservedEvent;
34
+ }
35
+ /** An event observed by a metric. */
36
+ export interface ObservedEvent {
37
+ /** The name of the event. */
38
+ eventName: string;
39
+ /** [Optional] A condition to filter events. */
40
+ filter?: string;
41
+ }
42
+ /** The definition of a UserCount metric definition. Counts unique users who encounter a specified event. */
43
+ export interface UserCountMetricDefinition extends ExperimentMetricDefinitionParent {
44
+ /** The type of metric. */
45
+ type: "UserCount";
46
+ /** Event to observe. */
47
+ event: ObservedEvent;
48
+ }
49
+ /** The definition of an EventRate metric definition. Calculates the percentage of events satisfying a specified condition. */
50
+ export interface EventRateMetricDefinition extends ExperimentMetricDefinitionParent {
51
+ /** The type of metric. */
52
+ type: "EventRate";
53
+ /** Event to observe as the rate denominator. */
54
+ event: ObservedEvent;
55
+ /** The event contributes to the rate numerator if it satisfies this condition. */
56
+ rateCondition: string;
57
+ }
58
+ /** The definition of a UserRate metric definition. Calculates the percentage of users who encounter a start event and subsequently an end event. Users must encounter events in the specified order. */
59
+ export interface UserRateMetricDefinition extends ExperimentMetricDefinitionParent {
60
+ /** The type of metric. */
61
+ type: "UserRate";
62
+ /** The start event to observe as the rate denominator. */
63
+ startEvent: ObservedEvent;
64
+ /** The end event to observe, which is a condition for the rate numerator. */
65
+ endEvent: ObservedEvent;
66
+ }
67
+ /** The definition of a Sum metric definition. Calculates the sum of a specified event property. Experiment analysis accounts for unequal traffic allocation. */
68
+ export interface SumMetricDefinition extends ExperimentMetricDefinitionParent {
69
+ /** The type of metric. */
70
+ type: "Sum";
71
+ /** The value to aggregate. */
72
+ value: AggregatedValue;
73
+ }
74
+ /** An event property value aggregated by a metric. */
75
+ export interface AggregatedValue {
76
+ /** The name of the event. */
77
+ eventName: string;
78
+ /** [Optional] A condition to filter events. */
79
+ filter?: string;
80
+ /** The key of the event property to aggregate. */
81
+ eventProperty: string;
82
+ }
83
+ /** The definition of an Average metric definition. Calculates the average value of a specified event property. */
84
+ export interface AverageMetricDefinition extends ExperimentMetricDefinitionParent {
85
+ /** The type of metric. */
86
+ type: "Average";
87
+ /** The value to aggregate. */
88
+ value: AggregatedValue;
89
+ }
90
+ /** The definition of a Percentile metric definition. Calculates a specified percentile of an event property. */
91
+ export interface PercentileMetricDefinition extends ExperimentMetricDefinitionParent {
92
+ /** The type of metric. */
93
+ type: "Percentile";
94
+ /** The value to aggregate, including the event name and property to measure. */
95
+ value: AggregatedValue;
96
+ /** The percentile to measure. */
97
+ percentile: number;
98
+ }
99
+ /** The metric definition, which determines how the metric value is calculated from event data. */
100
+ export type ExperimentMetricDefinition = ExperimentMetricDefinitionParent | EventCountMetricDefinition | UserCountMetricDefinition | EventRateMetricDefinition | UserRateMetricDefinition | SumMetricDefinition | AverageMetricDefinition | PercentileMetricDefinition;
101
+ /** Alias for LifecycleStage */
102
+ export type LifecycleStage = string;
103
+ /** Alias for DesiredDirection */
104
+ export type DesiredDirection = string;
@@ -0,0 +1,3 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ export {};
@@ -0,0 +1,15 @@
1
+ import type { ClientOptions } from "@azure-rest/core-client";
2
+ import type { TokenCredential } from "@azure/core-auth";
3
+ import type { OnlineExperimentationClient } from "./clientDefinitions.js";
4
+ /** The optional parameters for the client */
5
+ export interface OnlineExperimentationClientOptions extends ClientOptions {
6
+ /** The api version option of the client */
7
+ apiVersion?: string;
8
+ }
9
+ /**
10
+ * Initialize a new instance of `OnlineExperimentationClient`
11
+ * @param endpointParam - Endpoint URL for the Online Experimentation workspace.
12
+ * @param credentials - uniquely identify client credential
13
+ * @param options - the parameter for all optional parameters
14
+ */
15
+ export default function createClient(endpointParam: string, credentials: TokenCredential, { apiVersion, ...options }?: OnlineExperimentationClientOptions): OnlineExperimentationClient;
@@ -0,0 +1,45 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { getClient } from "@azure-rest/core-client";
4
+ import { logger } from "./logger.js";
5
+ /**
6
+ * Initialize a new instance of `OnlineExperimentationClient`
7
+ * @param endpointParam - Endpoint URL for the Online Experimentation workspace.
8
+ * @param credentials - uniquely identify client credential
9
+ * @param options - the parameter for all optional parameters
10
+ */
11
+ export default function createClient(endpointParam, credentials, { apiVersion = "2025-05-31-preview", ...options } = {}) {
12
+ const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`;
13
+ const userAgentInfo = `azsdk-js-@azure-rest/onlineexperimentation/1.0.0-beta.1`;
14
+ const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
15
+ ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}`
16
+ : `${userAgentInfo}`;
17
+ const clientOptions = {
18
+ ...options,
19
+ userAgentOptions: {
20
+ userAgentPrefix,
21
+ },
22
+ loggingOptions: {
23
+ logger: options.loggingOptions?.logger ?? logger.info,
24
+ },
25
+ credentials: {
26
+ scopes: options.credentials?.scopes ?? ["https://exp.azure.net/.default"],
27
+ },
28
+ };
29
+ const client = getClient(endpointUrl, credentials, clientOptions);
30
+ client.pipeline.removePolicy({ name: "ApiVersionPolicy" });
31
+ client.pipeline.addPolicy({
32
+ name: "ClientApiVersionPolicy",
33
+ sendRequest: (req, next) => {
34
+ // Use the apiVersion defined in request url directly
35
+ // Append one if there is no apiVersion and we have one at client options
36
+ const url = new URL(req.url);
37
+ if (!url.searchParams.get("api-version") && apiVersion) {
38
+ // eslint-disable-next-line no-param-reassign
39
+ req.url = `${req.url}${Array.from(url.searchParams.keys()).length > 0 ? "&" : "?"}api-version=${apiVersion}`;
40
+ }
41
+ return next(req);
42
+ },
43
+ });
44
+ return client;
45
+ }
@@ -0,0 +1,137 @@
1
+ /** Defines experiment metric metadata and computation details. */
2
+ export interface ExperimentMetricOutput {
3
+ /** Identifier for this experiment metric. Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores. */
4
+ readonly id: string;
5
+ /**
6
+ * Determines whether it is included in experiment analysis.
7
+ *
8
+ * Possible values: "Active", "Inactive"
9
+ */
10
+ lifecycle: LifecycleStageOutput;
11
+ /** A user-friendly display name for the experiment metric shown in reports and dashboards. */
12
+ displayName: string;
13
+ /** A detailed description of the experiment metric. */
14
+ description: string;
15
+ /** Categories associated with the experiment metric. Used for organizing and filtering metrics. */
16
+ categories: string[];
17
+ /**
18
+ * The desired direction for changes in the metric value.
19
+ *
20
+ * Possible values: "Increase", "Decrease", "Neutral"
21
+ */
22
+ desiredDirection: DesiredDirectionOutput;
23
+ /** The metric definition specifying how the metric value is calculated from event data. */
24
+ definition: ExperimentMetricDefinitionOutput;
25
+ /** ETag of the experiment metric. */
26
+ readonly eTag: string;
27
+ /** The timestamp (UTC) of the last modification to the experiment metric resource. */
28
+ readonly lastModifiedAt: string;
29
+ }
30
+ /** The metric definition, which determines how the metric value is calculated from event data. */
31
+ export interface ExperimentMetricDefinitionOutputParent {
32
+ type: string;
33
+ }
34
+ /** The definition of an EventCount metric definition. Counts the occurrences of a specified event. */
35
+ export interface EventCountMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
36
+ /** The type of metric. */
37
+ type: "EventCount";
38
+ /** Event to observe. */
39
+ event: ObservedEventOutput;
40
+ }
41
+ /** An event observed by a metric. */
42
+ export interface ObservedEventOutput {
43
+ /** The name of the event. */
44
+ eventName: string;
45
+ /** [Optional] A condition to filter events. */
46
+ filter?: string;
47
+ }
48
+ /** The definition of a UserCount metric definition. Counts unique users who encounter a specified event. */
49
+ export interface UserCountMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
50
+ /** The type of metric. */
51
+ type: "UserCount";
52
+ /** Event to observe. */
53
+ event: ObservedEventOutput;
54
+ }
55
+ /** The definition of an EventRate metric definition. Calculates the percentage of events satisfying a specified condition. */
56
+ export interface EventRateMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
57
+ /** The type of metric. */
58
+ type: "EventRate";
59
+ /** Event to observe as the rate denominator. */
60
+ event: ObservedEventOutput;
61
+ /** The event contributes to the rate numerator if it satisfies this condition. */
62
+ rateCondition: string;
63
+ }
64
+ /** The definition of a UserRate metric definition. Calculates the percentage of users who encounter a start event and subsequently an end event. Users must encounter events in the specified order. */
65
+ export interface UserRateMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
66
+ /** The type of metric. */
67
+ type: "UserRate";
68
+ /** The start event to observe as the rate denominator. */
69
+ startEvent: ObservedEventOutput;
70
+ /** The end event to observe, which is a condition for the rate numerator. */
71
+ endEvent: ObservedEventOutput;
72
+ }
73
+ /** The definition of a Sum metric definition. Calculates the sum of a specified event property. Experiment analysis accounts for unequal traffic allocation. */
74
+ export interface SumMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
75
+ /** The type of metric. */
76
+ type: "Sum";
77
+ /** The value to aggregate. */
78
+ value: AggregatedValueOutput;
79
+ }
80
+ /** An event property value aggregated by a metric. */
81
+ export interface AggregatedValueOutput {
82
+ /** The name of the event. */
83
+ eventName: string;
84
+ /** [Optional] A condition to filter events. */
85
+ filter?: string;
86
+ /** The key of the event property to aggregate. */
87
+ eventProperty: string;
88
+ }
89
+ /** The definition of an Average metric definition. Calculates the average value of a specified event property. */
90
+ export interface AverageMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
91
+ /** The type of metric. */
92
+ type: "Average";
93
+ /** The value to aggregate. */
94
+ value: AggregatedValueOutput;
95
+ }
96
+ /** The definition of a Percentile metric definition. Calculates a specified percentile of an event property. */
97
+ export interface PercentileMetricDefinitionOutput extends ExperimentMetricDefinitionOutputParent {
98
+ /** The type of metric. */
99
+ type: "Percentile";
100
+ /** The value to aggregate, including the event name and property to measure. */
101
+ value: AggregatedValueOutput;
102
+ /** The percentile to measure. */
103
+ percentile: number;
104
+ }
105
+ /** The result of validating an experiment metric. */
106
+ export interface ExperimentMetricValidationResultOutput {
107
+ /** Indicates whether the experiment metric is valid. */
108
+ isValid: boolean;
109
+ /** Diagnostic details from the validation process. */
110
+ readonly diagnostics: Array<DiagnosticDetailOutput>;
111
+ }
112
+ /** Diagnostic details for validation errors. */
113
+ export interface DiagnosticDetailOutput {
114
+ /** A human-readable error message. */
115
+ readonly message: string;
116
+ /**
117
+ * The diagnostic error code.
118
+ *
119
+ * Possible values: "FailedSchemaValidation", "InvalidEventCondition", "UnsupportedEventCondition", "InvalidExperimentMetricDefinition"
120
+ */
121
+ readonly code: DiagnosticCodeOutput;
122
+ }
123
+ /** Paged collection of ExperimentMetric items */
124
+ export interface PagedExperimentMetricOutput {
125
+ /** The ExperimentMetric items on this page */
126
+ value: Array<ExperimentMetricOutput>;
127
+ /** The link to the next page of items */
128
+ nextLink?: string;
129
+ }
130
+ /** The metric definition, which determines how the metric value is calculated from event data. */
131
+ export type ExperimentMetricDefinitionOutput = ExperimentMetricDefinitionOutputParent | EventCountMetricDefinitionOutput | UserCountMetricDefinitionOutput | EventRateMetricDefinitionOutput | UserRateMetricDefinitionOutput | SumMetricDefinitionOutput | AverageMetricDefinitionOutput | PercentileMetricDefinitionOutput;
132
+ /** Alias for LifecycleStageOutput */
133
+ export type LifecycleStageOutput = string;
134
+ /** Alias for DesiredDirectionOutput */
135
+ export type DesiredDirectionOutput = string;
136
+ /** Alias for DiagnosticCodeOutput */
137
+ export type DiagnosticCodeOutput = string;
@@ -0,0 +1,3 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ export {};
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,67 @@
1
+ import type { Client, PathUncheckedResponse } from "@azure-rest/core-client";
2
+ /**
3
+ * An interface that tracks the settings for paged iteration
4
+ */
5
+ export interface PageSettings {
6
+ /**
7
+ * The token that keeps track of where to continue the iterator
8
+ */
9
+ continuationToken?: string;
10
+ }
11
+ /**
12
+ * An interface that allows async iterable iteration both to completion and by page.
13
+ */
14
+ export interface PagedAsyncIterableIterator<TElement, TPage = TElement[], TPageSettings = PageSettings> {
15
+ /**
16
+ * The next method, part of the iteration protocol
17
+ */
18
+ next(): Promise<IteratorResult<TElement>>;
19
+ /**
20
+ * The connection to the async iterator, part of the iteration protocol
21
+ */
22
+ [Symbol.asyncIterator](): PagedAsyncIterableIterator<TElement, TPage, TPageSettings>;
23
+ /**
24
+ * Return an AsyncIterableIterator that works a page at a time
25
+ */
26
+ byPage: (settings?: TPageSettings) => AsyncIterableIterator<TPage>;
27
+ }
28
+ /**
29
+ * Helper type to extract the type of an array
30
+ */
31
+ export type GetArrayType<T> = T extends Array<infer TData> ? TData : never;
32
+ /**
33
+ * The type of a custom function that defines how to get a page and a link to the next one if any.
34
+ */
35
+ export type GetPage<TPage> = (pageLink: string) => Promise<{
36
+ page: TPage;
37
+ nextPageLink?: string;
38
+ }>;
39
+ /**
40
+ * Options for the paging helper
41
+ */
42
+ export interface PagingOptions<TResponse> {
43
+ /**
44
+ * Custom function to extract pagination details for crating the PagedAsyncIterableIterator
45
+ */
46
+ customGetPage?: GetPage<PaginateReturn<TResponse>[]>;
47
+ }
48
+ /**
49
+ * Helper type to infer the Type of the paged elements from the response type
50
+ * This type is generated based on the swagger information for x-ms-pageable
51
+ * specifically on the itemName property which indicates the property of the response
52
+ * where the page items are found. The default value is `value`.
53
+ * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter
54
+ */
55
+ export type PaginateReturn<TResult> = TResult extends {
56
+ body: {
57
+ value?: infer TPage;
58
+ };
59
+ } ? GetArrayType<TPage> : Array<unknown>;
60
+ /**
61
+ * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension
62
+ * @param client - Client to use for sending the next page requests
63
+ * @param initialResponse - Initial response containing the nextLink and current page of elements
64
+ * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results
65
+ * @returns - PagedAsyncIterableIterator to iterate the elements
66
+ */
67
+ export declare function paginate<TResponse extends PathUncheckedResponse>(client: Client, initialResponse: TResponse, options?: PagingOptions<TResponse>): PagedAsyncIterableIterator<PaginateReturn<TResponse>>;
@@ -0,0 +1,136 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { createRestError } from "@azure-rest/core-client";
4
+ /**
5
+ * returns an async iterator that iterates over results. It also has a `byPage`
6
+ * method that returns pages of items at once.
7
+ *
8
+ * @param pagedResult - an object that specifies how to get pages.
9
+ * @returns a paged async iterator that iterates over results.
10
+ */
11
+ function getPagedAsyncIterator(pagedResult) {
12
+ const iter = getItemAsyncIterator(pagedResult);
13
+ return {
14
+ next() {
15
+ return iter.next();
16
+ },
17
+ [Symbol.asyncIterator]() {
18
+ return this;
19
+ },
20
+ byPage: pagedResult?.byPage ??
21
+ ((settings) => {
22
+ const { continuationToken } = settings ?? {};
23
+ return getPageAsyncIterator(pagedResult, {
24
+ pageLink: continuationToken,
25
+ });
26
+ }),
27
+ };
28
+ }
29
+ async function* getItemAsyncIterator(pagedResult) {
30
+ const pages = getPageAsyncIterator(pagedResult);
31
+ const firstVal = await pages.next();
32
+ // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is
33
+ if (!Array.isArray(firstVal.value)) {
34
+ // can extract elements from this page
35
+ const { toElements } = pagedResult;
36
+ if (toElements) {
37
+ yield* toElements(firstVal.value);
38
+ for await (const page of pages) {
39
+ yield* toElements(page);
40
+ }
41
+ }
42
+ else {
43
+ yield firstVal.value;
44
+ // `pages` is of type `AsyncIterableIterator<TPage>` but TPage = TElement in this case
45
+ yield* pages;
46
+ }
47
+ }
48
+ else {
49
+ yield* firstVal.value;
50
+ for await (const page of pages) {
51
+ // pages is of type `AsyncIterableIterator<TPage>` so `page` is of type `TPage`. In this branch,
52
+ // it must be the case that `TPage = TElement[]`
53
+ yield* page;
54
+ }
55
+ }
56
+ }
57
+ async function* getPageAsyncIterator(pagedResult, options = {}) {
58
+ const { pageLink } = options;
59
+ let response = await pagedResult.getPage(pageLink ?? pagedResult.firstPageLink);
60
+ if (!response) {
61
+ return;
62
+ }
63
+ yield response.page;
64
+ while (response.nextPageLink) {
65
+ response = await pagedResult.getPage(response.nextPageLink);
66
+ if (!response) {
67
+ return;
68
+ }
69
+ yield response.page;
70
+ }
71
+ }
72
+ /**
73
+ * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension
74
+ * @param client - Client to use for sending the next page requests
75
+ * @param initialResponse - Initial response containing the nextLink and current page of elements
76
+ * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results
77
+ * @returns - PagedAsyncIterableIterator to iterate the elements
78
+ */
79
+ export function paginate(client, initialResponse, options = {}) {
80
+ let firstRun = true;
81
+ const itemName = "value";
82
+ const nextLinkName = "nextLink";
83
+ const { customGetPage } = options;
84
+ const pagedResult = {
85
+ firstPageLink: "",
86
+ getPage: typeof customGetPage === "function"
87
+ ? customGetPage
88
+ : async (pageLink) => {
89
+ const result = firstRun ? initialResponse : await client.pathUnchecked(pageLink).get();
90
+ firstRun = false;
91
+ checkPagingRequest(result);
92
+ const nextLink = getNextLink(result.body, nextLinkName);
93
+ const values = getElements(result.body, itemName);
94
+ return {
95
+ page: values,
96
+ nextPageLink: nextLink,
97
+ };
98
+ },
99
+ };
100
+ return getPagedAsyncIterator(pagedResult);
101
+ }
102
+ /**
103
+ * Gets for the value of nextLink in the body
104
+ */
105
+ function getNextLink(body, nextLinkName) {
106
+ if (!nextLinkName) {
107
+ return undefined;
108
+ }
109
+ const nextLink = body[nextLinkName];
110
+ if (typeof nextLink !== "string" && typeof nextLink !== "undefined") {
111
+ throw new Error(`Body Property ${nextLinkName} should be a string or undefined`);
112
+ }
113
+ return nextLink;
114
+ }
115
+ /**
116
+ * Gets the elements of the current request in the body.
117
+ */
118
+ function getElements(body, itemName) {
119
+ const value = body[itemName];
120
+ // value has to be an array according to the x-ms-pageable extension.
121
+ // The fact that this must be an array is used above to calculate the
122
+ // type of elements in the page in PaginateReturn
123
+ if (!Array.isArray(value)) {
124
+ throw new Error(`Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`);
125
+ }
126
+ return value ?? [];
127
+ }
128
+ /**
129
+ * Checks if a request failed
130
+ */
131
+ function checkPagingRequest(response) {
132
+ const Http2xxStatusCodes = ["200", "201", "202", "203", "204", "205", "206", "207", "208", "226"];
133
+ if (!Http2xxStatusCodes.includes(response.status)) {
134
+ throw createRestError(`Pagination failed with unexpected statusCode ${response.status}`, response);
135
+ }
136
+ }