UNPKG

@azure/data-tables

Version:

An isomorphic client library for the Azure Tables service.

1,484 lines (1,463 loc) 179 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tslib = require('tslib'); var coreAuth = require('@azure/core-auth'); var coreXml = require('@azure/core-xml'); var coreClient = require('@azure/core-client'); var logger$1 = require('@azure/logger'); var coreRestPipeline = require('@azure/core-rest-pipeline'); var crypto = require('crypto'); var coreTracing = require('@azure/core-tracing'); var coreUtil = require('@azure/core-util'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient); /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Known values of {@link OdataMetadataFormat} that the service accepts. */ var KnownOdataMetadataFormat; (function (KnownOdataMetadataFormat) { KnownOdataMetadataFormat["ApplicationJsonOdataNometadata"] = "application/json;odata=nometadata"; KnownOdataMetadataFormat["ApplicationJsonOdataMinimalmetadata"] = "application/json;odata=minimalmetadata"; KnownOdataMetadataFormat["ApplicationJsonOdataFullmetadata"] = "application/json;odata=fullmetadata"; })(KnownOdataMetadataFormat || (KnownOdataMetadataFormat = {})); /** Known values of {@link ResponseFormat} that the service accepts. */ var KnownResponseFormat; (function (KnownResponseFormat) { KnownResponseFormat["ReturnNoContent"] = "return-no-content"; KnownResponseFormat["ReturnContent"] = "return-content"; })(KnownResponseFormat || (KnownResponseFormat = {})); /** Known values of {@link GeoReplicationStatusType} that the service accepts. */ exports.KnownGeoReplicationStatusType = void 0; (function (KnownGeoReplicationStatusType) { KnownGeoReplicationStatusType["Live"] = "live"; KnownGeoReplicationStatusType["Bootstrap"] = "bootstrap"; KnownGeoReplicationStatusType["Unavailable"] = "unavailable"; })(exports.KnownGeoReplicationStatusType || (exports.KnownGeoReplicationStatusType = {})); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Parse initializes the AccountSASPermissions fields from a string. * * @param permissions - */ function accountSasPermissionsFromString(permissions) { const accountSasPermissions = {}; for (const c of permissions) { switch (c) { case "r": accountSasPermissions.query = true; break; case "w": accountSasPermissions.write = true; break; case "d": accountSasPermissions.delete = true; break; case "l": accountSasPermissions.list = true; break; case "a": accountSasPermissions.add = true; break; case "u": accountSasPermissions.update = true; break; default: throw new RangeError(`Invalid permission character: ${c}`); } } return accountSasPermissions; } /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. * * Using this method will guarantee the resource types are in * an order accepted by the service. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ function accountSasPermissionsToString(permissions) { // The order of the characters should be as specified here to ensure correctness: // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas // Use a string array instead of string concatenating += operator for performance const permissionString = []; if (permissions.query) { permissionString.push("r"); } if (permissions.write) { permissionString.push("w"); } if (permissions.delete) { permissionString.push("d"); } if (permissions.list) { permissionString.push("l"); } if (permissions.add) { permissionString.push("a"); } if (permissions.update) { permissionString.push("u"); } return permissionString.join(""); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Creates an {@link AccountSasServices} from the specified services string. This method will throw an * Error if it encounters a character that does not correspond to a valid service. * * @param services - */ function accountSasServicesFromString(services) { const accountSasServices = {}; for (const c of services) { switch (c) { case "b": accountSasServices.blob = true; break; case "f": accountSasServices.file = true; break; case "q": accountSasServices.queue = true; break; case "t": accountSasServices.table = true; break; default: throw new RangeError(`Invalid service character: ${c}`); } } return accountSasServices; } /** * Converts the given services to a string. * */ function accountSasServicesToString(services = { table: true }) { const servicesString = []; if (services.blob) { servicesString.push("b"); } if (services.table) { servicesString.push("t"); } if (services.queue) { servicesString.push("q"); } if (services.file) { servicesString.push("f"); } return servicesString.join(""); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Generate SasIPRange format string. For example: * * "8.8.8.8" or "1.1.1.1-255.255.255.255" * * @param ipRange - */ function ipRangeToString(ipRange) { if (!ipRange) { return ""; } return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Rounds a date off to seconds. * * @param date - * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns Date string in ISO8061 format, with or without 7 milliseconds component */ function truncatedISO8061Date(date, withMilliseconds = true) { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Represents the components that make up an Azure SAS' query parameters. This type is not constructed directly * by the user; it is only generated by the {@link AccountSasSignatureValues} and {@link TableSasSignatureValues} * types. Once generated, it can be encoded into a `string` and appended to a URL directly (though caution should * be taken here in case there are existing query parameters, which might affect the appropriate means of appending * these query parameters). * * NOTE: Instances of this class are immutable. */ class SasQueryParameters { /** * Optional. IP range allowed for this SAS. * * @readonly */ get ipRange() { if (this.ipRangeInner) { return { end: this.ipRangeInner.end, start: this.ipRangeInner.start, }; } return undefined; } /** * Creates an instance of SASQueryParameters. * * @param version - Representing the table service version * @param signature - Representing the signature for the SAS token * @param options - Optional. Options to construct the SASQueryParameters. */ constructor(version, signature, options = {}) { this.version = version; this.signature = signature; this.permissions = options.permissions; this.services = options.services; this.resourceTypes = options.resourceTypes; this.protocol = options.protocol; this.startsOn = options.startsOn; this.expiresOn = options.expiresOn; this.ipRangeInner = options.ipRange; this.identifier = options.identifier; this.tableName = options.tableName; this.endPartitionKey = options.endPartitionKey; this.endRowKey = options.endRowKey; this.startPartitionKey = options.startPartitionKey; this.startRowKey = options.startRowKey; if (options.userDelegationKey) { this.signedOid = options.userDelegationKey.signedObjectId; this.signedTenantId = options.userDelegationKey.signedTenantId; this.signedStartsOn = options.userDelegationKey.signedStartsOn; this.signedExpiresOn = options.userDelegationKey.signedExpiresOn; this.signedService = options.userDelegationKey.signedService; this.signedVersion = options.userDelegationKey.signedVersion; this.preauthorizedAgentObjectId = options.preauthorizedAgentObjectId; this.correlationId = options.correlationId; } } /** * Encodes all SAS query parameters into a string that can be appended to a URL. * */ toString() { const params = [ "sv", // SignedVersion "ss", // SignedServices "srt", // SignedResourceTypes "spr", // SignedProtocol "st", // SignedStart "se", // SignedExpiry "sip", // SignedIP "si", // SignedIdentifier "skoid", // Signed object ID "sktid", // Signed tenant ID "skt", // Signed key start time "ske", // Signed key expiry time "sks", // Signed key service "skv", // Signed key version "sr", // signedResource "sp", // SignedPermission "sig", // Signature "rscc", // Cache-Control "rscd", // Content-Disposition "rsce", // Content-Encoding "rscl", // Content-Language "rsct", // Content-Type "saoid", // signedAuthorizedObjectId "scid", // signedCorrelationId "tn", // TableName, "srk", // StartRowKey "spk", // StartPartitionKey "epk", // EndPartitionKey "erk", // EndRowKey ]; const queries = []; for (const param of params) { switch (param) { case "sv": this.tryAppendQueryParameter(queries, param, this.version); break; case "ss": this.tryAppendQueryParameter(queries, param, this.services); break; case "srt": this.tryAppendQueryParameter(queries, param, this.resourceTypes); break; case "spr": this.tryAppendQueryParameter(queries, param, this.protocol); break; case "st": this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); break; case "se": this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); break; case "sip": this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); break; case "si": this.tryAppendQueryParameter(queries, param, this.identifier); break; case "skoid": // Signed object ID this.tryAppendQueryParameter(queries, param, this.signedOid); break; case "sktid": // Signed tenant ID this.tryAppendQueryParameter(queries, param, this.signedTenantId); break; case "skt": // Signed key start time this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); break; case "ske": // Signed key expiry time this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); break; case "sks": // Signed key service this.tryAppendQueryParameter(queries, param, this.signedService); break; case "skv": // Signed key version this.tryAppendQueryParameter(queries, param, this.signedVersion); break; case "sp": this.tryAppendQueryParameter(queries, param, this.permissions); break; case "sig": this.tryAppendQueryParameter(queries, param, this.signature); break; case "saoid": this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); break; case "scid": this.tryAppendQueryParameter(queries, param, this.correlationId); break; case "tn": this.tryAppendQueryParameter(queries, param, this.tableName); break; case "spk": this.tryAppendQueryParameter(queries, param, this.startPartitionKey); break; case "srk": this.tryAppendQueryParameter(queries, param, this.startRowKey); break; case "epk": this.tryAppendQueryParameter(queries, param, this.endPartitionKey); break; case "erk": this.tryAppendQueryParameter(queries, param, this.endRowKey); break; } } return queries.join("&"); } /** * A private helper method used to filter and append query key/value pairs into an array. * * @param queries - * @param key - * @param value - */ tryAppendQueryParameter(queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { queries.push(`${key}=${value}`); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Creates an {@link accountSasResourceTypesFromString} from the specified resource types string. This method will throw an * Error if it encounters a character that does not correspond to a valid resource type. * * @param resourceTypes - */ function accountSasResourceTypesFromString(resourceTypes) { const accountSasResourceTypes = {}; for (const c of resourceTypes) { switch (c) { case "s": accountSasResourceTypes.service = true; break; case "c": accountSasResourceTypes.container = true; break; case "o": accountSasResourceTypes.object = true; break; default: throw new RangeError(`Invalid resource type: ${c}`); } } return accountSasResourceTypes; } /** * Converts the given resource types to a string. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ function accountSasResourceTypesToString(resourceTypes) { const resourceTypesString = []; if (resourceTypes.service) { resourceTypesString.push("s"); } if (resourceTypes.container) { resourceTypesString.push("c"); } if (resourceTypes.object) { resourceTypesString.push("o"); } return resourceTypesString.join(""); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. const SERVICE_VERSION = "2019-02-02"; const TRANSACTION_HTTP_VERSION_1_1 = "HTTP/1.1"; const TRANSACTION_HTTP_LINE_ENDING = "\r\n"; const STORAGE_SCOPE = "https://storage.azure.com/.default"; const COSMOS_SCOPE = "https://cosmos.azure.com/.default"; const HeaderConstants = { AUTHORIZATION: "authorization", CONTENT_LENGTH: "content-length", CONTENT_MD5: "content-md5", CONTENT_TYPE: "content-type", CONTENT_TRANSFER_ENCODING: "content-transfer-encoding", DATE: "date", X_MS_DATE: "x-ms-date", X_MS_VERSION: "x-ms-version", }; const TablesLoggingAllowedHeaderNames = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", "Content-Type", "Date", "Prefer", "Preference-Applied", "Request-Id", "traceparent", "Transfer-Encoding", "User-Agent", "x-ms-client-request-id", "x-ms-user-agent", "x-ms-date", "x-ms-error-code", "x-ms-request-id", "x-ms-return-client-request-id", "x-ms-version", "Accept-Ranges", "Accept", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-MD5", "Content-Range", "ETag", "Last-Modified", "Server", "Vary", "x-ms-content-crc64", "x-ms-copy-action", "x-ms-copy-completion-time", "x-ms-copy-id", "x-ms-copy-progress", "x-ms-copy-status", "x-ms-continuation-NextTableName", "x-ms-continuation-NextPartitionKey", "x-ms-continuation-NextRowKey", "x-ms-has-immutability-policy", "x-ms-has-legal-hold", "x-ms-lease-state", "x-ms-lease-status", "x-ms-range", "x-ms-request-server-encrypted", "x-ms-server-encrypted", "x-ms-snapshot", "x-ms-source-range", "If-Match", "If-Modified-Since", "If-None-Match", "If-Unmodified-Since", "x-ms-access-tier", "x-ms-access-tier-change-time", "x-ms-access-tier-inferred", "x-ms-account-kind", "x-ms-archive-status", "x-ms-copy-destination-snapshot", "x-ms-creation-time", "x-ms-default-encryption-scope", "x-ms-delete-type-permanent", "x-ms-deny-encryption-scope-override", "x-ms-encryption-algorithm", "x-ms-incremental-copy", "x-ms-lease-action", "x-ms-lease-break-period", "x-ms-lease-duration", "x-ms-lease-id", "x-ms-lease-time", "x-ms-page-write", "x-ms-proposed-lease-id", "x-ms-range-get-content-md5", "x-ms-rehydrate-priority", "x-ms-sequence-number-action", "x-ms-sku-name", "x-ms-source-content-md5", "x-ms-source-if-match", "x-ms-source-if-modified-since", "x-ms-source-if-none-match", "x-ms-source-if-unmodified-since", "x-ms-tag-count", "x-ms-encryption-key-sha256", ]; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. function computeHMACSHA256(stringToSign, accountKey) { const key = Buffer.from(accountKey, "base64"); return crypto.createHmac("sha256", key).update(stringToSign, "utf8").digest("base64"); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Generates a {@link SasQueryParameters} object which contains all SAS query parameters needed to make an actual * REST request. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @param accountSasSignatureValues - * @param sharedKeyCredential - */ function generateAccountSasQueryParameters(accountSasSignatureValues, credential) { const version = accountSasSignatureValues.version ? accountSasSignatureValues.version : SERVICE_VERSION; const parsedPermissions = accountSasPermissionsToString(accountSasSignatureValues.permissions); const parsedServices = accountSasServicesToString(accountSasServicesFromString(accountSasSignatureValues.services)); // to and from string to guarantee the correct order of resoruce types is generated const parsedResourceTypes = accountSasResourceTypesToString(accountSasResourceTypesFromString(accountSasSignatureValues.resourceTypes)); const stringToSign = [ credential.name, parsedPermissions, parsedServices, parsedResourceTypes, accountSasSignatureValues.startsOn ? truncatedISO8061Date(accountSasSignatureValues.startsOn, false) : "", truncatedISO8061Date(accountSasSignatureValues.expiresOn, false), accountSasSignatureValues.ipRange ? ipRangeToString(accountSasSignatureValues.ipRange) : "", accountSasSignatureValues.protocol ? accountSasSignatureValues.protocol : "", version, "", // Account SAS requires an additional newline character ].join("\n"); const signature = computeHMACSHA256(stringToSign, credential.key); return new SasQueryParameters(version, signature, { permissions: parsedPermissions.toString(), services: parsedServices, resourceTypes: parsedResourceTypes, protocol: accountSasSignatureValues.protocol, startsOn: accountSasSignatureValues.startsOn, expiresOn: accountSasSignatureValues.expiresOn, ipRange: accountSasSignatureValues.ipRange, }); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Generates a Table Account Shared Access Signature (SAS) URI based on the client properties * and parameters passed in. The SAS is signed by the shared key credential of the client. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas * * @param options - Optional parameters. * @returns An account SAS token */ function generateAccountSas(credential, options = {}) { const { expiresOn, permissions = accountSasPermissionsFromString("rl"), resourceTypes = "sco", services = accountSasServicesFromString("t") } = options, rest = tslib.__rest(options, ["expiresOn", "permissions", "resourceTypes", "services"]); if (!coreAuth.isNamedKeyCredential(credential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } let expiry = expiresOn; if (expiry === undefined) { const now = new Date(); expiry = new Date(now.getTime() + 3600 * 1000); } const sas = generateAccountSasQueryParameters(Object.assign({ permissions, expiresOn: expiry, resourceTypes, services: accountSasServicesToString(services) }, rest), credential).toString(); return sas; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Creates a {@link TableSasPermissions} from the specified permissions string. This method will throw an * Error if it encounters a character that does not correspond to a valid permission. * * @param permissions - */ function tableSasPermissionsFromString(permissions) { const tableSasPermissions = {}; for (const char of permissions) { switch (char) { case "r": tableSasPermissions.query = true; break; case "a": tableSasPermissions.add = true; break; case "u": tableSasPermissions.update = true; break; case "d": tableSasPermissions.delete = true; break; default: throw new RangeError(`Invalid permission: ${char}`); } } return tableSasPermissions; } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns A string which represents the TableSasPermissions */ function tableSasPermissionsToString(permissions) { if (!permissions) { return ""; } const permissionsString = []; if (permissions.query) { permissionsString.push("r"); } if (permissions.add) { permissionsString.push("a"); } if (permissions.update) { permissionsString.push("u"); } if (permissions.delete) { permissionsString.push("d"); } return permissionsString.join(""); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Creates an instance of SASQueryParameters. * * **Note**: When identifier is not provided, permissions has a default value of "read" and expiresOn of one hour from the time the token is generated. */ function generateTableSasQueryParameters(tableName, credential, tableSasSignatureValues) { var _a, _b, _c, _d, _e, _f; const version = (_a = tableSasSignatureValues.version) !== null && _a !== void 0 ? _a : SERVICE_VERSION; if (credential === undefined) { throw TypeError("Invalid NamedKeyCredential"); } if (!tableName) { throw new Error("Must provide a 'tableName'"); } const signedPermissions = tableSasPermissionsToString(tableSasSignatureValues.permissions); const signedStart = tableSasSignatureValues.startsOn ? truncatedISO8061Date(tableSasSignatureValues.startsOn, false /** withMilliseconds */) : ""; const signedExpiry = tableSasSignatureValues.expiresOn ? truncatedISO8061Date(tableSasSignatureValues.expiresOn, false /** withMilliseconds */) : ""; const canonicalizedResource = getCanonicalName(credential.name, tableName); const signedIdentifier = (_b = tableSasSignatureValues.identifier) !== null && _b !== void 0 ? _b : ""; const signedIP = ipRangeToString(tableSasSignatureValues.ipRange); const signedProtocol = tableSasSignatureValues.protocol || ""; const startingPartitionKey = (_c = tableSasSignatureValues.startPartitionKey) !== null && _c !== void 0 ? _c : ""; const startingRowKey = (_d = tableSasSignatureValues.startRowKey) !== null && _d !== void 0 ? _d : ""; const endingPartitionKey = (_e = tableSasSignatureValues.endPartitionKey) !== null && _e !== void 0 ? _e : ""; const endingRowKey = (_f = tableSasSignatureValues.endRowKey) !== null && _f !== void 0 ? _f : ""; const stringToSign = [ signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, signedProtocol, version, startingPartitionKey, startingRowKey, endingPartitionKey, endingRowKey, ].join("\n"); const signature = computeHMACSHA256(stringToSign, credential.key); return new SasQueryParameters(version, signature, { permissions: signedPermissions, protocol: tableSasSignatureValues.protocol, startsOn: tableSasSignatureValues.startsOn, expiresOn: tableSasSignatureValues.expiresOn, ipRange: tableSasSignatureValues.ipRange, identifier: tableSasSignatureValues.identifier, tableName, startPartitionKey: tableSasSignatureValues.startPartitionKey, startRowKey: tableSasSignatureValues.startRowKey, endPartitionKey: tableSasSignatureValues.endPartitionKey, endRowKey: tableSasSignatureValues.endRowKey, }); } function getCanonicalName(accountName, tableName) { // Sample CanonicalName for URL = https://myaccount.table.core.windows.net/Employees(PartitionKey='Jeff',RowKey='Price'): // canonicalizedResource = "/table/myaccount/employees" return `/table/${accountName}/${tableName.toLowerCase()}`; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * Generates a Table Service Shared Access Signature (SAS) URI based on the client properties * and parameters passed in. The SAS is signed by the shared key credential of the client. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ function generateTableSas(tableName, credential, options = {}) { let { expiresOn, permissions } = options; if (!coreAuth.isNamedKeyCredential(credential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } // expiresOn and permissions are optional if an identifier is provided // set defaults when no identifier and no values were provided if (!options.identifier) { if (!permissions) { permissions = tableSasPermissionsFromString("r"); } if (expiresOn === undefined) { const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } } const sas = generateTableSasQueryParameters(tableName, credential, Object.assign(Object.assign({}, options), { expiresOn, permissions })).toString(); return sas; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /** * The programmatic identifier of the tablesSecondaryEndpointPolicy. */ const tablesSecondaryEndpointPolicyName = "tablesSecondaryEndpointPolicy"; const SecondaryLocationHeaderName = "tables-secondary-endpoint"; const SecondaryLocationAccountSuffix = "-secondary"; /** * Policy that would replace the Primary Endpoint with the secondary endpoint * when the `tables-secondary-endpoint` is set in the request */ const tablesSecondaryEndpointPolicy = { name: tablesSecondaryEndpointPolicyName, sendRequest: async (req, next) => { // Only replace the URL if the SecondaryLocationHeader is set if (req.headers.get(SecondaryLocationHeaderName)) { // Since the header is for internal use only, clean it up. req.headers.delete(SecondaryLocationHeaderName); // Calculate and update the secondary url req.url = getSecondaryUrlFromPrimary(req.url); } return next(req); }, }; /** * Utility function that injects the SecondaryEndpointHeader into an operation options */ function injectSecondaryEndpointHeader(options) { var _a; const headerToInject = { [SecondaryLocationHeaderName]: "true" }; 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) }) }); } /** * Utility function that calculates the secondary URL for a table instance given the primary URL. */ function getSecondaryUrlFromPrimary(primaryUrl) { const parsedPrimaryUrl = new URL(primaryUrl); const host = parsedPrimaryUrl.hostname.split("."); if (host.length > 1) { host[0] = `${host[0]}${SecondaryLocationAccountSuffix}`; } parsedPrimaryUrl.hostname = host.join("."); return parsedPrimaryUrl.toString(); } /* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ const TableQueryResponse = { serializedName: "TableQueryResponse", type: { name: "Composite", className: "TableQueryResponse", modelProperties: { odataMetadata: { serializedName: "odata\\.metadata", xmlName: "odata\\.metadata", type: { name: "String" } }, value: { serializedName: "value", xmlName: "value", xmlElementName: "TableResponseProperties", type: { name: "Sequence", element: { type: { name: "Composite", className: "TableResponseProperties" } } } } } } }; const TableResponseProperties = { serializedName: "TableResponseProperties", type: { name: "Composite", className: "TableResponseProperties", modelProperties: { name: { serializedName: "TableName", xmlName: "TableName", type: { name: "String" } }, odataType: { serializedName: "odata\\.type", xmlName: "odata\\.type", type: { name: "String" } }, odataId: { serializedName: "odata\\.id", xmlName: "odata\\.id", type: { name: "String" } }, odataEditLink: { serializedName: "odata\\.editLink", xmlName: "odata\\.editLink", type: { name: "String" } } } } }; const TableServiceError = { serializedName: "TableServiceError", type: { name: "Composite", className: "TableServiceError", modelProperties: { odataError: { serializedName: "odata\\.error", xmlName: "odata\\.error", type: { name: "Composite", className: "TableServiceErrorOdataError" } } } } }; const TableServiceErrorOdataError = { serializedName: "TableServiceErrorOdataError", type: { name: "Composite", className: "TableServiceErrorOdataError", modelProperties: { code: { serializedName: "code", xmlName: "code", type: { name: "String" } }, message: { serializedName: "message", xmlName: "message", type: { name: "Composite", className: "TableServiceErrorOdataErrorMessage" } } } } }; const TableServiceErrorOdataErrorMessage = { serializedName: "TableServiceErrorOdataErrorMessage", type: { name: "Composite", className: "TableServiceErrorOdataErrorMessage", modelProperties: { lang: { serializedName: "lang", xmlName: "lang", type: { name: "String" } }, value: { serializedName: "value", xmlName: "value", type: { name: "String" } } } } }; const TableProperties = { serializedName: "TableProperties", type: { name: "Composite", className: "TableProperties", modelProperties: { name: { serializedName: "TableName", xmlName: "TableName", type: { name: "String" } } } } }; const TableEntityQueryResponse = { serializedName: "TableEntityQueryResponse", type: { name: "Composite", className: "TableEntityQueryResponse", modelProperties: { odataMetadata: { serializedName: "odata\\.metadata", xmlName: "odata\\.metadata", type: { name: "String" } }, value: { serializedName: "value", xmlName: "value", xmlElementName: "TableEntityProperties", type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "any" } } } } } } } } }; const SignedIdentifier = { serializedName: "SignedIdentifier", xmlName: "SignedIdentifier", type: { name: "Composite", className: "SignedIdentifier", modelProperties: { id: { serializedName: "Id", required: true, xmlName: "Id", type: { name: "String" } }, accessPolicy: { serializedName: "AccessPolicy", xmlName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy" } } } } }; const AccessPolicy = { serializedName: "AccessPolicy", xmlName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy", modelProperties: { start: { serializedName: "Start", xmlName: "Start", type: { name: "String" } }, expiry: { serializedName: "Expiry", xmlName: "Expiry", type: { name: "String" } }, permission: { serializedName: "Permission", xmlName: "Permission", type: { name: "String" } } } } }; const TableServiceProperties = { serializedName: "TableServiceProperties", xmlName: "StorageServiceProperties", type: { name: "Composite", className: "TableServiceProperties", modelProperties: { logging: { serializedName: "Logging", xmlName: "Logging", type: { name: "Composite", className: "Logging" } }, hourMetrics: { serializedName: "HourMetrics", xmlName: "HourMetrics", type: { name: "Composite", className: "Metrics" } }, minuteMetrics: { serializedName: "MinuteMetrics", xmlName: "MinuteMetrics", type: { name: "Composite", className: "Metrics" } }, cors: { serializedName: "Cors", xmlName: "Cors", xmlIsWrapped: true, xmlElementName: "CorsRule", type: { name: "Sequence", element: { type: { name: "Composite", className: "CorsRule" } } } } } } }; const Logging = { serializedName: "Logging", xmlName: "Logging", type: { name: "Composite", className: "Logging", modelProperties: { version: { serializedName: "Version", required: true, xmlName: "Version", type: { name: "String" } }, delete: { serializedName: "Delete", required: true, xmlName: "Delete", type: { name: "Boolean" } }, read: { serializedName: "Read", required: true, xmlName: "Read", type: { name: "Boolean" } }, write: { serializedName: "Write", required: true, xmlName: "Write", type: { name: "Boolean" } }, retentionPolicy: { serializedName: "RetentionPolicy", xmlName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy" } } } } }; const RetentionPolicy = { serializedName: "RetentionPolicy", xmlName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", modelProperties: { enabled: { serializedName: "Enabled", required: true, xmlName: "Enabled", type: { name: "Boolean" } }, days: { constraints: { InclusiveMinimum: 1 }, serializedName: "Days", xmlName: "Days", type: { name: "Number" } } } } }; const Metrics = { serializedName: "Metrics", type: { name: "Composite", className: "Metrics", modelProperties: { version: { serializedName: "Version", xmlName: "Version", type: { name: "String" } }, enabled: { serializedName: "Enabled", required: true, xmlName: "Enabled", type: { name: "Boolean" } }, includeAPIs: { serializedName: "IncludeAPIs", xmlName: "IncludeAPIs", type: { name: "Boolean" } }, retentionPolicy: { serializedName: "RetentionPolicy", xmlName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy" } } } } }; const CorsRule = { serializedName: "CorsRule", xmlName: "CorsRule", type: { name: "Composite", className: "CorsRule", modelProperties: { allowedOrigins: { serializedName: "AllowedOrigins", required: true, xmlName: "AllowedOrigins", type: { name: "String" } }, allowedMethods: { serializedName: "AllowedMethods", required: true, xmlName: "AllowedMethods", type: { name: "String" } }, allowedHeaders: { serializedName: "AllowedHeaders", required: true, xmlName: "AllowedHeaders", type: { name: "String" } }, exposedHeaders: { serializedName: "ExposedHeaders", required: true, xmlName: "ExposedHeaders", type: { name: "String" } }, maxAgeInSeconds: { constraints: { InclusiveMinimum: 0 }, serializedName: "MaxAgeInSeconds", required: true, xmlName: "MaxAgeInSeconds", type: { name: "Number" } } } } }; const TableServiceStats = { serializedName: "TableServiceStats", xmlName: "StorageServiceStats", type: { name: "Composite", className: "TableServiceStats", modelProperties: { geoReplication: { serializedName: "GeoReplication", xmlName: "GeoReplication", type: { name: "Composite", className: "GeoReplication" } } } } }; const GeoReplication = { serializedName: "GeoReplication", xmlName: "GeoReplication", type: { name: "Composite", className: "GeoReplication", modelProperties: { status: { serializedName: "Status", required: true, xmlName: "Status", type: { name: "String" } }, lastSyncTime: { serializedName: "LastSyncTime", required: true, xmlName: "LastSyncTime", type: { name: "DateTimeRfc1123" } } } } }; const TableResponse = { serializedName: "TableResponse", type: { name: "Composite", className: "TableResponse", modelProperties: Object.assign(Object.assign({}, TableResponseProperties.type.modelProperties), { odataMetadata: { serializedName: "odata\\.metadata", xmlName: "odata\\.metadata", type: { name: "String" } } }) } }; const TableQueryHeaders = { serializedName: "Table_queryHeaders", type: { name: "Composite", className: "TableQueryHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, xMsContinuationNextTableName: { serializedName: "x-ms-continuation-nexttablename", xmlName: "x-ms-continuation-nexttablename", type: { name: "String" } } } } }; const TableQueryExceptionHeaders = { serializedName: "Table_queryExceptionHeaders", type: { name: "Composite", className: "TableQueryExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const TableCreateHeaders = { serializedName: "Table_createHeaders", type: { name: "Composite", className: "TableCreateHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, preferenceApplied: { serializedName: "preference-applied", xmlName: "preference-applied", type: { name: "String" } } } } }; const TableCreateExceptionHeaders = { serializedName: "Table_createExceptionHeaders", type: { name: "Composite", className: "TableCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const TableDeleteHeaders = { serializedName: "Table_deleteHeaders", type: { name: "Composite", className: "TableDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id",