@azure/data-tables 13.0.2-alpha.20220211.1 → 13.1.0-alpha.20220218.1

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.
@@ -4,16 +4,16 @@ import { __asyncDelegator, __asyncGenerator, __asyncValues, __await, __rest } fr
4
4
  import "@azure/core-paging";
5
5
  import { isNamedKeyCredential, isSASCredential, isTokenCredential, } from "@azure/core-auth";
6
6
  import { STORAGE_SCOPE, TablesLoggingAllowedHeaderNames } from "./utils/constants";
7
+ import { injectSecondaryEndpointHeader, tablesSecondaryEndpointPolicy, } from "./secondaryEndpointPolicy";
7
8
  import { parseXML, stringifyXML } from "@azure/core-xml";
8
9
  import { GeneratedClient } from "./generated/generatedClient";
9
- import { SpanStatusCode } from "@azure/core-tracing";
10
- import { createSpan } from "./utils/tracing";
11
10
  import { getClientParamsFromConnectionString } from "./utils/connectionString";
12
11
  import { handleTableAlreadyExists } from "./utils/errorHelpers";
13
12
  import { isCredential } from "./utils/isCredential";
14
13
  import { logger } from "./logger";
15
14
  import { tablesNamedKeyCredentialPolicy } from "./tablesNamedCredentialPolicy";
16
15
  import { tablesSASTokenPolicy } from "./tablesSASTokenPolicy";
16
+ import { tracingClient } from "./utils/tracing";
17
17
  /**
18
18
  * A TableServiceClient represents a Client to the Azure Tables service allowing you
19
19
  * to perform operations on the tables and the entities.
@@ -37,6 +37,7 @@ export class TableServiceClient {
37
37
  },
38
38
  }), (isTokenCredential(credential) && { credential, credentialScopes: STORAGE_SCOPE }));
39
39
  const client = new GeneratedClient(this.url, internalPipelineOptions);
40
+ client.pipeline.addPolicy(tablesSecondaryEndpointPolicy);
40
41
  if (isNamedKeyCredential(credential)) {
41
42
  client.pipeline.addPolicy(tablesNamedKeyCredentialPolicy(credential));
42
43
  }
@@ -53,35 +54,15 @@ export class TableServiceClient {
53
54
  * @param options - The options parameters.
54
55
  */
55
56
  async getStatistics(options = {}) {
56
- const { span, updatedOptions } = createSpan("TableServiceClient-getStatistics", options);
57
- try {
58
- return await this.service.getStatistics(updatedOptions);
59
- }
60
- catch (e) {
61
- span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
62
- throw e;
63
- }
64
- finally {
65
- span.end();
66
- }
57
+ return tracingClient.withSpan("TableServiceClient.getStatistics", options, (updatedOptions) => this.service.getStatistics(injectSecondaryEndpointHeader(updatedOptions)));
67
58
  }
68
59
  /**
69
60
  * Gets the properties of an account's Table service, including properties for Analytics and CORS
70
61
  * (Cross-Origin Resource Sharing) rules.
71
62
  * @param options - The options parameters.
72
63
  */
73
- async getProperties(options = {}) {
74
- const { span, updatedOptions } = createSpan("TableServiceClient-getProperties", options);
75
- try {
76
- return await this.service.getProperties(updatedOptions);
77
- }
78
- catch (e) {
79
- span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
80
- throw e;
81
- }
82
- finally {
83
- span.end();
84
- }
64
+ getProperties(options = {}) {
65
+ return tracingClient.withSpan("TableServiceClient.getProperties", options, (updatedOptions) => this.service.getProperties(updatedOptions));
85
66
  }
86
67
  /**
87
68
  * Sets properties for an account's Table service endpoint, including properties for Analytics and CORS
@@ -89,58 +70,43 @@ export class TableServiceClient {
89
70
  * @param properties - The Table Service properties.
90
71
  * @param options - The options parameters.
91
72
  */
92
- async setProperties(properties, options = {}) {
93
- const { span, updatedOptions } = createSpan("TableServiceClient-setProperties", options);
94
- try {
95
- return await this.service.setProperties(properties, updatedOptions);
96
- }
97
- catch (e) {
98
- span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
99
- throw e;
100
- }
101
- finally {
102
- span.end();
103
- }
73
+ setProperties(properties, options = {}) {
74
+ return tracingClient.withSpan("TableServiceClient.setProperties", options, (updatedOptions) => this.service.setProperties(properties, updatedOptions));
104
75
  }
105
76
  /**
106
77
  * Creates a new table under the given account.
107
78
  * @param name - The name of the table.
108
79
  * @param options - The options parameters.
109
80
  */
110
- async createTable(name, options = {}) {
111
- const { span, updatedOptions } = createSpan("TableServiceClient-createTable", options);
112
- try {
113
- await this.table.create({ name }, Object.assign({}, updatedOptions));
114
- }
115
- catch (e) {
116
- handleTableAlreadyExists(e, Object.assign(Object.assign({}, updatedOptions), { span, logger, tableName: name }));
117
- }
118
- finally {
119
- span.end();
120
- }
81
+ createTable(name, options = {}) {
82
+ return tracingClient.withSpan("TableServiceClient.createTable", options, async (updatedOptions) => {
83
+ try {
84
+ await this.table.create({ name }, updatedOptions);
85
+ }
86
+ catch (e) {
87
+ handleTableAlreadyExists(e, Object.assign(Object.assign({}, updatedOptions), { logger, tableName: name }));
88
+ }
89
+ });
121
90
  }
122
91
  /**
123
92
  * Operation permanently deletes the specified table.
124
93
  * @param name - The name of the table.
125
94
  * @param options - The options parameters.
126
95
  */
127
- async deleteTable(name, options = {}) {
128
- const { span, updatedOptions } = createSpan("TableServiceClient-deleteTable", options);
129
- try {
130
- await this.table.delete(name, updatedOptions);
131
- }
132
- catch (e) {
133
- if (e.statusCode === 404) {
134
- logger.info("TableServiceClient-deleteTable: Table doesn't exist");
96
+ deleteTable(name, options = {}) {
97
+ return tracingClient.withSpan("TableServiceClient.deleteTable", options, async (updatedOptions) => {
98
+ try {
99
+ await this.table.delete(name, updatedOptions);
135
100
  }
136
- else {
137
- span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
138
- throw e;
101
+ catch (e) {
102
+ if (e.statusCode === 404) {
103
+ logger.info("TableServiceClient.deleteTable: Table doesn't exist");
104
+ }
105
+ else {
106
+ throw e;
107
+ }
139
108
  }
140
- }
141
- finally {
142
- span.end();
143
- }
109
+ });
144
110
  }
145
111
  /**
146
112
  * Queries tables under the given account.
@@ -192,22 +158,15 @@ export class TableServiceClient {
192
158
  }
193
159
  listTablesPage(options = {}) {
194
160
  return __asyncGenerator(this, arguments, function* listTablesPage_1() {
195
- const { span, updatedOptions } = createSpan("TableServiceClient-listTablesPage", options);
196
- try {
197
- let result = yield __await(this._listTables(updatedOptions));
161
+ let result = yield __await(tracingClient.withSpan("TableServiceClient.listTablesPage", options, (updatedOptions) => this._listTables(updatedOptions)));
162
+ yield yield __await(result);
163
+ while (result.continuationToken) {
164
+ const optionsWithContinuation = Object.assign(Object.assign({}, options), { continuationToken: result.continuationToken });
165
+ result = yield __await(tracingClient.withSpan("TableServiceClient.listTablesPage", optionsWithContinuation, async (updatedOptions, span) => {
166
+ span.setAttribute("continuationToken", updatedOptions.continuationToken);
167
+ return this._listTables(updatedOptions);
168
+ }));
198
169
  yield yield __await(result);
199
- while (result.continuationToken) {
200
- const optionsWithContinuation = Object.assign(Object.assign({}, updatedOptions), { continuationToken: result.continuationToken });
201
- result = yield __await(this._listTables(optionsWithContinuation));
202
- yield yield __await(result);
203
- }
204
- }
205
- catch (e) {
206
- span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
207
- throw e;
208
- }
209
- finally {
210
- span.end();
211
170
  }
212
171
  });
213
172
  }
@@ -1 +1 @@
1
- {"version":3,"file":"TableServiceClient.js","sourceRoot":"","sources":["../../src/TableServiceClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,oBAAoB,CAAC;AAe5B,OAAO,EAIL,oBAAoB,EACpB,eAAe,EACf,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,aAAa,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AAEnF,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,mCAAmC,EAAE,MAAM,0BAA0B,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,MAAM,EAA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,KAAK,iCACzF,WAAW,KACd,aAAa,IACb,CAAC;QACH,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED;;;;;;;;;;;;OAYG;IACI,MAAM,CAAC,oBAAoB,CAChC,gBAAwB;IACxB,8DAA8D;IAC9D,OAAmC;QAEnC,MAAM,EACJ,GAAG,EACH,OAAO,EAAE,aAAa,EACtB,UAAU,GACX,GAAG,mCAAmC,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAEnE,IAAI,UAAU,EAAE;YACd,OAAO,IAAI,kBAAkB,CAAC,GAAG,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;SAC/D;aAAM;YACL,OAAO,IAAI,kBAAkB,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;SACnD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport \"@azure/core-paging\";\nimport {\n GetPropertiesResponse,\n GetStatisticsResponse,\n ServiceProperties,\n SetPropertiesOptions,\n SetPropertiesResponse,\n} from \"./generatedModels\";\nimport { InternalClientPipelineOptions, OperationOptions } from \"@azure/core-client\";\nimport {\n ListTableItemsOptions,\n TableItem,\n TableQueryOptions,\n TableServiceClientOptions,\n} from \"./models\";\nimport {\n NamedKeyCredential,\n SASCredential,\n TokenCredential,\n isNamedKeyCredential,\n isSASCredential,\n isTokenCredential,\n} from \"@azure/core-auth\";\nimport { STORAGE_SCOPE, TablesLoggingAllowedHeaderNames } from \"./utils/constants\";\nimport { Service, Table } from \"./generated\";\nimport { parseXML, stringifyXML } from \"@azure/core-xml\";\nimport { GeneratedClient } from \"./generated/generatedClient\";\nimport { PagedAsyncIterableIterator } from \"@azure/core-paging\";\nimport { Pipeline } from \"@azure/core-rest-pipeline\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { TableItemResultPage } from \"./models\";\nimport { createSpan } from \"./utils/tracing\";\nimport { getClientParamsFromConnectionString } from \"./utils/connectionString\";\nimport { handleTableAlreadyExists } from \"./utils/errorHelpers\";\nimport { isCredential } from \"./utils/isCredential\";\nimport { logger } from \"./logger\";\nimport { tablesNamedKeyCredentialPolicy } from \"./tablesNamedCredentialPolicy\";\nimport { tablesSASTokenPolicy } from \"./tablesSASTokenPolicy\";\n\n/**\n * A TableServiceClient represents a Client to the Azure Tables service allowing you\n * to perform operations on the tables and the entities.\n */\nexport class TableServiceClient {\n /**\n * Table Account URL\n */\n public url: string;\n /**\n * Represents a pipeline for making a HTTP request to a URL.\n * Pipelines can have multiple policies to manage manipulating each request before and after it is made to the server.\n */\n public pipeline: Pipeline;\n private table: Table;\n private service: Service;\n\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - NamedKeyCredential | SASCredential used to authenticate requests. Only Supported for Node\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using an account name/key:\n *\n * ```js\n * const { AzureNamedKeyCredential, TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const sharedKeyCredential = new AzureNamedKeyCredential(account, \"<account key>\");\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * sharedKeyCredential\n * );\n * ```\n */\n constructor(url: string, credential: NamedKeyCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - SASCredential used to authenticate requests\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using a SAS Token.\n *\n * ```js\n * const { AzureSASCredential, TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const sasCredential = new AzureSASCredential(account, \"<account key>\");\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * sasCredential\n * );\n * ```\n */\n constructor(url: string, credential: SASCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - Azure Active Directory credential used to authenticate requests\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using an Azure Active Directory credential:\n *\n * ```js\n * cons { DefaultAzureCredential } = require(\"@azure/identity\");\n * const { TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const credential = new DefaultAzureCredential();\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * credential\n * );\n * ```\n */\n constructor(url: string, credential: TokenCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as\n * \"https://myaccount.table.core.windows.net\". You can append a SAS,\n * such as \"https://myaccount.table.core.windows.net?sasString\".\n * @param options - Options to configure the HTTP pipeline.\n * Example appending a SAS token:\n *\n * ```js\n * const account = \"<storage account name>\";\n * const sasToken = \"<SAS token>\";\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net?${sasToken}`,\n * );\n * ```\n */\n constructor(url: string, options?: TableServiceClientOptions);\n constructor(\n url: string,\n credentialOrOptions?:\n | NamedKeyCredential\n | SASCredential\n | TokenCredential\n | TableServiceClientOptions,\n options?: TableServiceClientOptions\n ) {\n this.url = url;\n const credential = isCredential(credentialOrOptions) ? credentialOrOptions : undefined;\n const clientOptions =\n (!isCredential(credentialOrOptions) ? credentialOrOptions : options) || {};\n\n clientOptions.endpoint = clientOptions.endpoint || this.url;\n\n const internalPipelineOptions: InternalClientPipelineOptions = {\n ...clientOptions,\n ...{\n loggingOptions: {\n logger: logger.info,\n additionalAllowedHeaderNames: [...TablesLoggingAllowedHeaderNames],\n },\n deserializationOptions: {\n parseXML,\n },\n serializationOptions: {\n stringifyXML,\n },\n },\n ...(isTokenCredential(credential) && { credential, credentialScopes: STORAGE_SCOPE }),\n };\n const client = new GeneratedClient(this.url, internalPipelineOptions);\n if (isNamedKeyCredential(credential)) {\n client.pipeline.addPolicy(tablesNamedKeyCredentialPolicy(credential));\n } else if (isSASCredential(credential)) {\n client.pipeline.addPolicy(tablesSASTokenPolicy(credential));\n }\n\n this.pipeline = client.pipeline;\n this.table = client.table;\n this.service = client.service;\n }\n\n /**\n * Retrieves statistics related to replication for the Table service. It is only available on the\n * secondary location endpoint when read-access geo-redundant replication is enabled for the account.\n * @param options - The options parameters.\n */\n public async getStatistics(options: OperationOptions = {}): Promise<GetStatisticsResponse> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-getStatistics\", options);\n try {\n return await this.service.getStatistics(updatedOptions);\n } catch (e) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n throw e;\n } finally {\n span.end();\n }\n }\n\n /**\n * Gets the properties of an account's Table service, including properties for Analytics and CORS\n * (Cross-Origin Resource Sharing) rules.\n * @param options - The options parameters.\n */\n public async getProperties(options: OperationOptions = {}): Promise<GetPropertiesResponse> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-getProperties\", options);\n try {\n return await this.service.getProperties(updatedOptions);\n } catch (e) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n throw e;\n } finally {\n span.end();\n }\n }\n\n /**\n * Sets properties for an account's Table service endpoint, including properties for Analytics and CORS\n * (Cross-Origin Resource Sharing) rules.\n * @param properties - The Table Service properties.\n * @param options - The options parameters.\n */\n public async setProperties(\n properties: ServiceProperties,\n options: SetPropertiesOptions = {}\n ): Promise<SetPropertiesResponse> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-setProperties\", options);\n try {\n return await this.service.setProperties(properties, updatedOptions);\n } catch (e) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n throw e;\n } finally {\n span.end();\n }\n }\n\n /**\n * Creates a new table under the given account.\n * @param name - The name of the table.\n * @param options - The options parameters.\n */\n public async createTable(name: string, options: OperationOptions = {}): Promise<void> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-createTable\", options);\n try {\n await this.table.create({ name }, { ...updatedOptions });\n } catch (e) {\n handleTableAlreadyExists(e, { ...updatedOptions, span, logger, tableName: name });\n } finally {\n span.end();\n }\n }\n\n /**\n * Operation permanently deletes the specified table.\n * @param name - The name of the table.\n * @param options - The options parameters.\n */\n public async deleteTable(name: string, options: OperationOptions = {}): Promise<void> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-deleteTable\", options);\n try {\n await this.table.delete(name, updatedOptions);\n } catch (e) {\n if (e.statusCode === 404) {\n logger.info(\"TableServiceClient-deleteTable: Table doesn't exist\");\n } else {\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n throw e;\n }\n } finally {\n span.end();\n }\n }\n\n /**\n * Queries tables under the given account.\n * @param options - The options parameters.\n */\n public listTables(\n // eslint-disable-next-line @azure/azure-sdk/ts-naming-options\n options?: ListTableItemsOptions\n ): PagedAsyncIterableIterator<TableItem, TableItemResultPage> {\n const iter = this.listTablesAll(options);\n\n return {\n next() {\n return iter.next();\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n byPage: (settings) => {\n const pageOptions: InternalListTablesOptions = {\n ...options,\n queryOptions: { top: settings?.maxPageSize },\n };\n\n if (settings?.continuationToken) {\n pageOptions.continuationToken = settings.continuationToken;\n }\n\n return this.listTablesPage(pageOptions);\n },\n };\n }\n\n private async *listTablesAll(\n options?: InternalListTablesOptions\n ): AsyncIterableIterator<TableItem> {\n const firstPage = await this._listTables(options);\n const { continuationToken } = firstPage;\n yield* firstPage;\n if (continuationToken) {\n const optionsWithContinuation: InternalListTablesOptions = {\n ...options,\n continuationToken,\n };\n for await (const page of this.listTablesPage(optionsWithContinuation)) {\n yield* page;\n }\n }\n }\n\n private async *listTablesPage(\n options: InternalListTablesOptions = {}\n ): AsyncIterableIterator<TableItemResultPage> {\n const { span, updatedOptions } = createSpan(\"TableServiceClient-listTablesPage\", options);\n\n try {\n let result = await this._listTables(updatedOptions);\n\n yield result;\n\n while (result.continuationToken) {\n const optionsWithContinuation: InternalListTablesOptions = {\n ...updatedOptions,\n continuationToken: result.continuationToken,\n };\n result = await this._listTables(optionsWithContinuation);\n yield result;\n }\n } catch (e) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n throw e;\n } finally {\n span.end();\n }\n }\n\n private async _listTables(options: InternalListTablesOptions = {}): Promise<TableItemResultPage> {\n const { continuationToken: nextTableName, ...listOptions } = options;\n const { xMsContinuationNextTableName: continuationToken, value = [] } = await this.table.query({\n ...listOptions,\n nextTableName,\n });\n return Object.assign([...value], { continuationToken });\n }\n\n /**\n *\n * Creates an instance of TableServiceClient from connection string.\n *\n * @param connectionString - Account connection string or a SAS connection string of an Azure storage account.\n * [ Note - Account connection string can only be used in NODE.JS runtime. ]\n * Account connection string example -\n * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`\n * SAS connection string example -\n * `BlobEndpoint=https://myaccount.table.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`\n * @param options - Options to configure the HTTP pipeline.\n * @returns A new TableServiceClient from the given connection string.\n */\n public static fromConnectionString(\n connectionString: string,\n // eslint-disable-next-line @azure/azure-sdk/ts-naming-options\n options?: TableServiceClientOptions\n ): TableServiceClient {\n const {\n url,\n options: clientOptions,\n credential,\n } = getClientParamsFromConnectionString(connectionString, options);\n\n if (credential) {\n return new TableServiceClient(url, credential, clientOptions);\n } else {\n return new TableServiceClient(url, clientOptions);\n }\n }\n}\n\ntype InternalListTablesOptions = ListTableItemsOptions & {\n queryOptions?: TableQueryOptions & { top?: number };\n /**\n * A table query continuation token from a previous call.\n */\n continuationToken?: string;\n};\n"]}
1
+ {"version":3,"file":"TableServiceClient.js","sourceRoot":"","sources":["../../src/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EACJ,GAAG,EACH,OAAO,EAAE,aAAa,EACtB,UAAU,GACX,GAAG,mCAAmC,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAEnE,IAAI,UAAU,EAAE;YACd,OAAO,IAAI,kBAAkB,CAAC,GAAG,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;SAC/D;aAAM;YACL,OAAO,IAAI,kBAAkB,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;SACnD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport \"@azure/core-paging\";\n\nimport {\n GetPropertiesResponse,\n GetStatisticsResponse,\n ServiceProperties,\n SetPropertiesOptions,\n SetPropertiesResponse,\n} from \"./generatedModels\";\nimport { InternalClientPipelineOptions, OperationOptions } from \"@azure/core-client\";\nimport {\n ListTableItemsOptions,\n TableItem,\n TableQueryOptions,\n TableServiceClientOptions,\n} from \"./models\";\nimport {\n NamedKeyCredential,\n SASCredential,\n TokenCredential,\n isNamedKeyCredential,\n isSASCredential,\n isTokenCredential,\n} from \"@azure/core-auth\";\nimport { STORAGE_SCOPE, TablesLoggingAllowedHeaderNames } from \"./utils/constants\";\nimport { Service, Table } from \"./generated\";\nimport {\n injectSecondaryEndpointHeader,\n tablesSecondaryEndpointPolicy,\n} from \"./secondaryEndpointPolicy\";\nimport { parseXML, stringifyXML } from \"@azure/core-xml\";\n\nimport { GeneratedClient } from \"./generated/generatedClient\";\nimport { PagedAsyncIterableIterator } from \"@azure/core-paging\";\nimport { Pipeline } from \"@azure/core-rest-pipeline\";\nimport { TableItemResultPage } from \"./models\";\nimport { getClientParamsFromConnectionString } from \"./utils/connectionString\";\nimport { handleTableAlreadyExists } from \"./utils/errorHelpers\";\nimport { isCredential } from \"./utils/isCredential\";\nimport { logger } from \"./logger\";\nimport { tablesNamedKeyCredentialPolicy } from \"./tablesNamedCredentialPolicy\";\nimport { tablesSASTokenPolicy } from \"./tablesSASTokenPolicy\";\nimport { tracingClient } from \"./utils/tracing\";\n\n/**\n * A TableServiceClient represents a Client to the Azure Tables service allowing you\n * to perform operations on the tables and the entities.\n */\nexport class TableServiceClient {\n /**\n * Table Account URL\n */\n public url: string;\n /**\n * Represents a pipeline for making a HTTP request to a URL.\n * Pipelines can have multiple policies to manage manipulating each request before and after it is made to the server.\n */\n public pipeline: Pipeline;\n private table: Table;\n private service: Service;\n\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - NamedKeyCredential | SASCredential used to authenticate requests. Only Supported for Node\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using an account name/key:\n *\n * ```js\n * const { AzureNamedKeyCredential, TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const sharedKeyCredential = new AzureNamedKeyCredential(account, \"<account key>\");\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * sharedKeyCredential\n * );\n * ```\n */\n constructor(url: string, credential: NamedKeyCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - SASCredential used to authenticate requests\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using a SAS Token.\n *\n * ```js\n * const { AzureSASCredential, TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const sasCredential = new AzureSASCredential(account, \"<account key>\");\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * sasCredential\n * );\n * ```\n */\n constructor(url: string, credential: SASCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as \"https://myaccount.table.core.windows.net\".\n * @param credential - Azure Active Directory credential used to authenticate requests\n * @param options - Options to configure the HTTP pipeline.\n *\n * ### Example using an Azure Active Directory credential:\n *\n * ```js\n * cons { DefaultAzureCredential } = require(\"@azure/identity\");\n * const { TableServiceClient } = require(\"@azure/data-tables\")\n * const account = \"<storage account name>\"\n * const credential = new DefaultAzureCredential();\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net`,\n * credential\n * );\n * ```\n */\n constructor(url: string, credential: TokenCredential, options?: TableServiceClientOptions);\n /**\n * Creates a new instance of the TableServiceClient class.\n *\n * @param url - The URL of the service account that is the target of the desired operation., such as\n * \"https://myaccount.table.core.windows.net\". You can append a SAS,\n * such as \"https://myaccount.table.core.windows.net?sasString\".\n * @param options - Options to configure the HTTP pipeline.\n * Example appending a SAS token:\n *\n * ```js\n * const account = \"<storage account name>\";\n * const sasToken = \"<SAS token>\";\n *\n * const tableServiceClient = new TableServiceClient(\n * `https://${account}.table.core.windows.net?${sasToken}`,\n * );\n * ```\n */\n constructor(url: string, options?: TableServiceClientOptions);\n constructor(\n url: string,\n credentialOrOptions?:\n | NamedKeyCredential\n | SASCredential\n | TokenCredential\n | TableServiceClientOptions,\n options?: TableServiceClientOptions\n ) {\n this.url = url;\n const credential = isCredential(credentialOrOptions) ? credentialOrOptions : undefined;\n const clientOptions =\n (!isCredential(credentialOrOptions) ? credentialOrOptions : options) || {};\n\n clientOptions.endpoint = clientOptions.endpoint || this.url;\n\n const internalPipelineOptions: InternalClientPipelineOptions = {\n ...clientOptions,\n ...{\n loggingOptions: {\n logger: logger.info,\n additionalAllowedHeaderNames: [...TablesLoggingAllowedHeaderNames],\n },\n deserializationOptions: {\n parseXML,\n },\n serializationOptions: {\n stringifyXML,\n },\n },\n ...(isTokenCredential(credential) && { credential, credentialScopes: STORAGE_SCOPE }),\n };\n const client = new GeneratedClient(this.url, internalPipelineOptions);\n client.pipeline.addPolicy(tablesSecondaryEndpointPolicy);\n\n if (isNamedKeyCredential(credential)) {\n client.pipeline.addPolicy(tablesNamedKeyCredentialPolicy(credential));\n } else if (isSASCredential(credential)) {\n client.pipeline.addPolicy(tablesSASTokenPolicy(credential));\n }\n\n this.pipeline = client.pipeline;\n this.table = client.table;\n this.service = client.service;\n }\n\n /**\n * Retrieves statistics related to replication for the Table service. It is only available on the\n * secondary location endpoint when read-access geo-redundant replication is enabled for the account.\n * @param options - The options parameters.\n */\n public async getStatistics(options: OperationOptions = {}): Promise<GetStatisticsResponse> {\n return tracingClient.withSpan(\"TableServiceClient.getStatistics\", options, (updatedOptions) =>\n this.service.getStatistics(injectSecondaryEndpointHeader(updatedOptions))\n );\n }\n\n /**\n * Gets the properties of an account's Table service, including properties for Analytics and CORS\n * (Cross-Origin Resource Sharing) rules.\n * @param options - The options parameters.\n */\n public getProperties(options: OperationOptions = {}): Promise<GetPropertiesResponse> {\n return tracingClient.withSpan(\"TableServiceClient.getProperties\", options, (updatedOptions) =>\n this.service.getProperties(updatedOptions)\n );\n }\n\n /**\n * Sets properties for an account's Table service endpoint, including properties for Analytics and CORS\n * (Cross-Origin Resource Sharing) rules.\n * @param properties - The Table Service properties.\n * @param options - The options parameters.\n */\n public setProperties(\n properties: ServiceProperties,\n options: SetPropertiesOptions = {}\n ): Promise<SetPropertiesResponse> {\n return tracingClient.withSpan(\"TableServiceClient.setProperties\", options, (updatedOptions) =>\n this.service.setProperties(properties, updatedOptions)\n );\n }\n\n /**\n * Creates a new table under the given account.\n * @param name - The name of the table.\n * @param options - The options parameters.\n */\n public createTable(name: string, options: OperationOptions = {}): Promise<void> {\n return tracingClient.withSpan(\n \"TableServiceClient.createTable\",\n options,\n async (updatedOptions) => {\n try {\n await this.table.create({ name }, updatedOptions);\n } catch (e) {\n handleTableAlreadyExists(e, { ...updatedOptions, logger, tableName: name });\n }\n }\n );\n }\n\n /**\n * Operation permanently deletes the specified table.\n * @param name - The name of the table.\n * @param options - The options parameters.\n */\n public deleteTable(name: string, options: OperationOptions = {}): Promise<void> {\n return tracingClient.withSpan(\n \"TableServiceClient.deleteTable\",\n options,\n async (updatedOptions) => {\n try {\n await this.table.delete(name, updatedOptions);\n } catch (e) {\n if (e.statusCode === 404) {\n logger.info(\"TableServiceClient.deleteTable: Table doesn't exist\");\n } else {\n throw e;\n }\n }\n }\n );\n }\n\n /**\n * Queries tables under the given account.\n * @param options - The options parameters.\n */\n public listTables(\n // eslint-disable-next-line @azure/azure-sdk/ts-naming-options\n options?: ListTableItemsOptions\n ): PagedAsyncIterableIterator<TableItem, TableItemResultPage> {\n const iter = this.listTablesAll(options);\n\n return {\n next() {\n return iter.next();\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n byPage: (settings) => {\n const pageOptions: InternalListTablesOptions = {\n ...options,\n queryOptions: { top: settings?.maxPageSize },\n };\n\n if (settings?.continuationToken) {\n pageOptions.continuationToken = settings.continuationToken;\n }\n\n return this.listTablesPage(pageOptions);\n },\n };\n }\n\n private async *listTablesAll(\n options?: InternalListTablesOptions\n ): AsyncIterableIterator<TableItem> {\n const firstPage = await this._listTables(options);\n const { continuationToken } = firstPage;\n yield* firstPage;\n if (continuationToken) {\n const optionsWithContinuation: InternalListTablesOptions = {\n ...options,\n continuationToken,\n };\n for await (const page of this.listTablesPage(optionsWithContinuation)) {\n yield* page;\n }\n }\n }\n\n private async *listTablesPage(\n options: InternalListTablesOptions = {}\n ): AsyncIterableIterator<TableItemResultPage> {\n let result = await tracingClient.withSpan(\n \"TableServiceClient.listTablesPage\",\n options,\n (updatedOptions) => this._listTables(updatedOptions)\n );\n\n yield result;\n\n while (result.continuationToken) {\n const optionsWithContinuation: InternalListTablesOptions = {\n ...options,\n continuationToken: result.continuationToken,\n };\n result = await tracingClient.withSpan(\n \"TableServiceClient.listTablesPage\",\n optionsWithContinuation,\n async (updatedOptions, span) => {\n span.setAttribute(\"continuationToken\", updatedOptions.continuationToken);\n return this._listTables(updatedOptions);\n }\n );\n yield result;\n }\n }\n\n private async _listTables(options: InternalListTablesOptions = {}): Promise<TableItemResultPage> {\n const { continuationToken: nextTableName, ...listOptions } = options;\n const { xMsContinuationNextTableName: continuationToken, value = [] } = await this.table.query({\n ...listOptions,\n nextTableName,\n });\n return Object.assign([...value], { continuationToken });\n }\n\n /**\n *\n * Creates an instance of TableServiceClient from connection string.\n *\n * @param connectionString - Account connection string or a SAS connection string of an Azure storage account.\n * [ Note - Account connection string can only be used in NODE.JS runtime. ]\n * Account connection string example -\n * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`\n * SAS connection string example -\n * `BlobEndpoint=https://myaccount.table.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`\n * @param options - Options to configure the HTTP pipeline.\n * @returns A new TableServiceClient from the given connection string.\n */\n public static fromConnectionString(\n connectionString: string,\n // eslint-disable-next-line @azure/azure-sdk/ts-naming-options\n options?: TableServiceClientOptions\n ): TableServiceClient {\n const {\n url,\n options: clientOptions,\n credential,\n } = getClientParamsFromConnectionString(connectionString, options);\n\n if (credential) {\n return new TableServiceClient(url, credential, clientOptions);\n } else {\n return new TableServiceClient(url, clientOptions);\n }\n }\n}\n\ntype InternalListTablesOptions = ListTableItemsOptions & {\n queryOptions?: TableQueryOptions & { top?: number };\n /**\n * A table query continuation token from a previous call.\n */\n continuationToken?: string;\n};\n"]}
@@ -4,11 +4,10 @@ import { serializationPolicy, serializationPolicyName, } from "@azure/core-clien
4
4
  import { RestError, createHttpHeaders, createPipelineRequest, } from "@azure/core-rest-pipeline";
5
5
  import { getInitialTransactionBody, getTransactionHttpRequestBody, } from "./utils/transactionHelpers";
6
6
  import { transactionHeaderFilterPolicy, transactionHeaderFilterPolicyName, transactionRequestAssemblePolicy, transactionRequestAssemblePolicyName, } from "./TablePolicies";
7
- import { SpanStatusCode } from "@azure/core-tracing";
8
7
  import { cosmosPatchPolicy } from "./cosmosPathPolicy";
9
- import { createSpan } from "./utils/tracing";
10
8
  import { getTransactionHeaders } from "./utils/transactionHeaders";
11
9
  import { isCosmosEndpoint } from "./utils/isCosmosEndpoint";
10
+ import { tracingClient } from "./utils/tracing";
12
11
  /**
13
12
  * Helper to build a list of transaction actions
14
13
  */
@@ -153,29 +152,18 @@ export class InternalTableTransaction {
153
152
  await Promise.all(this.resetableState.pendingOperations);
154
153
  const body = getTransactionHttpRequestBody(this.resetableState.bodyParts, this.resetableState.transactionId, this.resetableState.changesetId);
155
154
  const headers = getTransactionHeaders(this.resetableState.transactionId);
156
- const { span, updatedOptions } = createSpan("TableTransaction-submitTransaction", {});
157
- const request = createPipelineRequest({
158
- url: this.url,
159
- method: "POST",
160
- body,
161
- headers: createHttpHeaders(headers),
162
- tracingOptions: updatedOptions.tracingOptions,
163
- allowInsecureConnection: this.allowInsecureConnection,
164
- });
165
- try {
155
+ return tracingClient.withSpan("TableTransaction.submitTransaction", {}, async (updatedOptions) => {
156
+ const request = createPipelineRequest({
157
+ url: this.url,
158
+ method: "POST",
159
+ body,
160
+ headers: createHttpHeaders(headers),
161
+ tracingOptions: updatedOptions.tracingOptions,
162
+ allowInsecureConnection: this.allowInsecureConnection,
163
+ });
166
164
  const rawTransactionResponse = await this.client.sendRequest(request);
167
165
  return parseTransactionResponse(rawTransactionResponse);
168
- }
169
- catch (error) {
170
- span.setStatus({
171
- code: SpanStatusCode.ERROR,
172
- message: error.message,
173
- });
174
- throw error;
175
- }
176
- finally {
177
- span.end();
178
- }
166
+ });
179
167
  }
180
168
  checkPartitionKey(partitionKey) {
181
169
  if (this.resetableState.partitionKey !== partitionKey) {
@@ -1 +1 @@
1
- {"version":3,"file":"TableTransaction.js","sourceRoot":"","sources":["../../src/TableTransaction.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAGL,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIL,SAAS,EACT,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,yBAAyB,EACz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AAC,SAAS,CAAC,mBAAmB,EAAE,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;IAClE,QAAQ,CAAC,SAAS,CAAC,6BAA6B,EAAE,CAAC,CAAC;IACpD,QAAQ,CAAC,SAAS,CAAC,gCAAgC,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;IAC7E,IAAI,QAAQ,EAAE;QACZ,QAAQ,CAAC,SAAS,CAAC,iBAAiB,EAAE,EAAE;YACtC,aAAa,EAAE,CAAC,iCAAiC,CAAC;YAClD,cAAc,EAAE,CAAC,uBAAuB,EAAE,oCAAoC,CAAC;SAChF,CAAC,CAAC;KACJ;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DeleteTableEntityOptions,\n TableEntity,\n TableTransactionEntityResponse,\n TableTransactionResponse,\n TransactionAction,\n UpdateMode,\n UpdateTableEntityOptions,\n} from \"./models\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport {\n OperationOptions,\n ServiceClient,\n serializationPolicy,\n serializationPolicyName,\n} from \"@azure/core-client\";\nimport {\n Pipeline,\n PipelineRequest,\n PipelineResponse,\n RestError,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport {\n getInitialTransactionBody,\n getTransactionHttpRequestBody,\n} from \"./utils/transactionHelpers\";\nimport {\n transactionHeaderFilterPolicy,\n transactionHeaderFilterPolicyName,\n transactionRequestAssemblePolicy,\n transactionRequestAssemblePolicyName,\n} from \"./TablePolicies\";\n\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { TableClientLike } from \"./utils/internalModels\";\nimport { TableServiceErrorOdataError } from \"./generated\";\nimport { cosmosPatchPolicy } from \"./cosmosPathPolicy\";\nimport { createSpan } from \"./utils/tracing\";\nimport { getTransactionHeaders } from \"./utils/transactionHeaders\";\nimport { isCosmosEndpoint } from \"./utils/isCosmosEndpoint\";\n\n/**\n * Helper to build a list of transaction actions\n */\nexport class TableTransaction {\n /**\n * List of actions to perform in a transaction\n */\n public actions: TransactionAction[];\n\n constructor(actions?: TransactionAction[]) {\n this.actions = actions ?? [];\n }\n\n /**\n * Adds a create action to the transaction\n * @param entity - entity to create\n */\n createEntity<T extends object = Record<string, unknown>>(entity: TableEntity<T>): void {\n this.actions.push([\"create\", entity]);\n }\n\n /**\n * Adds a delete action to the transaction\n * @param partitionKey - partition key of the entity to delete\n * @param rowKey - rowKey of the entity to delete\n */\n deleteEntity(partitionKey: string, rowKey: string): void {\n this.actions.push([\"delete\", { partitionKey, rowKey }]);\n }\n\n /**\n * Adds an update action to the transaction\n * @param entity - entity to update\n * @param updateMode - update mode\n */\n updateEntity<T extends object = Record<string, unknown>>(\n entity: TableEntity<T>,\n updateMode: UpdateMode = \"Merge\"\n ): void {\n this.actions.push([\"update\", entity, updateMode]);\n }\n\n /**\n * Adds an upsert action to the transaction, which inserts if the entity doesn't exist or updates the existing one\n * @param entity - entity to upsert\n * @param updateMode - update mode\n */\n upsertEntity<T extends object = Record<string, unknown>>(\n entity: TableEntity<T>,\n updateMode: UpdateMode = \"Merge\"\n ): void {\n this.actions.push([\"upsert\", entity, updateMode]);\n }\n}\n\n/**\n * TableTransaction collects sub-operations that can be submitted together via submitTransaction\n */\nexport class InternalTableTransaction {\n /**\n * Table Account URL\n */\n public url: string;\n /**\n * This part of the state can be reset by\n * calling the reset function. Other parts of the state\n * such as the credentials remain the same throughout the life\n * of the instance.\n */\n private resetableState: {\n transactionId: string;\n changesetId: string;\n pendingOperations: Promise<any>[];\n bodyParts: string[];\n partitionKey: string;\n };\n private interceptClient: TableClientLike;\n private allowInsecureConnection: boolean;\n private client: ServiceClient;\n\n /**\n * @param url - Tables account url\n * @param partitionKey - partition key\n * @param credential - credential to authenticate the transaction request\n */\n constructor(\n url: string,\n partitionKey: string,\n transactionId: string,\n changesetId: string,\n client: ServiceClient,\n interceptClient: TableClientLike,\n credential?: NamedKeyCredential | SASCredential | TokenCredential,\n allowInsecureConnection: boolean = false\n ) {\n this.client = client;\n this.url = url;\n this.interceptClient = interceptClient;\n this.allowInsecureConnection = allowInsecureConnection;\n\n // Initialize Reset-able properties\n this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);\n\n // Depending on the auth method used we need to build the url\n if (!credential) {\n // When the SAS token is provided as part of the URL we need to move it after $batch\n const urlParts = url.split(\"?\");\n this.url = urlParts[0];\n const sas = urlParts.length > 1 ? `?${urlParts[1]}` : \"\";\n this.url = `${this.getUrlWithSlash()}$batch${sas}`;\n } else {\n // When using a SharedKey credential no SAS token is needed\n this.url = `${this.getUrlWithSlash()}$batch`;\n }\n }\n\n /**\n * Resets the state of the Transaction.\n */\n reset(transactionId: string, changesetId: string, partitionKey: string): void {\n this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);\n }\n\n private initializeSharedState(transactionId: string, changesetId: string, partitionKey: string) {\n const pendingOperations: Promise<any>[] = [];\n const bodyParts = getInitialTransactionBody(transactionId, changesetId);\n const isCosmos = isCosmosEndpoint(this.url);\n prepateTransactionPipeline(this.interceptClient.pipeline, bodyParts, changesetId, isCosmos);\n\n return {\n transactionId,\n changesetId,\n partitionKey,\n pendingOperations,\n bodyParts,\n };\n }\n\n /**\n * Adds a createEntity operation to the transaction\n * @param entity - Entity to create\n */\n public createEntity<T extends object>(entity: TableEntity<T>): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));\n }\n\n /**\n * Adds a createEntity operation to the transaction per each entity in the entities array\n * @param entities - Array of entities to create\n */\n public createEntities<T extends object>(entities: TableEntity<T>[]): void {\n for (const entity of entities) {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));\n }\n }\n\n /**\n * Adds a deleteEntity operation to the transaction\n * @param partitionKey - Partition key of the entity to delete\n * @param rowKey - Row key of the entity to delete\n * @param options - Options for the delete operation\n */\n public deleteEntity(\n partitionKey: string,\n rowKey: string,\n options?: DeleteTableEntityOptions\n ): void {\n this.checkPartitionKey(partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.deleteEntity(partitionKey, rowKey, options)\n );\n }\n\n /**\n * Adds an updateEntity operation to the transaction\n * @param entity - Entity to update\n * @param mode - Update mode (Merge or Replace)\n * @param options - Options for the update operation\n */\n public updateEntity<T extends object>(\n entity: TableEntity<T>,\n mode: UpdateMode,\n options?: UpdateTableEntityOptions\n ): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.updateEntity(entity, mode, options)\n );\n }\n\n /**\n * Adds an upsertEntity operation to the transaction\n * @param entity - The properties for the table entity.\n * @param mode - The different modes for updating the entity:\n * - Merge: Updates an entity by updating the entity's properties without replacing the existing entity.\n * - Replace: Updates an existing entity by replacing the entire entity.\n * @param options - The options parameters.\n */\n public upsertEntity<T extends object>(\n entity: TableEntity<T>,\n mode: UpdateMode,\n options?: OperationOptions\n ): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.upsertEntity(entity, mode, options)\n );\n }\n\n /**\n * Submits the operations in the transaction\n */\n public async submitTransaction(): Promise<TableTransactionResponse> {\n await Promise.all(this.resetableState.pendingOperations);\n const body = getTransactionHttpRequestBody(\n this.resetableState.bodyParts,\n this.resetableState.transactionId,\n this.resetableState.changesetId\n );\n\n const headers = getTransactionHeaders(this.resetableState.transactionId);\n\n const { span, updatedOptions } = createSpan(\n \"TableTransaction-submitTransaction\",\n {} as OperationOptions\n );\n const request = createPipelineRequest({\n url: this.url,\n method: \"POST\",\n body,\n headers: createHttpHeaders(headers),\n tracingOptions: updatedOptions.tracingOptions,\n allowInsecureConnection: this.allowInsecureConnection,\n });\n\n try {\n const rawTransactionResponse = await this.client.sendRequest(request);\n return parseTransactionResponse(rawTransactionResponse);\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n throw error;\n } finally {\n span.end();\n }\n }\n\n private checkPartitionKey(partitionKey: string): void {\n if (this.resetableState.partitionKey !== partitionKey) {\n throw new Error(\"All operations in a transaction must target the same partitionKey\");\n }\n }\n\n private getUrlWithSlash(): string {\n return this.url.endsWith(\"/\") ? this.url : `${this.url}/`;\n }\n}\n\nexport function parseTransactionResponse(\n transactionResponse: PipelineResponse\n): TableTransactionResponse {\n const subResponsePrefix = `--changesetresponse_`;\n const status = transactionResponse.status;\n const rawBody = transactionResponse.bodyAsText || \"\";\n const splitBody = rawBody.split(subResponsePrefix);\n const isSuccessByStatus = 200 <= status && status < 300;\n\n if (!isSuccessByStatus) {\n handleBodyError(rawBody, status, transactionResponse.request, transactionResponse);\n }\n\n // Dropping the first and last elements as they are the boundaries\n // we just care about sub request content\n const subResponses = splitBody.slice(1, splitBody.length - 1);\n\n const responses: TableTransactionEntityResponse[] = subResponses.map((subResponse) => {\n const statusMatch = subResponse.match(/HTTP\\/1.1 ([0-9]*)/);\n if (statusMatch?.length !== 2) {\n throw new Error(`Couldn't extract status from sub-response:\\n ${subResponse}`);\n }\n const subResponseStatus = Number.parseInt(statusMatch[1]);\n if (!Number.isInteger(subResponseStatus)) {\n throw new Error(`Expected sub-response status to be an integer ${subResponseStatus}`);\n }\n\n const bodyMatch = subResponse.match(/\\{(.*)\\}/);\n if (bodyMatch?.length === 2) {\n handleBodyError(\n bodyMatch[0],\n subResponseStatus,\n transactionResponse.request,\n transactionResponse\n );\n }\n\n const etagMatch = subResponse.match(/ETag: (.*)/);\n const rowKeyMatch = subResponse.match(/RowKey='(.*)'/);\n\n return {\n status: subResponseStatus,\n ...(rowKeyMatch?.length === 2 && { rowKey: rowKeyMatch[1] }),\n ...(etagMatch?.length === 2 && { etag: etagMatch[1] }),\n };\n });\n\n return {\n status,\n subResponses: responses,\n getResponseForEntity: (rowKey: string) => responses.find((r) => r.rowKey === rowKey),\n };\n}\n\nfunction handleBodyError(\n bodyAsText: string,\n statusCode: number,\n request: PipelineRequest,\n response: PipelineResponse\n) {\n let parsedError;\n\n try {\n parsedError = JSON.parse(bodyAsText);\n } catch {\n parsedError = {};\n }\n\n let message = \"Transaction Failed\";\n let code: string | undefined;\n // Only transaction sub-responses return body\n if (parsedError && parsedError[\"odata.error\"]) {\n const error: TableServiceErrorOdataError = parsedError[\"odata.error\"];\n message = error.message?.value ?? message;\n code = error.code;\n }\n\n throw new RestError(message, {\n code,\n statusCode,\n request,\n response,\n });\n}\n\n/**\n * Prepares the transaction pipeline to intercept operations\n * @param pipeline - Client pipeline\n */\nexport function prepateTransactionPipeline(\n pipeline: Pipeline,\n bodyParts: string[],\n changesetId: string,\n isCosmos: boolean\n): void {\n // Fist, we need to clear all the existing policies to make sure we start\n // with a fresh state.\n const policies = pipeline.getOrderedPolicies();\n for (const policy of policies) {\n pipeline.removePolicy({\n name: policy.name,\n });\n }\n\n // With the clear state we now initialize the pipelines required for intercepting the requests.\n // Use transaction assemble policy to assemble request and intercept request from going to wire\n\n pipeline.addPolicy(serializationPolicy(), { phase: \"Serialize\" });\n pipeline.addPolicy(transactionHeaderFilterPolicy());\n pipeline.addPolicy(transactionRequestAssemblePolicy(bodyParts, changesetId));\n if (isCosmos) {\n pipeline.addPolicy(cosmosPatchPolicy(), {\n afterPolicies: [transactionHeaderFilterPolicyName],\n beforePolicies: [serializationPolicyName, transactionRequestAssemblePolicyName],\n });\n }\n}\n"]}
1
+ {"version":3,"file":"TableTransaction.js","sourceRoot":"","sources":["../../src/TableTransaction.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAGL,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIL,SAAS,EACT,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,iCAAiC,EACjC,g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,cAAc,EAAE,CAAC,uBAAuB,EAAE,oCAAoC,CAAC;SAChF,CAAC,CAAC;KACJ;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DeleteTableEntityOptions,\n TableEntity,\n TableTransactionEntityResponse,\n TableTransactionResponse,\n TransactionAction,\n UpdateMode,\n UpdateTableEntityOptions,\n} from \"./models\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport {\n OperationOptions,\n ServiceClient,\n serializationPolicy,\n serializationPolicyName,\n} from \"@azure/core-client\";\nimport {\n Pipeline,\n PipelineRequest,\n PipelineResponse,\n RestError,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport {\n getInitialTransactionBody,\n getTransactionHttpRequestBody,\n} from \"./utils/transactionHelpers\";\nimport {\n transactionHeaderFilterPolicy,\n transactionHeaderFilterPolicyName,\n transactionRequestAssemblePolicy,\n transactionRequestAssemblePolicyName,\n} from \"./TablePolicies\";\n\nimport { TableClientLike } from \"./utils/internalModels\";\nimport { TableServiceErrorOdataError } from \"./generated\";\nimport { cosmosPatchPolicy } from \"./cosmosPathPolicy\";\nimport { getTransactionHeaders } from \"./utils/transactionHeaders\";\nimport { isCosmosEndpoint } from \"./utils/isCosmosEndpoint\";\nimport { tracingClient } from \"./utils/tracing\";\n\n/**\n * Helper to build a list of transaction actions\n */\nexport class TableTransaction {\n /**\n * List of actions to perform in a transaction\n */\n public actions: TransactionAction[];\n\n constructor(actions?: TransactionAction[]) {\n this.actions = actions ?? [];\n }\n\n /**\n * Adds a create action to the transaction\n * @param entity - entity to create\n */\n createEntity<T extends object = Record<string, unknown>>(entity: TableEntity<T>): void {\n this.actions.push([\"create\", entity]);\n }\n\n /**\n * Adds a delete action to the transaction\n * @param partitionKey - partition key of the entity to delete\n * @param rowKey - rowKey of the entity to delete\n */\n deleteEntity(partitionKey: string, rowKey: string): void {\n this.actions.push([\"delete\", { partitionKey, rowKey }]);\n }\n\n /**\n * Adds an update action to the transaction\n * @param entity - entity to update\n * @param updateMode - update mode\n */\n updateEntity<T extends object = Record<string, unknown>>(\n entity: TableEntity<T>,\n updateMode: UpdateMode = \"Merge\"\n ): void {\n this.actions.push([\"update\", entity, updateMode]);\n }\n\n /**\n * Adds an upsert action to the transaction, which inserts if the entity doesn't exist or updates the existing one\n * @param entity - entity to upsert\n * @param updateMode - update mode\n */\n upsertEntity<T extends object = Record<string, unknown>>(\n entity: TableEntity<T>,\n updateMode: UpdateMode = \"Merge\"\n ): void {\n this.actions.push([\"upsert\", entity, updateMode]);\n }\n}\n\n/**\n * TableTransaction collects sub-operations that can be submitted together via submitTransaction\n */\nexport class InternalTableTransaction {\n /**\n * Table Account URL\n */\n public url: string;\n /**\n * This part of the state can be reset by\n * calling the reset function. Other parts of the state\n * such as the credentials remain the same throughout the life\n * of the instance.\n */\n private resetableState: {\n transactionId: string;\n changesetId: string;\n pendingOperations: Promise<any>[];\n bodyParts: string[];\n partitionKey: string;\n };\n private interceptClient: TableClientLike;\n private allowInsecureConnection: boolean;\n private client: ServiceClient;\n\n /**\n * @param url - Tables account url\n * @param partitionKey - partition key\n * @param credential - credential to authenticate the transaction request\n */\n constructor(\n url: string,\n partitionKey: string,\n transactionId: string,\n changesetId: string,\n client: ServiceClient,\n interceptClient: TableClientLike,\n credential?: NamedKeyCredential | SASCredential | TokenCredential,\n allowInsecureConnection: boolean = false\n ) {\n this.client = client;\n this.url = url;\n this.interceptClient = interceptClient;\n this.allowInsecureConnection = allowInsecureConnection;\n\n // Initialize Reset-able properties\n this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);\n\n // Depending on the auth method used we need to build the url\n if (!credential) {\n // When the SAS token is provided as part of the URL we need to move it after $batch\n const urlParts = url.split(\"?\");\n this.url = urlParts[0];\n const sas = urlParts.length > 1 ? `?${urlParts[1]}` : \"\";\n this.url = `${this.getUrlWithSlash()}$batch${sas}`;\n } else {\n // When using a SharedKey credential no SAS token is needed\n this.url = `${this.getUrlWithSlash()}$batch`;\n }\n }\n\n /**\n * Resets the state of the Transaction.\n */\n reset(transactionId: string, changesetId: string, partitionKey: string): void {\n this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);\n }\n\n private initializeSharedState(transactionId: string, changesetId: string, partitionKey: string) {\n const pendingOperations: Promise<any>[] = [];\n const bodyParts = getInitialTransactionBody(transactionId, changesetId);\n const isCosmos = isCosmosEndpoint(this.url);\n prepateTransactionPipeline(this.interceptClient.pipeline, bodyParts, changesetId, isCosmos);\n\n return {\n transactionId,\n changesetId,\n partitionKey,\n pendingOperations,\n bodyParts,\n };\n }\n\n /**\n * Adds a createEntity operation to the transaction\n * @param entity - Entity to create\n */\n public createEntity<T extends object>(entity: TableEntity<T>): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));\n }\n\n /**\n * Adds a createEntity operation to the transaction per each entity in the entities array\n * @param entities - Array of entities to create\n */\n public createEntities<T extends object>(entities: TableEntity<T>[]): void {\n for (const entity of entities) {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));\n }\n }\n\n /**\n * Adds a deleteEntity operation to the transaction\n * @param partitionKey - Partition key of the entity to delete\n * @param rowKey - Row key of the entity to delete\n * @param options - Options for the delete operation\n */\n public deleteEntity(\n partitionKey: string,\n rowKey: string,\n options?: DeleteTableEntityOptions\n ): void {\n this.checkPartitionKey(partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.deleteEntity(partitionKey, rowKey, options)\n );\n }\n\n /**\n * Adds an updateEntity operation to the transaction\n * @param entity - Entity to update\n * @param mode - Update mode (Merge or Replace)\n * @param options - Options for the update operation\n */\n public updateEntity<T extends object>(\n entity: TableEntity<T>,\n mode: UpdateMode,\n options?: UpdateTableEntityOptions\n ): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.updateEntity(entity, mode, options)\n );\n }\n\n /**\n * Adds an upsertEntity operation to the transaction\n * @param entity - The properties for the table entity.\n * @param mode - The different modes for updating the entity:\n * - Merge: Updates an entity by updating the entity's properties without replacing the existing entity.\n * - Replace: Updates an existing entity by replacing the entire entity.\n * @param options - The options parameters.\n */\n public upsertEntity<T extends object>(\n entity: TableEntity<T>,\n mode: UpdateMode,\n options?: OperationOptions\n ): void {\n this.checkPartitionKey(entity.partitionKey);\n this.resetableState.pendingOperations.push(\n this.interceptClient.upsertEntity(entity, mode, options)\n );\n }\n\n /**\n * Submits the operations in the transaction\n */\n public async submitTransaction(): Promise<TableTransactionResponse> {\n await Promise.all(this.resetableState.pendingOperations);\n const body = getTransactionHttpRequestBody(\n this.resetableState.bodyParts,\n this.resetableState.transactionId,\n this.resetableState.changesetId\n );\n\n const headers = getTransactionHeaders(this.resetableState.transactionId);\n\n return tracingClient.withSpan(\n \"TableTransaction.submitTransaction\",\n {} as OperationOptions,\n async (updatedOptions) => {\n const request = createPipelineRequest({\n url: this.url,\n method: \"POST\",\n body,\n headers: createHttpHeaders(headers),\n tracingOptions: updatedOptions.tracingOptions,\n allowInsecureConnection: this.allowInsecureConnection,\n });\n\n const rawTransactionResponse = await this.client.sendRequest(request);\n return parseTransactionResponse(rawTransactionResponse);\n }\n );\n }\n\n private checkPartitionKey(partitionKey: string): void {\n if (this.resetableState.partitionKey !== partitionKey) {\n throw new Error(\"All operations in a transaction must target the same partitionKey\");\n }\n }\n\n private getUrlWithSlash(): string {\n return this.url.endsWith(\"/\") ? this.url : `${this.url}/`;\n }\n}\n\nexport function parseTransactionResponse(\n transactionResponse: PipelineResponse\n): TableTransactionResponse {\n const subResponsePrefix = `--changesetresponse_`;\n const status = transactionResponse.status;\n const rawBody = transactionResponse.bodyAsText || \"\";\n const splitBody = rawBody.split(subResponsePrefix);\n const isSuccessByStatus = 200 <= status && status < 300;\n\n if (!isSuccessByStatus) {\n handleBodyError(rawBody, status, transactionResponse.request, transactionResponse);\n }\n\n // Dropping the first and last elements as they are the boundaries\n // we just care about sub request content\n const subResponses = splitBody.slice(1, splitBody.length - 1);\n\n const responses: TableTransactionEntityResponse[] = subResponses.map((subResponse) => {\n const statusMatch = subResponse.match(/HTTP\\/1.1 ([0-9]*)/);\n if (statusMatch?.length !== 2) {\n throw new Error(`Couldn't extract status from sub-response:\\n ${subResponse}`);\n }\n const subResponseStatus = Number.parseInt(statusMatch[1]);\n if (!Number.isInteger(subResponseStatus)) {\n throw new Error(`Expected sub-response status to be an integer ${subResponseStatus}`);\n }\n\n const bodyMatch = subResponse.match(/\\{(.*)\\}/);\n if (bodyMatch?.length === 2) {\n handleBodyError(\n bodyMatch[0],\n subResponseStatus,\n transactionResponse.request,\n transactionResponse\n );\n }\n\n const etagMatch = subResponse.match(/ETag: (.*)/);\n const rowKeyMatch = subResponse.match(/RowKey='(.*)'/);\n\n return {\n status: subResponseStatus,\n ...(rowKeyMatch?.length === 2 && { rowKey: rowKeyMatch[1] }),\n ...(etagMatch?.length === 2 && { etag: etagMatch[1] }),\n };\n });\n\n return {\n status,\n subResponses: responses,\n getResponseForEntity: (rowKey: string) => responses.find((r) => r.rowKey === rowKey),\n };\n}\n\nfunction handleBodyError(\n bodyAsText: string,\n statusCode: number,\n request: PipelineRequest,\n response: PipelineResponse\n) {\n let parsedError;\n\n try {\n parsedError = JSON.parse(bodyAsText);\n } catch {\n parsedError = {};\n }\n\n let message = \"Transaction Failed\";\n let code: string | undefined;\n // Only transaction sub-responses return body\n if (parsedError && parsedError[\"odata.error\"]) {\n const error: TableServiceErrorOdataError = parsedError[\"odata.error\"];\n message = error.message?.value ?? message;\n code = error.code;\n }\n\n throw new RestError(message, {\n code,\n statusCode,\n request,\n response,\n });\n}\n\n/**\n * Prepares the transaction pipeline to intercept operations\n * @param pipeline - Client pipeline\n */\nexport function prepateTransactionPipeline(\n pipeline: Pipeline,\n bodyParts: string[],\n changesetId: string,\n isCosmos: boolean\n): void {\n // Fist, we need to clear all the existing policies to make sure we start\n // with a fresh state.\n const policies = pipeline.getOrderedPolicies();\n for (const policy of policies) {\n pipeline.removePolicy({\n name: policy.name,\n });\n }\n\n // With the clear state we now initialize the pipelines required for intercepting the requests.\n // Use transaction assemble policy to assemble request and intercept request from going to wire\n\n pipeline.addPolicy(serializationPolicy(), { phase: \"Serialize\" });\n pipeline.addPolicy(transactionHeaderFilterPolicy());\n pipeline.addPolicy(transactionRequestAssemblePolicy(bodyParts, changesetId));\n if (isCosmos) {\n pipeline.addPolicy(cosmosPatchPolicy(), {\n afterPolicies: [transactionHeaderFilterPolicyName],\n beforePolicies: [serializationPolicyName, transactionRequestAssemblePolicyName],\n });\n }\n}\n"]}
@@ -24,7 +24,7 @@ export class GeneratedClientContext extends coreClient.ServiceClient {
24
24
  const defaults = {
25
25
  requestContentType: "application/json; charset=utf-8"
26
26
  };
27
- const packageDetails = `azsdk-js-data-tables/13.0.2`;
27
+ const packageDetails = `azsdk-js-data-tables/13.1.0`;
28
28
  const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
29
29
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
30
30
  : `${packageDetails}`;
@@ -1 +1 @@
1
- {"version":3,"file":"generatedClientContext.js","sourceRoot":"","sources":["../../../src/generated/generatedClientContext.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AAGjD,gBAAgB;AAChB,MAAM,OAAO,sBAAuB,SAAQ,UAAU,CAAC,aAAa;IAIlE;;;;OAIG;IACH,YAAY,GAAW,EAAE,OAAuC;QAC9D,IAAI,GAAG,KAAK,SAAS,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;SACzC;QAED,0CAA0C;QAC1C,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,EAAE,CAAC;SACd;QACD,MAAM,QAAQ,GAAkC;YAC9C,kBAAkB,EAAE,iCAAiC;SACtD,CAAC;QAEF,MAAM,cAAc,GAAG,6BAA6B,CAAC;QACrD,MAAM,eAAe,GACnB,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,CAAC,eAAe;YAClE,CAAC,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,eAAe,IAAI,cAAc,EAAE;YACjE,CAAC,CAAC,GAAG,cAAc,EAAE,CAAC;QAE1B,MAAM,mBAAmB,iDACpB,QAAQ,GACR,OAAO,KACV,gBAAgB,EAAE;gBAChB,eAAe;aAChB,EACD,OAAO,EAAE,OAAO,CAAC,QAAQ,IAAI,OAAO,GACrC,CAAC;QACF,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC3B,wBAAwB;QACxB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QAEf,0CAA0C;QAC1C,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,YAAY,CAAC;IACjD,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport { GeneratedClientOptionalParams } from \"./models\";\n\n/** @internal */\nexport class GeneratedClientContext extends coreClient.ServiceClient {\n url: string;\n version: string;\n\n /**\n * Initializes a new instance of the GeneratedClientContext class.\n * @param url The URL of the service account or table that is the target of the desired operation.\n * @param options The parameter options\n */\n constructor(url: string, options?: GeneratedClientOptionalParams) {\n if (url === undefined) {\n throw new Error(\"'url' cannot be null\");\n }\n\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: GeneratedClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\"\n };\n\n const packageDetails = `azsdk-js-data-tables/13.0.2`;\n const userAgentPrefix =\n options.userAgentOptions && options.userAgentOptions.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const optionsWithDefaults = {\n ...defaults,\n ...options,\n userAgentOptions: {\n userAgentPrefix\n },\n baseUri: options.endpoint || \"{url}\"\n };\n super(optionsWithDefaults);\n // Parameter assignments\n this.url = url;\n\n // Assigning values to Constant parameters\n this.version = options.version || \"2019-02-02\";\n }\n}\n"]}
1
+ {"version":3,"file":"generatedClientContext.js","sourceRoot":"","sources":["../../../src/generated/generatedClientContext.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AAGjD,gBAAgB;AAChB,MAAM,OAAO,sBAAuB,SAAQ,UAAU,CAAC,aAAa;IAIlE;;;;OAIG;IACH,YAAY,GAAW,EAAE,OAAuC;QAC9D,IAAI,GAAG,KAAK,SAAS,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;SACzC;QAED,0CAA0C;QAC1C,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,EAAE,CAAC;SACd;QACD,MAAM,QAAQ,GAAkC;YAC9C,kBAAkB,EAAE,iCAAiC;SACtD,CAAC;QAEF,MAAM,cAAc,GAAG,6BAA6B,CAAC;QACrD,MAAM,eAAe,GACnB,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,CAAC,eAAe;YAClE,CAAC,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,eAAe,IAAI,cAAc,EAAE;YACjE,CAAC,CAAC,GAAG,cAAc,EAAE,CAAC;QAE1B,MAAM,mBAAmB,iDACpB,QAAQ,GACR,OAAO,KACV,gBAAgB,EAAE;gBAChB,eAAe;aAChB,EACD,OAAO,EAAE,OAAO,CAAC,QAAQ,IAAI,OAAO,GACrC,CAAC;QACF,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC3B,wBAAwB;QACxB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QAEf,0CAA0C;QAC1C,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,YAAY,CAAC;IACjD,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport { GeneratedClientOptionalParams } from \"./models\";\n\n/** @internal */\nexport class GeneratedClientContext extends coreClient.ServiceClient {\n url: string;\n version: string;\n\n /**\n * Initializes a new instance of the GeneratedClientContext class.\n * @param url The URL of the service account or table that is the target of the desired operation.\n * @param options The parameter options\n */\n constructor(url: string, options?: GeneratedClientOptionalParams) {\n if (url === undefined) {\n throw new Error(\"'url' cannot be null\");\n }\n\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: GeneratedClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\"\n };\n\n const packageDetails = `azsdk-js-data-tables/13.1.0`;\n const userAgentPrefix =\n options.userAgentOptions && options.userAgentOptions.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const optionsWithDefaults = {\n ...defaults,\n ...options,\n userAgentOptions: {\n userAgentPrefix\n },\n baseUri: options.endpoint || \"{url}\"\n };\n super(optionsWithDefaults);\n // Parameter assignments\n this.url = url;\n\n // Assigning values to Constant parameters\n this.version = options.version || \"2019-02-02\";\n }\n}\n"]}
@@ -0,0 +1,46 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ /**
4
+ * The programmatic identifier of the tablesSecondaryEndpointPolicy.
5
+ */
6
+ export const tablesSecondaryEndpointPolicyName = "tablesSecondaryEndpointPolicy";
7
+ export const SecondaryLocationHeaderName = "tables-secondary-endpoint";
8
+ const SecondaryLocationAccountSuffix = "-secondary";
9
+ /**
10
+ * Policy that would replace the Primary Endpoint with the secondary endpoint
11
+ * when the `tables-secondary-endpoint` is set in the request
12
+ */
13
+ export const tablesSecondaryEndpointPolicy = {
14
+ name: tablesSecondaryEndpointPolicyName,
15
+ sendRequest: async (req, next) => {
16
+ // Only replace the URL if the SecondaryLocationHeader is set
17
+ if (req.headers.get(SecondaryLocationHeaderName)) {
18
+ // Since the header is for internal use only, clean it up.
19
+ req.headers.delete(SecondaryLocationHeaderName);
20
+ // Calculate and update the secondary url
21
+ req.url = getSecondaryUrlFromPrimary(req.url);
22
+ }
23
+ return next(req);
24
+ },
25
+ };
26
+ /**
27
+ * Utility function that injects the SecondaryEndpointHeader into an operation options
28
+ */
29
+ export function injectSecondaryEndpointHeader(options) {
30
+ var _a;
31
+ const headerToInject = { [SecondaryLocationHeaderName]: "true" };
32
+ return Object.assign(Object.assign({}, options), { requestOptions: Object.assign(Object.assign({}, options.requestOptions), { customHeaders: Object.assign(Object.assign({}, (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders), headerToInject) }) });
33
+ }
34
+ /**
35
+ * Utility function that calculates the secondary URL for a table instance given the primary URL.
36
+ */
37
+ function getSecondaryUrlFromPrimary(primaryUrl) {
38
+ const parsedPrimaryUrl = new URL(primaryUrl);
39
+ const host = parsedPrimaryUrl.hostname.split(".");
40
+ if (host.length > 1) {
41
+ host[0] = `${host[0]}${SecondaryLocationAccountSuffix}`;
42
+ }
43
+ parsedPrimaryUrl.hostname = host.join(".");
44
+ return parsedPrimaryUrl.toString();
45
+ }
46
+ //# sourceMappingURL=secondaryEndpointPolicy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secondaryEndpointPolicy.js","sourceRoot":"","sources":["../../src/secondaryEndpointPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,+BAA+B,CAAC;AACjF,MAAM,CAAC,MAAM,2BAA2B,GAAG,2BAA2B,CAAC;AACvE,MAAM,8BAA8B,GAAG,YAAY,CAAC;AAEpD;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAmB;IAC3D,IAAI,EAAE,iCAAiC;IACvC,WAAW,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC/B,6DAA6D;QAC7D,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,EAAE;YAChD,0DAA0D;YAC1D,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;YAChD,yCAAyC;YACzC,GAAG,CAAC,GAAG,GAAG,0BAA0B,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;SAC/C;QAED,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC;CACF,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,6BAA6B,CAAC,OAAyB;;IACrE,MAAM,cAAc,GAAG,EAAE,CAAC,2BAA2B,CAAC,EAAE,MAAM,EAAE,CAAC;IACjE,uCACK,OAAO,KACV,cAAc,kCACT,OAAO,CAAC,cAAc,KACzB,aAAa,kCACR,MAAA,OAAO,CAAC,cAAc,0CAAE,aAAa,GACrC,cAAc,QAGrB;AACJ,CAAC;AAED;;GAEG;AACH,SAAS,0BAA0B,CAAC,UAAkB;IACpD,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAClD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;QACnB,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,8BAA8B,EAAE,CAAC;KACzD;IACD,gBAAgB,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE3C,OAAO,gBAAgB,CAAC,QAAQ,EAAE,CAAC;AACrC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationOptions } from \"@azure/core-client\";\nimport { PipelinePolicy } from \"@azure/core-rest-pipeline\";\n\n/**\n * The programmatic identifier of the tablesSecondaryEndpointPolicy.\n */\nexport const tablesSecondaryEndpointPolicyName = \"tablesSecondaryEndpointPolicy\";\nexport const SecondaryLocationHeaderName = \"tables-secondary-endpoint\";\nconst SecondaryLocationAccountSuffix = \"-secondary\";\n\n/**\n * Policy that would replace the Primary Endpoint with the secondary endpoint\n * when the `tables-secondary-endpoint` is set in the request\n */\nexport const tablesSecondaryEndpointPolicy: PipelinePolicy = {\n name: tablesSecondaryEndpointPolicyName,\n sendRequest: async (req, next) => {\n // Only replace the URL if the SecondaryLocationHeader is set\n if (req.headers.get(SecondaryLocationHeaderName)) {\n // Since the header is for internal use only, clean it up.\n req.headers.delete(SecondaryLocationHeaderName);\n // Calculate and update the secondary url\n req.url = getSecondaryUrlFromPrimary(req.url);\n }\n\n return next(req);\n },\n};\n\n/**\n * Utility function that injects the SecondaryEndpointHeader into an operation options\n */\nexport function injectSecondaryEndpointHeader(options: OperationOptions): OperationOptions {\n const headerToInject = { [SecondaryLocationHeaderName]: \"true\" };\n return {\n ...options,\n requestOptions: {\n ...options.requestOptions,\n customHeaders: {\n ...options.requestOptions?.customHeaders,\n ...headerToInject,\n },\n },\n };\n}\n\n/**\n * Utility function that calculates the secondary URL for a table instance given the primary URL.\n */\nfunction getSecondaryUrlFromPrimary(primaryUrl: string): string {\n const parsedPrimaryUrl = new URL(primaryUrl);\n const host = parsedPrimaryUrl.hostname.split(\".\");\n if (host.length > 1) {\n host[0] = `${host[0]}${SecondaryLocationAccountSuffix}`;\n }\n parsedPrimaryUrl.hostname = host.join(\".\");\n\n return parsedPrimaryUrl.toString();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"connectionString.js","sourceRoot":"","sources":["../../../src/utils/connectionString.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAEpG,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C,CAAC;IAClC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAElC,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,EAAE;QACrD,0EAA0E;QAC1E,uCAAuC;QACvC,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QACjD,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;KAClC;SAAM,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,EAAE;QAChC,iFAAiF;QACjF,2GAA2G;QAC3G,mCAAmC;QACnC,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;KAC5B;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;KAC7E;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ClientParamsFromConnectionString, ConnectionString } from \"./internalModels\";\nimport { fromAccountConnectionString, getAccountConnectionString } from \"./accountConnectionString\";\nimport { TableServiceClientOptions } from \"../models\";\nimport { URL } from \"./url\";\n\nconst DevelopmentConnectionString =\n \"DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1\";\n\n/**\n * This function parses a connection string into a set of\n * parameters to pass to be passed to TableClientService,\n * depending on the connection string type these parameter would\n * contain:\n * - Account Connection String: A pipeline to sign the request with a SharedKey\n * - SAS Connection String: Attach a SAS token to the storage account url for authentication\n * @param connectionString - Connection string to parse\n * @param options - TableService client options\n */\nexport function getClientParamsFromConnectionString(\n connectionString: string,\n options: TableServiceClientOptions = {}\n): ClientParamsFromConnectionString {\n if (connectionString.toLowerCase().indexOf(\"usedevelopmentstorage=true\") !== -1) {\n connectionString = DevelopmentConnectionString;\n options.allowInsecureConnection = true;\n }\n const extractedCreds = extractConnectionStringParts(connectionString);\n if (extractedCreds.kind === \"AccountConnString\") {\n return fromAccountConnectionString(extractedCreds, options);\n } else if (extractedCreds.kind === \"SASConnString\") {\n return {\n url: `${extractedCreds.url}?${extractedCreds.accountSas}`,\n options,\n };\n } else {\n throw new Error(\n \"Connection string must be either an Account connection string or a SAS connection string\"\n );\n }\n}\n\n/**\n * Extracts the parts of an Storage account connection string.\n *\n * @param connectionString - Connection string.\n * @returns String key value pairs of the storage account's url and credentials.\n */\nexport function extractConnectionStringParts(connectionString: string): ConnectionString {\n // Matching TableEndpoint in the Account connection string\n let tableEndpoint = getValueInConnString(connectionString, \"TableEndpoint\");\n // Slicing off '/' at the end if exists\n // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end)\n tableEndpoint = tableEndpoint.endsWith(\"/\") ? tableEndpoint.slice(0, -1) : tableEndpoint;\n\n if (isAccountConnectionString(connectionString)) {\n return getAccountConnectionString(\n getValueInConnString(connectionString, \"AccountName\"),\n getValueInConnString(connectionString, \"AccountKey\"),\n getValueInConnString(connectionString, \"DefaultEndpointsProtocol\"),\n getValueInConnString(connectionString, \"EndpointSuffix\"),\n tableEndpoint\n );\n } else {\n return getSASConnectionString(connectionString, tableEndpoint);\n }\n}\n\n/**\n * Checks whether a connection string is an Account Connection string or not\n */\nfunction isAccountConnectionString(connectionString: string) {\n const lowercaseConnectionString = connectionString.toLowerCase();\n return (\n lowercaseConnectionString.search(\"defaultendpointsprotocol=\") !== -1 &&\n lowercaseConnectionString.search(\"accountkey=\") !== -1\n );\n}\n\nfunction getSASConnectionString(connectionString: string, tableEndpoint: string): ConnectionString {\n const accountName = getAccountNameFromUrl(tableEndpoint);\n const accountSas = getValueInConnString(connectionString, \"SharedAccessSignature\");\n if (!tableEndpoint) {\n throw new Error(\"Invalid TableEndpoint in the provided SAS Connection String\");\n } else if (!accountSas) {\n throw new Error(\"Invalid SharedAccessSignature in the provided SAS Connection String\");\n } else if (!accountName) {\n throw new Error(\"Invalid AccountName in the provided SAS Connection String\");\n }\n\n return { kind: \"SASConnString\", url: tableEndpoint, accountName, accountSas };\n}\n\nfunction getValueInConnString(\n connectionString: string,\n argument:\n | \"TableEndpoint\"\n | \"AccountName\"\n | \"AccountKey\"\n | \"DefaultEndpointsProtocol\"\n | \"EndpointSuffix\"\n | \"SharedAccessSignature\"\n): string {\n const searchKey = argument.toLowerCase();\n const elements = connectionString.split(\";\").filter((e) => Boolean(e));\n for (const element of elements) {\n const trimmedElement = element.trim();\n const [elementKey, value] = getValuePair(trimmedElement);\n const key = elementKey.toLowerCase();\n if (key === searchKey) {\n return value;\n }\n }\n return \"\";\n}\n\nfunction getValuePair(kvp: string): string[] {\n // If the string is not in kvp format <key>=<valye> return an empty array\n if (!kvp || kvp.indexOf(\"=\") === -1) {\n return [];\n }\n // Get the substring before the first '='\n const key = kvp.substr(0, kvp.indexOf(\"=\"));\n // Get the substring after the first '='\n const value = kvp.substr(kvp.indexOf(\"=\") + 1);\n\n return [key, value];\n}\n\n/**\n * Extracts account name from the url\n * @param url - URL to extract the account name from\n * @returns The account name\n */\nfunction getAccountNameFromUrl(url: string): string {\n if (!url) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n let accountName;\n\n const host = parsedUrl.host || \"\";\n const path = parsedUrl.pathname || \"\";\n const hostParts = host.split(\".\");\n const pathParts = path.split(\"/\");\n\n if (hostParts.length >= 1 && hostParts[1] === \"table\") {\n // `${defaultEndpointsProtocol}://${accountName}.table.${endpointSuffix}`;\n // Slicing off '/' at the end if exists\n url = url.endsWith(\"/\") ? url.slice(0, -1) : url;\n accountName = host.split(\".\")[0];\n } else if (pathParts.length >= 1) {\n // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/\n // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/\n // .getPath() -> /devstoreaccount1/\n accountName = pathParts[1];\n } else {\n throw new Error(\"Unable to extract accountName with provided information.\");\n }\n\n return accountName;\n}\n"]}
1
+ {"version":3,"file":"connectionString.js","sourceRoot":"","sources":["../../../src/utils/connectionString.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAGpG,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B,MAAM,2BAA2B,GAC/B,sNAAsN,CAAC;AAEzN;;;;;;;;;GASG;AACH,MAAM,UAAU,mCAAmC,CACjD,gBAAwB,EACxB,UAAqC,EAAE;IAEvC,IAAI,gBAAgB,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,4BAA4B,CAAC,KAAK,CAAC,CAAC,EAAE;QAC/E,gBAAgB,GAAG,2BAA2B,CAAC;QAC/C,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC;KACxC;IACD,MAAM,cAAc,GAAG,4BAA4B,CAAC,gBAAgB,CAAC,CAAC;IACtE,IAAI,cAAc,CAAC,IAAI,KAAK,mBAAmB,EAAE;QAC/C,OAAO,2BAA2B,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;KAC7D;SAAM,IAAI,cAAc,CAAC,IAAI,KAAK,eAAe,EAAE;QAClD,OAAO;YACL,GAAG,EAAE,GAAG,cAAc,CAAC,GAAG,IAAI,cAAc,CAAC,UAAU,EAAE;YACzD,OAAO;SACR,CAAC;KACH;SAAM;QACL,MAAM,IAAI,KAAK,CACb,0FAA0F,CAC3F,CAAC;KACH;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAAC,gBAAwB;IACnE,0DAA0D;IAC1D,IAAI,aAAa,GAAG,o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;AACtB,CAAC;AAED;;;;GAIG;AACH,SAAS,qBAAqB,CAAC,GAAW;IACxC,IAAI,CAAC,GAAG,EAAE;QACR,OAAO,GAAG,CAAC;KACZ;IAED,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,WAAW,CAAC;IAEhB,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,IAAI,EAAE,CAAC;IACtC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAElC,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,EAAE;QACrD,0EAA0E;QAC1E,uCAAuC;QACvC,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QACjD,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;KAClC;SAAM,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,EAAE;QAChC,iFAAiF;QACjF,2GAA2G;QAC3G,mCAAmC;QACnC,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;KAC5B;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;KAC7E;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ClientParamsFromConnectionString, ConnectionString } from \"./internalModels\";\nimport { fromAccountConnectionString, getAccountConnectionString } from \"./accountConnectionString\";\n\nimport { TableServiceClientOptions } from \"../models\";\nimport { URL } from \"./url\";\n\nconst DevelopmentConnectionString =\n \"DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1\";\n\n/**\n * This function parses a connection string into a set of\n * parameters to pass to be passed to TableClientService,\n * depending on the connection string type these parameter would\n * contain:\n * - Account Connection String: A pipeline to sign the request with a SharedKey\n * - SAS Connection String: Attach a SAS token to the storage account url for authentication\n * @param connectionString - Connection string to parse\n * @param options - TableService client options\n */\nexport function getClientParamsFromConnectionString(\n connectionString: string,\n options: TableServiceClientOptions = {}\n): ClientParamsFromConnectionString {\n if (connectionString.toLowerCase().indexOf(\"usedevelopmentstorage=true\") !== -1) {\n connectionString = DevelopmentConnectionString;\n options.allowInsecureConnection = true;\n }\n const extractedCreds = extractConnectionStringParts(connectionString);\n if (extractedCreds.kind === \"AccountConnString\") {\n return fromAccountConnectionString(extractedCreds, options);\n } else if (extractedCreds.kind === \"SASConnString\") {\n return {\n url: `${extractedCreds.url}?${extractedCreds.accountSas}`,\n options,\n };\n } else {\n throw new Error(\n \"Connection string must be either an Account connection string or a SAS connection string\"\n );\n }\n}\n\n/**\n * Extracts the parts of an Storage account connection string.\n *\n * @param connectionString - Connection string.\n * @returns String key value pairs of the storage account's url and credentials.\n */\nexport function extractConnectionStringParts(connectionString: string): ConnectionString {\n // Matching TableEndpoint in the Account connection string\n let tableEndpoint = getValueInConnString(connectionString, \"TableEndpoint\");\n // Slicing off '/' at the end if exists\n // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end)\n tableEndpoint = tableEndpoint.endsWith(\"/\") ? tableEndpoint.slice(0, -1) : tableEndpoint;\n\n if (isAccountConnectionString(connectionString)) {\n return getAccountConnectionString(\n getValueInConnString(connectionString, \"AccountName\"),\n getValueInConnString(connectionString, \"AccountKey\"),\n getValueInConnString(connectionString, \"DefaultEndpointsProtocol\"),\n getValueInConnString(connectionString, \"EndpointSuffix\"),\n tableEndpoint\n );\n } else {\n return getSASConnectionString(connectionString, tableEndpoint);\n }\n}\n\n/**\n * Checks whether a connection string is an Account Connection string or not\n */\nfunction isAccountConnectionString(connectionString: string) {\n const lowercaseConnectionString = connectionString.toLowerCase();\n return (\n lowercaseConnectionString.search(\"defaultendpointsprotocol=\") !== -1 &&\n lowercaseConnectionString.search(\"accountkey=\") !== -1\n );\n}\n\nfunction getSASConnectionString(connectionString: string, tableEndpoint: string): ConnectionString {\n const accountName = getAccountNameFromUrl(tableEndpoint);\n const accountSas = getValueInConnString(connectionString, \"SharedAccessSignature\");\n if (!tableEndpoint) {\n throw new Error(\"Invalid TableEndpoint in the provided SAS Connection String\");\n } else if (!accountSas) {\n throw new Error(\"Invalid SharedAccessSignature in the provided SAS Connection String\");\n } else if (!accountName) {\n throw new Error(\"Invalid AccountName in the provided SAS Connection String\");\n }\n\n return { kind: \"SASConnString\", url: tableEndpoint, accountName, accountSas };\n}\n\nfunction getValueInConnString(\n connectionString: string,\n argument:\n | \"TableEndpoint\"\n | \"AccountName\"\n | \"AccountKey\"\n | \"DefaultEndpointsProtocol\"\n | \"EndpointSuffix\"\n | \"SharedAccessSignature\"\n): string {\n const searchKey = argument.toLowerCase();\n const elements = connectionString.split(\";\").filter((e) => Boolean(e));\n for (const element of elements) {\n const trimmedElement = element.trim();\n const [elementKey, value] = getValuePair(trimmedElement);\n const key = elementKey.toLowerCase();\n if (key === searchKey) {\n return value;\n }\n }\n return \"\";\n}\n\nfunction getValuePair(kvp: string): string[] {\n // If the string is not in kvp format <key>=<valye> return an empty array\n if (!kvp || kvp.indexOf(\"=\") === -1) {\n return [];\n }\n // Get the substring before the first '='\n const key = kvp.substr(0, kvp.indexOf(\"=\"));\n // Get the substring after the first '='\n const value = kvp.substr(kvp.indexOf(\"=\") + 1);\n\n return [key, value];\n}\n\n/**\n * Extracts account name from the url\n * @param url - URL to extract the account name from\n * @returns The account name\n */\nfunction getAccountNameFromUrl(url: string): string {\n if (!url) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n let accountName;\n\n const host = parsedUrl.host || \"\";\n const path = parsedUrl.pathname || \"\";\n const hostParts = host.split(\".\");\n const pathParts = path.split(\"/\");\n\n if (hostParts.length >= 1 && hostParts[1] === \"table\") {\n // `${defaultEndpointsProtocol}://${accountName}.table.${endpointSuffix}`;\n // Slicing off '/' at the end if exists\n url = url.endsWith(\"/\") ? url.slice(0, -1) : url;\n accountName = host.split(\".\")[0];\n } else if (pathParts.length >= 1) {\n // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/\n // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/\n // .getPath() -> /devstoreaccount1/\n accountName = pathParts[1];\n } else {\n throw new Error(\"Unable to extract accountName with provided information.\");\n }\n\n return accountName;\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
- import { SpanStatusCode } from "@azure/core-tracing";
4
3
  export function handleTableAlreadyExists(error, options = {}) {
5
- var _a, _b, _c;
4
+ var _a, _b;
6
5
  const responseError = getErrorResponse(error);
7
6
  if (responseError &&
8
7
  responseError.status === 409 &&
@@ -13,7 +12,6 @@ export function handleTableAlreadyExists(error, options = {}) {
13
12
  }
14
13
  }
15
14
  else {
16
- options === null || options === void 0 ? void 0 : options.span.setStatus({ code: SpanStatusCode.ERROR, message: (_c = error) === null || _c === void 0 ? void 0 : _c.message });
17
15
  throw error;
18
16
  }
19
17
  }