{ "version": 3, "sources": ["../../../node_modules/@rails/actioncable/src/adapters.js", "../../../node_modules/@rails/actioncable/src/logger.js", "../../../node_modules/@rails/actioncable/src/connection_monitor.js", "../../../node_modules/@rails/actioncable/src/internal.js", "../../../node_modules/@rails/actioncable/src/connection.js", "../../../node_modules/@rails/actioncable/src/subscription.js", "../../../node_modules/@rails/actioncable/src/subscription_guarantor.js", "../../../node_modules/@rails/actioncable/src/subscriptions.js", "../../../node_modules/@rails/actioncable/src/consumer.js", "../../../node_modules/@rails/actioncable/src/index.js", "../../../node_modules/cos-js-sdk-v5/dist/cos-js-sdk-v5.js", "../../../node_modules/qrcode/lib/can-promise.js", "../../../node_modules/qrcode/lib/core/utils.js", "../../../node_modules/qrcode/lib/core/error-correction-level.js", "../../../node_modules/qrcode/lib/core/bit-buffer.js", "../../../node_modules/qrcode/lib/core/bit-matrix.js", "../../../node_modules/qrcode/lib/core/alignment-pattern.js", "../../../node_modules/qrcode/lib/core/finder-pattern.js", "../../../node_modules/qrcode/lib/core/mask-pattern.js", "../../../node_modules/qrcode/lib/core/error-correction-code.js", "../../../node_modules/qrcode/lib/core/galois-field.js", "../../../node_modules/qrcode/lib/core/polynomial.js", "../../../node_modules/qrcode/lib/core/reed-solomon-encoder.js", "../../../node_modules/qrcode/lib/core/version-check.js", "../../../node_modules/qrcode/lib/core/regex.js", "../../../node_modules/qrcode/lib/core/mode.js", "../../../node_modules/qrcode/lib/core/version.js", "../../../node_modules/qrcode/lib/core/format-info.js", "../../../node_modules/qrcode/lib/core/numeric-data.js", "../../../node_modules/qrcode/lib/core/alphanumeric-data.js", "../../../node_modules/encode-utf8/index.js", "../../../node_modules/qrcode/lib/core/byte-data.js", "../../../node_modules/qrcode/lib/core/kanji-data.js", "../../../node_modules/dijkstrajs/dijkstra.js", "../../../node_modules/qrcode/lib/core/segments.js", "../../../node_modules/qrcode/lib/core/qrcode.js", "../../../node_modules/qrcode/lib/renderer/utils.js", "../../../node_modules/qrcode/lib/renderer/canvas.js", "../../../node_modules/qrcode/lib/renderer/svg-tag.js", "../../../node_modules/qrcode/lib/browser.js", "../../../node_modules/compressorjs/dist/compressor.js", "../../../node_modules/alpinejs/dist/alpine.js", "../../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../javascript/controllers/application.js", "../../javascript/controllers/add_chat_member_controller.js", "../../javascript/controllers/hello_controller.js", "../../javascript/controllers/learning_form_controller.js", "../../javascript/controllers/login_controller.js", "../../../node_modules/js-base64/base64.mjs", "../../javascript/controllers/scroll_controller.js", "../../javascript/controllers/send_message_controller.js", "../../../node_modules/just-extend/index.esm.js", "../../../node_modules/dropzone/dist/src/dropzone.js", "../../../node_modules/dropzone/dist/src/emitter.js", "../../../node_modules/dropzone/dist/src/options.js", "../../../node_modules/dropzone/dist/node_modules/@parcel/runtime-js/lib/bundles/runtime-044f6de40395a564.js", "../../javascript/controllers/upload_image_controller.js", "../../javascript/controllers/index.js", "../../../node_modules/alpine-turbo-drive-adapter/dist/alpine-turbo-drive-adapter.esm.js", "../../javascript/application.js", "../../javascript/common/global_utils.js", "../../../node_modules/vue/dist/vue.runtime.esm.js", "../../../node_modules/vue-turbolinks/index.js", "../../javascript/pages/bind_phone.js", "../../javascript/pages/login.js", "../../javascript/pages/open_in_wechat.js"], "sourcesContent": ["export default {\n logger: self.console,\n WebSocket: self.WebSocket\n}\n", "import adapters from \"./adapters\"\n\n// The logger is disabled by default. You can enable it with:\n//\n// ActionCable.logger.enabled = true\n//\n// Example:\n//\n// import * as ActionCable from '@rails/actioncable'\n//\n// ActionCable.logger.enabled = true\n// ActionCable.logger.log('Connection Established.')\n//\n\nexport default {\n log(...messages) {\n if (this.enabled) {\n messages.push(Date.now())\n adapters.logger.log(\"[ActionCable]\", ...messages)\n }\n },\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring the cable connection is in good health by validating the heartbeat pings sent from the server, and attempting\n// revival reconnections if things go astray. Internal class, not intended for direct user manipulation.\n\nconst now = () => new Date().getTime()\n\nconst secondsSince = time => (now() - time) / 1000\n\nclass ConnectionMonitor {\n constructor(connection) {\n this.visibilityDidChange = this.visibilityDidChange.bind(this)\n this.connection = connection\n this.reconnectAttempts = 0\n }\n\n start() {\n if (!this.isRunning()) {\n this.startedAt = now()\n delete this.stoppedAt\n this.startPolling()\n addEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`)\n }\n }\n\n stop() {\n if (this.isRunning()) {\n this.stoppedAt = now()\n this.stopPolling()\n removeEventListener(\"visibilitychange\", this.visibilityDidChange)\n logger.log(\"ConnectionMonitor stopped\")\n }\n }\n\n isRunning() {\n return this.startedAt && !this.stoppedAt\n }\n\n recordPing() {\n this.pingedAt = now()\n }\n\n recordConnect() {\n this.reconnectAttempts = 0\n this.recordPing()\n delete this.disconnectedAt\n logger.log(\"ConnectionMonitor recorded connect\")\n }\n\n recordDisconnect() {\n this.disconnectedAt = now()\n logger.log(\"ConnectionMonitor recorded disconnect\")\n }\n\n // Private\n\n startPolling() {\n this.stopPolling()\n this.poll()\n }\n\n stopPolling() {\n clearTimeout(this.pollTimeout)\n }\n\n poll() {\n this.pollTimeout = setTimeout(() => {\n this.reconnectIfStale()\n this.poll()\n }\n , this.getPollInterval())\n }\n\n getPollInterval() {\n const { staleThreshold, reconnectionBackoffRate } = this.constructor\n const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10))\n const jitterMax = this.reconnectAttempts === 0 ? 1.0 : reconnectionBackoffRate\n const jitter = jitterMax * Math.random()\n return staleThreshold * 1000 * backoff * (1 + jitter)\n }\n\n reconnectIfStale() {\n if (this.connectionIsStale()) {\n logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`)\n this.reconnectAttempts++\n if (this.disconnectedRecently()) {\n logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`)\n } else {\n logger.log(\"ConnectionMonitor reopening\")\n this.connection.reopen()\n }\n }\n }\n\n get refreshedAt() {\n return this.pingedAt ? this.pingedAt : this.startedAt\n }\n\n connectionIsStale() {\n return secondsSince(this.refreshedAt) > this.constructor.staleThreshold\n }\n\n disconnectedRecently() {\n return this.disconnectedAt && (secondsSince(this.disconnectedAt) < this.constructor.staleThreshold)\n }\n\n visibilityDidChange() {\n if (document.visibilityState === \"visible\") {\n setTimeout(() => {\n if (this.connectionIsStale() || !this.connection.isOpen()) {\n logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`)\n this.connection.reopen()\n }\n }\n , 200)\n }\n }\n\n}\n\nConnectionMonitor.staleThreshold = 6 // Server::Connections::BEAT_INTERVAL * 2 (missed two pings)\nConnectionMonitor.reconnectionBackoffRate = 0.15\n\nexport default ConnectionMonitor\n", "export default {\n \"message_types\": {\n \"welcome\": \"welcome\",\n \"disconnect\": \"disconnect\",\n \"ping\": \"ping\",\n \"confirmation\": \"confirm_subscription\",\n \"rejection\": \"reject_subscription\"\n },\n \"disconnect_reasons\": {\n \"unauthorized\": \"unauthorized\",\n \"invalid_request\": \"invalid_request\",\n \"server_restart\": \"server_restart\",\n \"remote\": \"remote\"\n },\n \"default_mount_path\": \"/cable\",\n \"protocols\": [\n \"actioncable-v1-json\",\n \"actioncable-unsupported\"\n ]\n}\n", "import adapters from \"./adapters\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport INTERNAL from \"./internal\"\nimport logger from \"./logger\"\n\n// Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.\n\nconst {message_types, protocols} = INTERNAL\nconst supportedProtocols = protocols.slice(0, protocols.length - 1)\n\nconst indexOf = [].indexOf\n\nclass Connection {\n constructor(consumer) {\n this.open = this.open.bind(this)\n this.consumer = consumer\n this.subscriptions = this.consumer.subscriptions\n this.monitor = new ConnectionMonitor(this)\n this.disconnected = true\n }\n\n send(data) {\n if (this.isOpen()) {\n this.webSocket.send(JSON.stringify(data))\n return true\n } else {\n return false\n }\n }\n\n open() {\n if (this.isActive()) {\n logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`)\n return false\n } else {\n const socketProtocols = [...protocols, ...this.consumer.subprotocols || []]\n logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`)\n if (this.webSocket) { this.uninstallEventHandlers() }\n this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols)\n this.installEventHandlers()\n this.monitor.start()\n return true\n }\n }\n\n close({allowReconnect} = {allowReconnect: true}) {\n if (!allowReconnect) { this.monitor.stop() }\n // Avoid closing websockets in a \"connecting\" state due to Safari 15.1+ bug. See: https://github.com/rails/rails/issues/43835#issuecomment-1002288478\n if (this.isOpen()) {\n return this.webSocket.close()\n }\n }\n\n reopen() {\n logger.log(`Reopening WebSocket, current state is ${this.getState()}`)\n if (this.isActive()) {\n try {\n return this.close()\n } catch (error) {\n logger.log(\"Failed to reopen WebSocket\", error)\n }\n finally {\n logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`)\n setTimeout(this.open, this.constructor.reopenDelay)\n }\n } else {\n return this.open()\n }\n }\n\n getProtocol() {\n if (this.webSocket) {\n return this.webSocket.protocol\n }\n }\n\n isOpen() {\n return this.isState(\"open\")\n }\n\n isActive() {\n return this.isState(\"open\", \"connecting\")\n }\n\n triedToReconnect() {\n return this.monitor.reconnectAttempts > 0\n }\n\n // Private\n\n isProtocolSupported() {\n return indexOf.call(supportedProtocols, this.getProtocol()) >= 0\n }\n\n isState(...states) {\n return indexOf.call(states, this.getState()) >= 0\n }\n\n getState() {\n if (this.webSocket) {\n for (let state in adapters.WebSocket) {\n if (adapters.WebSocket[state] === this.webSocket.readyState) {\n return state.toLowerCase()\n }\n }\n }\n return null\n }\n\n installEventHandlers() {\n for (let eventName in this.events) {\n const handler = this.events[eventName].bind(this)\n this.webSocket[`on${eventName}`] = handler\n }\n }\n\n uninstallEventHandlers() {\n for (let eventName in this.events) {\n this.webSocket[`on${eventName}`] = function() {}\n }\n }\n\n}\n\nConnection.reopenDelay = 500\n\nConnection.prototype.events = {\n message(event) {\n if (!this.isProtocolSupported()) { return }\n const {identifier, message, reason, reconnect, type} = JSON.parse(event.data)\n switch (type) {\n case message_types.welcome:\n if (this.triedToReconnect()) {\n this.reconnectAttempted = true\n }\n this.monitor.recordConnect()\n return this.subscriptions.reload()\n case message_types.disconnect:\n logger.log(`Disconnecting. Reason: ${reason}`)\n return this.close({allowReconnect: reconnect})\n case message_types.ping:\n return this.monitor.recordPing()\n case message_types.confirmation:\n this.subscriptions.confirmSubscription(identifier)\n if (this.reconnectAttempted) {\n this.reconnectAttempted = false\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: true})\n } else {\n return this.subscriptions.notify(identifier, \"connected\", {reconnected: false})\n }\n case message_types.rejection:\n return this.subscriptions.reject(identifier)\n default:\n return this.subscriptions.notify(identifier, \"received\", message)\n }\n },\n\n open() {\n logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`)\n this.disconnected = false\n if (!this.isProtocolSupported()) {\n logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\")\n return this.close({allowReconnect: false})\n }\n },\n\n close(event) {\n logger.log(\"WebSocket onclose event\")\n if (this.disconnected) { return }\n this.disconnected = true\n this.monitor.recordDisconnect()\n return this.subscriptions.notifyAll(\"disconnected\", {willAttemptReconnect: this.monitor.isRunning()})\n },\n\n error() {\n logger.log(\"WebSocket onerror event\")\n }\n}\n\nexport default Connection\n", "// A new subscription is created through the ActionCable.Subscriptions instance available on the consumer.\n// It provides a number of callbacks and a method for calling remote procedure calls on the corresponding\n// Channel instance on the server side.\n//\n// An example demonstrates the basic functionality:\n//\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\", {\n// connected() {\n// // Called once the subscription has been successfully completed\n// },\n//\n// disconnected({ willAttemptReconnect: boolean }) {\n// // Called when the client has disconnected with the server.\n// // The object will have an `willAttemptReconnect` property which\n// // says whether the client has the intention of attempting\n// // to reconnect.\n// },\n//\n// appear() {\n// this.perform('appear', {appearing_on: this.appearingOn()})\n// },\n//\n// away() {\n// this.perform('away')\n// },\n//\n// appearingOn() {\n// $('main').data('appearing-on')\n// }\n// })\n//\n// The methods #appear and #away forward their intent to the remote AppearanceChannel instance on the server\n// by calling the `perform` method with the first parameter being the action (which maps to AppearanceChannel#appear/away).\n// The second parameter is a hash that'll get JSON encoded and made available on the server in the data parameter.\n//\n// This is how the server component would look:\n//\n// class AppearanceChannel < ApplicationActionCable::Channel\n// def subscribed\n// current_user.appear\n// end\n//\n// def unsubscribed\n// current_user.disappear\n// end\n//\n// def appear(data)\n// current_user.appear on: data['appearing_on']\n// end\n//\n// def away\n// current_user.away\n// end\n// end\n//\n// The \"AppearanceChannel\" name is automatically mapped between the client-side subscription creation and the server-side Ruby class name.\n// The AppearanceChannel#appear/away public methods are exposed automatically to client-side invocation through the perform method.\n\nconst extend = function(object, properties) {\n if (properties != null) {\n for (let key in properties) {\n const value = properties[key]\n object[key] = value\n }\n }\n return object\n}\n\nexport default class Subscription {\n constructor(consumer, params = {}, mixin) {\n this.consumer = consumer\n this.identifier = JSON.stringify(params)\n extend(this, mixin)\n }\n\n // Perform a channel action with the optional data passed as an attribute\n perform(action, data = {}) {\n data.action = action\n return this.send(data)\n }\n\n send(data) {\n return this.consumer.send({command: \"message\", identifier: this.identifier, data: JSON.stringify(data)})\n }\n\n unsubscribe() {\n return this.consumer.subscriptions.remove(this)\n }\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring channel subscribe command is confirmed, retrying until confirmation is received.\n// Internal class, not intended for direct user manipulation.\n\nclass SubscriptionGuarantor {\n constructor(subscriptions) {\n this.subscriptions = subscriptions\n this.pendingSubscriptions = []\n }\n\n guarantee(subscription) {\n if(this.pendingSubscriptions.indexOf(subscription) == -1){ \n logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`)\n this.pendingSubscriptions.push(subscription) \n }\n else {\n logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`)\n }\n this.startGuaranteeing()\n }\n\n forget(subscription) {\n logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`)\n this.pendingSubscriptions = (this.pendingSubscriptions.filter((s) => s !== subscription))\n }\n\n startGuaranteeing() {\n this.stopGuaranteeing()\n this.retrySubscribing()\n }\n \n stopGuaranteeing() {\n clearTimeout(this.retryTimeout)\n }\n\n retrySubscribing() {\n this.retryTimeout = setTimeout(() => {\n if (this.subscriptions && typeof(this.subscriptions.subscribe) === \"function\") {\n this.pendingSubscriptions.map((subscription) => {\n logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`)\n this.subscriptions.subscribe(subscription)\n })\n }\n }\n , 500)\n }\n}\n\nexport default SubscriptionGuarantor", "import Subscription from \"./subscription\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport logger from \"./logger\"\n\n// Collection class for creating (and internally managing) channel subscriptions.\n// The only method intended to be triggered by the user is ActionCable.Subscriptions#create,\n// and it should be called through the consumer like so:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n\nexport default class Subscriptions {\n constructor(consumer) {\n this.consumer = consumer\n this.guarantor = new SubscriptionGuarantor(this)\n this.subscriptions = []\n }\n\n create(channelName, mixin) {\n const channel = channelName\n const params = typeof channel === \"object\" ? channel : {channel}\n const subscription = new Subscription(this.consumer, params, mixin)\n return this.add(subscription)\n }\n\n // Private\n\n add(subscription) {\n this.subscriptions.push(subscription)\n this.consumer.ensureActiveConnection()\n this.notify(subscription, \"initialized\")\n this.subscribe(subscription)\n return subscription\n }\n\n remove(subscription) {\n this.forget(subscription)\n if (!this.findAll(subscription.identifier).length) {\n this.sendCommand(subscription, \"unsubscribe\")\n }\n return subscription\n }\n\n reject(identifier) {\n return this.findAll(identifier).map((subscription) => {\n this.forget(subscription)\n this.notify(subscription, \"rejected\")\n return subscription\n })\n }\n\n forget(subscription) {\n this.guarantor.forget(subscription)\n this.subscriptions = (this.subscriptions.filter((s) => s !== subscription))\n return subscription\n }\n\n findAll(identifier) {\n return this.subscriptions.filter((s) => s.identifier === identifier)\n }\n\n reload() {\n return this.subscriptions.map((subscription) =>\n this.subscribe(subscription))\n }\n\n notifyAll(callbackName, ...args) {\n return this.subscriptions.map((subscription) =>\n this.notify(subscription, callbackName, ...args))\n }\n\n notify(subscription, callbackName, ...args) {\n let subscriptions\n if (typeof subscription === \"string\") {\n subscriptions = this.findAll(subscription)\n } else {\n subscriptions = [subscription]\n }\n\n return subscriptions.map((subscription) =>\n (typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined))\n }\n\n subscribe(subscription) {\n if (this.sendCommand(subscription, \"subscribe\")) {\n this.guarantor.guarantee(subscription)\n }\n }\n\n confirmSubscription(identifier) {\n logger.log(`Subscription confirmed ${identifier}`)\n this.findAll(identifier).map((subscription) =>\n this.guarantor.forget(subscription))\n }\n\n sendCommand(subscription, command) {\n const {identifier} = subscription\n return this.consumer.send({command, identifier})\n }\n}\n", "import Connection from \"./connection\"\nimport Subscriptions from \"./subscriptions\"\n\n// The ActionCable.Consumer establishes the connection to a server-side Ruby Connection object. Once established,\n// the ActionCable.ConnectionMonitor will ensure that its properly maintained through heartbeats and checking for stale updates.\n// The Consumer instance is also the gateway to establishing subscriptions to desired channels through the #createSubscription\n// method.\n//\n// The following example shows how this can be set up:\n//\n// App = {}\n// App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n// App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n//\n// When a consumer is created, it automatically connects with the server.\n//\n// To disconnect from the server, call\n//\n// App.cable.disconnect()\n//\n// and to restart the connection:\n//\n// App.cable.connect()\n//\n// Any channel subscriptions which existed prior to disconnecting will\n// automatically resubscribe.\n\nexport default class Consumer {\n constructor(url) {\n this._url = url\n this.subscriptions = new Subscriptions(this)\n this.connection = new Connection(this)\n this.subprotocols = []\n }\n\n get url() {\n return createWebSocketURL(this._url)\n }\n\n send(data) {\n return this.connection.send(data)\n }\n\n connect() {\n return this.connection.open()\n }\n\n disconnect() {\n return this.connection.close({allowReconnect: false})\n }\n\n ensureActiveConnection() {\n if (!this.connection.isActive()) {\n return this.connection.open()\n }\n }\n\n addSubProtocol(subprotocol) {\n this.subprotocols = [...this.subprotocols, subprotocol]\n }\n}\n\nexport function createWebSocketURL(url) {\n if (typeof url === \"function\") {\n url = url()\n }\n\n if (url && !/^wss?:/i.test(url)) {\n const a = document.createElement(\"a\")\n a.href = url\n // Fix populating Location properties in IE. Otherwise, protocol will be blank.\n a.href = a.href\n a.protocol = a.protocol.replace(\"http\", \"ws\")\n return a.href\n } else {\n return url\n }\n}\n", "import Connection from \"./connection\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport Consumer, { createWebSocketURL } from \"./consumer\"\nimport INTERNAL from \"./internal\"\nimport Subscription from \"./subscription\"\nimport Subscriptions from \"./subscriptions\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport adapters from \"./adapters\"\nimport logger from \"./logger\"\n\nexport {\n Connection,\n ConnectionMonitor,\n Consumer,\n INTERNAL,\n Subscription,\n Subscriptions,\n SubscriptionGuarantor,\n adapters,\n createWebSocketURL,\n logger,\n}\n\nexport function createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n return new Consumer(url)\n}\n\nexport function getConfig(name) {\n const element = document.head.querySelector(`meta[name='action-cable-${name}']`)\n if (element) {\n return element.getAttribute(\"content\")\n }\n}\n", "(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"COS\"] = factory();\n\telse\n\t\troot[\"COS\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// define __esModule on exports\n/******/ \t__webpack_require__.r = function(exports) {\n/******/ \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n/******/ \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n/******/ \t\t}\n/******/ \t\tObject.defineProperty(exports, '__esModule', { value: true });\n/******/ \t};\n/******/\n/******/ \t// create a fake namespace object\n/******/ \t// mode & 1: value is a module id, require it\n/******/ \t// mode & 2: merge all properties of value into the ns\n/******/ \t// mode & 4: return value when already ns object\n/******/ \t// mode & 8|1: behave like require\n/******/ \t__webpack_require__.t = function(value, mode) {\n/******/ \t\tif(mode & 1) value = __webpack_require__(value);\n/******/ \t\tif(mode & 8) return value;\n/******/ \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n/******/ \t\tvar ns = Object.create(null);\n/******/ \t\t__webpack_require__.r(ns);\n/******/ \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n/******/ \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n/******/ \t\treturn ns;\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"/dist/\";\n/******/\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = \"./index.js\");\n/******/ })\n/************************************************************************/\n/******/ ({\n\n/***/ \"./index.js\":\n/*!******************!*\\\n !*** ./index.js ***!\n \\******************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar COS = __webpack_require__(/*! ./src/cos */ \"./src/cos.js\");\nmodule.exports = COS;\n\n/***/ }),\n\n/***/ \"./lib/base64.js\":\n/*!***********************!*\\\n !*** ./lib/base64.js ***!\n \\***********************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\n/*\n * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $\n *\n * Licensed under the BSD 3-Clause License.\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * References:\n * http://en.wikipedia.org/wiki/Base64\n */\n\nvar Base64 = function (global) {\n global = global || {};\n 'use strict';\n // existing version for noConflict()\n var _Base64 = global.Base64;\n var version = \"2.1.9\";\n // if node.js, we use Buffer\n var buffer;\n // constants\n var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n var b64tab = function (bin) {\n var t = {};\n for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;\n return t;\n }(b64chars);\n var fromCharCode = String.fromCharCode;\n // encoder stuff\n var cb_utob = function cb_utob(c) {\n if (c.length < 2) {\n var cc = c.charCodeAt(0);\n return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | cc >>> 6) + fromCharCode(0x80 | cc & 0x3f) : fromCharCode(0xe0 | cc >>> 12 & 0x0f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);\n } else {\n var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);\n return fromCharCode(0xf0 | cc >>> 18 & 0x07) + fromCharCode(0x80 | cc >>> 12 & 0x3f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);\n }\n };\n var re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n var utob = function utob(u) {\n return u.replace(re_utob, cb_utob);\n };\n var cb_encode = function cb_encode(ccc) {\n var padlen = [0, 2, 1][ccc.length % 3],\n ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0),\n chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? '=' : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63)];\n return chars.join('');\n };\n var btoa = global.btoa ? function (b) {\n return global.btoa(b);\n } : function (b) {\n return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n };\n var _encode = buffer ? function (u) {\n return (u.constructor === buffer.constructor ? u : new buffer(u)).toString('base64');\n } : function (u) {\n return btoa(utob(u));\n };\n var encode = function encode(u, urisafe) {\n return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\\/]/g, function (m0) {\n return m0 == '+' ? '-' : '_';\n }).replace(/=/g, '');\n };\n var encodeURI = function encodeURI(u) {\n return encode(u, true);\n };\n // decoder stuff\n var re_btou = new RegExp(['[\\xC0-\\xDF][\\x80-\\xBF]', '[\\xE0-\\xEF][\\x80-\\xBF]{2}', '[\\xF0-\\xF7][\\x80-\\xBF]{3}'].join('|'), 'g');\n var cb_btou = function cb_btou(cccc) {\n switch (cccc.length) {\n case 4:\n var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),\n offset = cp - 0x10000;\n return fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00);\n case 3:\n return fromCharCode((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));\n default:\n return fromCharCode((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));\n }\n };\n var btou = function btou(b) {\n return b.replace(re_btou, cb_btou);\n };\n var cb_decode = function cb_decode(cccc) {\n var len = cccc.length,\n padlen = len % 4,\n n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0),\n chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 0xff), fromCharCode(n & 0xff)];\n chars.length -= [0, 0, 2, 1][padlen];\n return chars.join('');\n };\n var atob = global.atob ? function (a) {\n return global.atob(a);\n } : function (a) {\n return a.replace(/[\\s\\S]{1,4}/g, cb_decode);\n };\n var _decode = buffer ? function (a) {\n return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString();\n } : function (a) {\n return btou(atob(a));\n };\n var decode = function decode(a) {\n return _decode(String(a).replace(/[-_]/g, function (m0) {\n return m0 == '-' ? '+' : '/';\n }).replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n };\n var noConflict = function noConflict() {\n var Base64 = global.Base64;\n global.Base64 = _Base64;\n return Base64;\n };\n // export Base64\n var Base64 = {\n VERSION: version,\n atob: atob,\n btoa: btoa,\n fromBase64: decode,\n toBase64: encode,\n utob: utob,\n encode: encode,\n encodeURI: encodeURI,\n btou: btou,\n decode: decode,\n noConflict: noConflict\n };\n return Base64;\n}();\nmodule.exports = Base64;\n\n/***/ }),\n\n/***/ \"./lib/crypto.js\":\n/*!***********************!*\\\n !*** ./lib/crypto.js ***!\n \\***********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(module) {var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\n/*\n CryptoJS v3.1.2\n code.google.com/p/crypto-js\n (c) 2009-2013 by Jeff Mott. All rights reserved.\n code.google.com/p/crypto-js/wiki/License\n */\nvar CryptoJS = CryptoJS || function (g, l) {\n var e = {},\n d = e.lib = {},\n m = function m() {},\n k = d.Base = {\n extend: function extend(a) {\n m.prototype = this;\n var c = new m();\n a && c.mixIn(a);\n c.hasOwnProperty(\"init\") || (c.init = function () {\n c.$super.init.apply(this, arguments);\n });\n c.init.prototype = c;\n c.$super = this;\n return c;\n },\n create: function create() {\n var a = this.extend();\n a.init.apply(a, arguments);\n return a;\n },\n init: function init() {},\n mixIn: function mixIn(a) {\n for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]);\n a.hasOwnProperty(\"toString\") && (this.toString = a.toString);\n },\n clone: function clone() {\n return this.init.prototype.extend(this);\n }\n },\n p = d.WordArray = k.extend({\n init: function init(a, c) {\n a = this.words = a || [];\n this.sigBytes = c != l ? c : 4 * a.length;\n },\n toString: function toString(a) {\n return (a || n).stringify(this);\n },\n concat: function concat(a) {\n var c = this.words,\n q = a.words,\n f = this.sigBytes;\n a = a.sigBytes;\n this.clamp();\n if (f % 4) for (var b = 0; b < a; b++) c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4);else if (65535 < q.length) for (b = 0; b < a; b += 4) c[f + b >>> 2] = q[b >>> 2];else c.push.apply(c, q);\n this.sigBytes += a;\n return this;\n },\n clamp: function clamp() {\n var a = this.words,\n c = this.sigBytes;\n a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);\n a.length = g.ceil(c / 4);\n },\n clone: function clone() {\n var a = k.clone.call(this);\n a.words = this.words.slice(0);\n return a;\n },\n random: function random(a) {\n for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * g.random() | 0);\n return new p.init(c, a);\n }\n }),\n b = e.enc = {},\n n = b.Hex = {\n stringify: function stringify(a) {\n var c = a.words;\n a = a.sigBytes;\n for (var b = [], f = 0; f < a; f++) {\n var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255;\n b.push((d >>> 4).toString(16));\n b.push((d & 15).toString(16));\n }\n return b.join(\"\");\n },\n parse: function parse(a) {\n for (var c = a.length, b = [], f = 0; f < c; f += 2) b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8);\n return new p.init(b, c / 2);\n }\n },\n j = b.Latin1 = {\n stringify: function stringify(a) {\n var c = a.words;\n a = a.sigBytes;\n for (var b = [], f = 0; f < a; f++) b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255));\n return b.join(\"\");\n },\n parse: function parse(a) {\n for (var c = a.length, b = [], f = 0; f < c; f++) b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4);\n return new p.init(b, c);\n }\n },\n h = b.Utf8 = {\n stringify: function stringify(a) {\n try {\n return decodeURIComponent(escape(j.stringify(a)));\n } catch (c) {\n throw Error(\"Malformed UTF-8 data\");\n }\n },\n parse: function parse(a) {\n return j.parse(unescape(encodeURIComponent(a)));\n }\n },\n r = d.BufferedBlockAlgorithm = k.extend({\n reset: function reset() {\n this._data = new p.init();\n this._nDataBytes = 0;\n },\n _append: function _append(a) {\n \"string\" == typeof a && (a = h.parse(a));\n this._data.concat(a);\n this._nDataBytes += a.sigBytes;\n },\n _process: function _process(a) {\n var c = this._data,\n b = c.words,\n f = c.sigBytes,\n d = this.blockSize,\n e = f / (4 * d),\n e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0);\n a = e * d;\n f = g.min(4 * a, f);\n if (a) {\n for (var k = 0; k < a; k += d) this._doProcessBlock(b, k);\n k = b.splice(0, a);\n c.sigBytes -= f;\n }\n return new p.init(k, f);\n },\n clone: function clone() {\n var a = k.clone.call(this);\n a._data = this._data.clone();\n return a;\n },\n _minBufferSize: 0\n });\n d.Hasher = r.extend({\n cfg: k.extend(),\n init: function init(a) {\n this.cfg = this.cfg.extend(a);\n this.reset();\n },\n reset: function reset() {\n r.reset.call(this);\n this._doReset();\n },\n update: function update(a) {\n this._append(a);\n this._process();\n return this;\n },\n finalize: function finalize(a) {\n a && this._append(a);\n return this._doFinalize();\n },\n blockSize: 16,\n _createHelper: function _createHelper(a) {\n return function (b, d) {\n return new a.init(d).finalize(b);\n };\n },\n _createHmacHelper: function _createHmacHelper(a) {\n return function (b, d) {\n return new s.HMAC.init(a, d).finalize(b);\n };\n }\n });\n var s = e.algo = {};\n return e;\n}(Math);\n(function () {\n var g = CryptoJS,\n l = g.lib,\n e = l.WordArray,\n d = l.Hasher,\n m = [],\n l = g.algo.SHA1 = d.extend({\n _doReset: function _doReset() {\n this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);\n },\n _doProcessBlock: function _doProcessBlock(d, e) {\n for (var b = this._hash.words, n = b[0], j = b[1], h = b[2], g = b[3], l = b[4], a = 0; 80 > a; a++) {\n if (16 > a) m[a] = d[e + a] | 0;else {\n var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16];\n m[a] = c << 1 | c >>> 31;\n }\n c = (n << 5 | n >>> 27) + l + m[a];\n c = 20 > a ? c + ((j & h | ~j & g) + 1518500249) : 40 > a ? c + ((j ^ h ^ g) + 1859775393) : 60 > a ? c + ((j & h | j & g | h & g) - 1894007588) : c + ((j ^ h ^ g) - 899497514);\n l = g;\n g = h;\n h = j << 30 | j >>> 2;\n j = n;\n n = c;\n }\n b[0] = b[0] + n | 0;\n b[1] = b[1] + j | 0;\n b[2] = b[2] + h | 0;\n b[3] = b[3] + g | 0;\n b[4] = b[4] + l | 0;\n },\n _doFinalize: function _doFinalize() {\n var d = this._data,\n e = d.words,\n b = 8 * this._nDataBytes,\n g = 8 * d.sigBytes;\n e[g >>> 5] |= 128 << 24 - g % 32;\n e[(g + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296);\n e[(g + 64 >>> 9 << 4) + 15] = b;\n d.sigBytes = 4 * e.length;\n this._process();\n return this._hash;\n },\n clone: function clone() {\n var e = d.clone.call(this);\n e._hash = this._hash.clone();\n return e;\n }\n });\n g.SHA1 = d._createHelper(l);\n g.HmacSHA1 = d._createHmacHelper(l);\n})();\n(function () {\n var g = CryptoJS,\n l = g.enc.Utf8;\n g.algo.HMAC = g.lib.Base.extend({\n init: function init(e, d) {\n e = this._hasher = new e.init();\n \"string\" == typeof d && (d = l.parse(d));\n var g = e.blockSize,\n k = 4 * g;\n d.sigBytes > k && (d = e.finalize(d));\n d.clamp();\n for (var p = this._oKey = d.clone(), b = this._iKey = d.clone(), n = p.words, j = b.words, h = 0; h < g; h++) n[h] ^= 1549556828, j[h] ^= 909522486;\n p.sigBytes = b.sigBytes = k;\n this.reset();\n },\n reset: function reset() {\n var e = this._hasher;\n e.reset();\n e.update(this._iKey);\n },\n update: function update(e) {\n this._hasher.update(e);\n return this;\n },\n finalize: function finalize(e) {\n var d = this._hasher;\n e = d.finalize(e);\n d.reset();\n return d.finalize(this._oKey.clone().concat(e));\n }\n });\n})();\n(function () {\n // Shortcuts\n var C = CryptoJS;\n var C_lib = C.lib;\n var WordArray = C_lib.WordArray;\n var C_enc = C.enc;\n\n /**\n * Base64 encoding strategy.\n */\n var Base64 = C_enc.Base64 = {\n /**\n * Converts a word array to a Base64 string.\n *\n * @param {WordArray} wordArray The word array.\n *\n * @return {string} The Base64 string.\n *\n * @static\n *\n * @example\n *\n * var base64String = CryptoJS.enc.Base64.stringify(wordArray);\n */\n stringify: function stringify(wordArray) {\n // Shortcuts\n var words = wordArray.words;\n var sigBytes = wordArray.sigBytes;\n var map = this._map;\n\n // Clamp excess bits\n wordArray.clamp();\n\n // Convert\n var base64Chars = [];\n for (var i = 0; i < sigBytes; i += 3) {\n var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;\n var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;\n var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;\n var triplet = byte1 << 16 | byte2 << 8 | byte3;\n for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {\n base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));\n }\n }\n\n // Add padding\n var paddingChar = map.charAt(64);\n if (paddingChar) {\n while (base64Chars.length % 4) {\n base64Chars.push(paddingChar);\n }\n }\n return base64Chars.join('');\n },\n /**\n * Converts a Base64 string to a word array.\n *\n * @param {string} base64Str The Base64 string.\n *\n * @return {WordArray} The word array.\n *\n * @static\n *\n * @example\n *\n * var wordArray = CryptoJS.enc.Base64.parse(base64String);\n */\n parse: function parse(base64Str) {\n // Shortcuts\n var base64StrLength = base64Str.length;\n var map = this._map;\n\n // Ignore padding\n var paddingChar = map.charAt(64);\n if (paddingChar) {\n var paddingIndex = base64Str.indexOf(paddingChar);\n if (paddingIndex != -1) {\n base64StrLength = paddingIndex;\n }\n }\n\n // Convert\n var words = [];\n var nBytes = 0;\n for (var i = 0; i < base64StrLength; i++) {\n if (i % 4) {\n var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;\n var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;\n words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;\n nBytes++;\n }\n }\n return WordArray.create(words, nBytes);\n },\n _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n };\n})();\nif (( false ? undefined : _typeof(module)) === 'object') {\n module.exports = CryptoJS;\n} else {\n window.CryptoJS = CryptoJS;\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/module.js */ \"./node_modules/webpack/buildin/module.js\")(module)))\n\n/***/ }),\n\n/***/ \"./lib/md5.js\":\n/*!********************!*\\\n !*** ./lib/md5.js ***!\n \\********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\n/* https://github.com/emn178/js-md5 */\n(function () {\n 'use strict';\n\n var WINDOW = (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_MD5_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && (typeof self === \"undefined\" ? \"undefined\" : _typeof(self)) === 'object';\n if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && ( false ? undefined : _typeof(module)) === 'object' && module.exports;\n var AMD = true && __webpack_require__(/*! !webpack amd options */ \"./node_modules/webpack/buildin/amd-options.js\");\n var ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var EXTRA = [128, 32768, 8388608, -2147483648];\n var SHIFT = [0, 8, 16, 24];\n var OUTPUT_TYPES = ['hex', 'array', 'digest', 'buffer', 'arrayBuffer', 'base64'];\n var BASE64_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n var blocks = [],\n buffer8;\n if (ARRAY_BUFFER) {\n var buffer = new ArrayBuffer(68);\n buffer8 = new Uint8Array(buffer);\n blocks = new Uint32Array(buffer);\n }\n if (root.JS_MD5_NO_NODE_JS || !Array.isArray) {\n Array.isArray = function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n };\n }\n if (ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n ArrayBuffer.isView = function (obj) {\n return _typeof(obj) === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n };\n }\n\n /**\n * @method hex\n * @memberof md5\n * @description Output hash as hex string\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {String} Hex string\n * @example\n * md5.hex('The quick brown fox jumps over the lazy dog');\n * // equal to\n * md5('The quick brown fox jumps over the lazy dog');\n */\n /**\n * @method digest\n * @memberof md5\n * @description Output hash as bytes array\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {Array} Bytes array\n * @example\n * md5.digest('The quick brown fox jumps over the lazy dog');\n */\n /**\n * @method array\n * @memberof md5\n * @description Output hash as bytes array\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {Array} Bytes array\n * @example\n * md5.array('The quick brown fox jumps over the lazy dog');\n */\n /**\n * @method arrayBuffer\n * @memberof md5\n * @description Output hash as ArrayBuffer\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {ArrayBuffer} ArrayBuffer\n * @example\n * md5.arrayBuffer('The quick brown fox jumps over the lazy dog');\n */\n /**\n * @method buffer\n * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.\n * @memberof md5\n * @description Output hash as ArrayBuffer\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {ArrayBuffer} ArrayBuffer\n * @example\n * md5.buffer('The quick brown fox jumps over the lazy dog');\n */\n /**\n * @method base64\n * @memberof md5\n * @description Output hash as base64 string\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {String} base64 string\n * @example\n * md5.base64('The quick brown fox jumps over the lazy dog');\n */\n var createOutputMethod = function createOutputMethod(outputType) {\n return function (message, isBinStr) {\n return new Md5(true).update(message, isBinStr)[outputType]();\n };\n };\n\n /**\n * @method create\n * @memberof md5\n * @description Create Md5 object\n * @returns {Md5} Md5 object.\n * @example\n * var hash = md5.create();\n */\n /**\n * @method update\n * @memberof md5\n * @description Create and update Md5 object\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {Md5} Md5 object.\n * @example\n * var hash = md5.update('The quick brown fox jumps over the lazy dog');\n * // equal to\n * var hash = md5.create();\n * hash.update('The quick brown fox jumps over the lazy dog');\n */\n var createMethod = function createMethod() {\n var method = createOutputMethod('hex');\n method.getCtx = method.create = function () {\n return new Md5();\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createOutputMethod(type);\n }\n return method;\n };\n\n /**\n * Md5 class\n * @class Md5\n * @description This is internal class.\n * @see {@link md5.create}\n */\n function Md5(sharedMemory) {\n if (sharedMemory) {\n blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n this.blocks = blocks;\n this.buffer8 = buffer8;\n } else {\n if (ARRAY_BUFFER) {\n var buffer = new ArrayBuffer(68);\n this.buffer8 = new Uint8Array(buffer);\n this.blocks = new Uint32Array(buffer);\n } else {\n this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n }\n }\n this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0;\n this.finalized = this.hashed = false;\n this.first = true;\n }\n\n /**\n * @method update\n * @memberof Md5\n * @instance\n * @description Update hash\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {Md5} Md5 object.\n * @see {@link md5.update}\n */\n Md5.prototype.update = function (message, isBinStr) {\n if (this.finalized) {\n return;\n }\n var code,\n index = 0,\n i,\n length = message.length,\n blocks = this.blocks;\n var buffer8 = this.buffer8;\n while (index < length) {\n if (this.hashed) {\n this.hashed = false;\n blocks[0] = blocks[16];\n blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n }\n if (ARRAY_BUFFER) {\n for (i = this.start; index < length && i < 64; ++index) {\n code = message.charCodeAt(index);\n if (isBinStr || code < 0x80) {\n buffer8[i++] = code;\n } else if (code < 0x800) {\n buffer8[i++] = 0xc0 | code >> 6;\n buffer8[i++] = 0x80 | code & 0x3f;\n } else if (code < 0xd800 || code >= 0xe000) {\n buffer8[i++] = 0xe0 | code >> 12;\n buffer8[i++] = 0x80 | code >> 6 & 0x3f;\n buffer8[i++] = 0x80 | code & 0x3f;\n } else {\n code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);\n buffer8[i++] = 0xf0 | code >> 18;\n buffer8[i++] = 0x80 | code >> 12 & 0x3f;\n buffer8[i++] = 0x80 | code >> 6 & 0x3f;\n buffer8[i++] = 0x80 | code & 0x3f;\n }\n }\n } else {\n for (i = this.start; index < length && i < 64; ++index) {\n code = message.charCodeAt(index);\n if (isBinStr || code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);\n blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n this.bytes += i - this.start;\n if (i >= 64) {\n this.start = i - 64;\n this.hash();\n this.hashed = true;\n } else {\n this.start = i;\n }\n }\n if (this.bytes > 4294967295) {\n this.hBytes += this.bytes / 4294967296 << 0;\n this.bytes = this.bytes % 4294967296;\n }\n return this;\n };\n Md5.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks,\n i = this.lastByteIndex;\n blocks[i >> 2] |= EXTRA[i & 3];\n if (i >= 56) {\n if (!this.hashed) {\n this.hash();\n }\n blocks[0] = blocks[16];\n blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n }\n blocks[14] = this.bytes << 3;\n blocks[15] = this.hBytes << 3 | this.bytes >>> 29;\n this.hash();\n };\n Md5.prototype.hash = function () {\n var a,\n b,\n c,\n d,\n bc,\n da,\n blocks = this.blocks;\n if (this.first) {\n a = blocks[0] - 680876937;\n a = (a << 7 | a >>> 25) - 271733879 << 0;\n d = (-1732584194 ^ a & 2004318071) + blocks[1] - 117830708;\n d = (d << 12 | d >>> 20) + a << 0;\n c = (-271733879 ^ d & (a ^ -271733879)) + blocks[2] - 1126478375;\n c = (c << 17 | c >>> 15) + d << 0;\n b = (a ^ c & (d ^ a)) + blocks[3] - 1316259209;\n b = (b << 22 | b >>> 10) + c << 0;\n } else {\n a = this.h0;\n b = this.h1;\n c = this.h2;\n d = this.h3;\n a += (d ^ b & (c ^ d)) + blocks[0] - 680876936;\n a = (a << 7 | a >>> 25) + b << 0;\n d += (c ^ a & (b ^ c)) + blocks[1] - 389564586;\n d = (d << 12 | d >>> 20) + a << 0;\n c += (b ^ d & (a ^ b)) + blocks[2] + 606105819;\n c = (c << 17 | c >>> 15) + d << 0;\n b += (a ^ c & (d ^ a)) + blocks[3] - 1044525330;\n b = (b << 22 | b >>> 10) + c << 0;\n }\n a += (d ^ b & (c ^ d)) + blocks[4] - 176418897;\n a = (a << 7 | a >>> 25) + b << 0;\n d += (c ^ a & (b ^ c)) + blocks[5] + 1200080426;\n d = (d << 12 | d >>> 20) + a << 0;\n c += (b ^ d & (a ^ b)) + blocks[6] - 1473231341;\n c = (c << 17 | c >>> 15) + d << 0;\n b += (a ^ c & (d ^ a)) + blocks[7] - 45705983;\n b = (b << 22 | b >>> 10) + c << 0;\n a += (d ^ b & (c ^ d)) + blocks[8] + 1770035416;\n a = (a << 7 | a >>> 25) + b << 0;\n d += (c ^ a & (b ^ c)) + blocks[9] - 1958414417;\n d = (d << 12 | d >>> 20) + a << 0;\n c += (b ^ d & (a ^ b)) + blocks[10] - 42063;\n c = (c << 17 | c >>> 15) + d << 0;\n b += (a ^ c & (d ^ a)) + blocks[11] - 1990404162;\n b = (b << 22 | b >>> 10) + c << 0;\n a += (d ^ b & (c ^ d)) + blocks[12] + 1804603682;\n a = (a << 7 | a >>> 25) + b << 0;\n d += (c ^ a & (b ^ c)) + blocks[13] - 40341101;\n d = (d << 12 | d >>> 20) + a << 0;\n c += (b ^ d & (a ^ b)) + blocks[14] - 1502002290;\n c = (c << 17 | c >>> 15) + d << 0;\n b += (a ^ c & (d ^ a)) + blocks[15] + 1236535329;\n b = (b << 22 | b >>> 10) + c << 0;\n a += (c ^ d & (b ^ c)) + blocks[1] - 165796510;\n a = (a << 5 | a >>> 27) + b << 0;\n d += (b ^ c & (a ^ b)) + blocks[6] - 1069501632;\n d = (d << 9 | d >>> 23) + a << 0;\n c += (a ^ b & (d ^ a)) + blocks[11] + 643717713;\n c = (c << 14 | c >>> 18) + d << 0;\n b += (d ^ a & (c ^ d)) + blocks[0] - 373897302;\n b = (b << 20 | b >>> 12) + c << 0;\n a += (c ^ d & (b ^ c)) + blocks[5] - 701558691;\n a = (a << 5 | a >>> 27) + b << 0;\n d += (b ^ c & (a ^ b)) + blocks[10] + 38016083;\n d = (d << 9 | d >>> 23) + a << 0;\n c += (a ^ b & (d ^ a)) + blocks[15] - 660478335;\n c = (c << 14 | c >>> 18) + d << 0;\n b += (d ^ a & (c ^ d)) + blocks[4] - 405537848;\n b = (b << 20 | b >>> 12) + c << 0;\n a += (c ^ d & (b ^ c)) + blocks[9] + 568446438;\n a = (a << 5 | a >>> 27) + b << 0;\n d += (b ^ c & (a ^ b)) + blocks[14] - 1019803690;\n d = (d << 9 | d >>> 23) + a << 0;\n c += (a ^ b & (d ^ a)) + blocks[3] - 187363961;\n c = (c << 14 | c >>> 18) + d << 0;\n b += (d ^ a & (c ^ d)) + blocks[8] + 1163531501;\n b = (b << 20 | b >>> 12) + c << 0;\n a += (c ^ d & (b ^ c)) + blocks[13] - 1444681467;\n a = (a << 5 | a >>> 27) + b << 0;\n d += (b ^ c & (a ^ b)) + blocks[2] - 51403784;\n d = (d << 9 | d >>> 23) + a << 0;\n c += (a ^ b & (d ^ a)) + blocks[7] + 1735328473;\n c = (c << 14 | c >>> 18) + d << 0;\n b += (d ^ a & (c ^ d)) + blocks[12] - 1926607734;\n b = (b << 20 | b >>> 12) + c << 0;\n bc = b ^ c;\n a += (bc ^ d) + blocks[5] - 378558;\n a = (a << 4 | a >>> 28) + b << 0;\n d += (bc ^ a) + blocks[8] - 2022574463;\n d = (d << 11 | d >>> 21) + a << 0;\n da = d ^ a;\n c += (da ^ b) + blocks[11] + 1839030562;\n c = (c << 16 | c >>> 16) + d << 0;\n b += (da ^ c) + blocks[14] - 35309556;\n b = (b << 23 | b >>> 9) + c << 0;\n bc = b ^ c;\n a += (bc ^ d) + blocks[1] - 1530992060;\n a = (a << 4 | a >>> 28) + b << 0;\n d += (bc ^ a) + blocks[4] + 1272893353;\n d = (d << 11 | d >>> 21) + a << 0;\n da = d ^ a;\n c += (da ^ b) + blocks[7] - 155497632;\n c = (c << 16 | c >>> 16) + d << 0;\n b += (da ^ c) + blocks[10] - 1094730640;\n b = (b << 23 | b >>> 9) + c << 0;\n bc = b ^ c;\n a += (bc ^ d) + blocks[13] + 681279174;\n a = (a << 4 | a >>> 28) + b << 0;\n d += (bc ^ a) + blocks[0] - 358537222;\n d = (d << 11 | d >>> 21) + a << 0;\n da = d ^ a;\n c += (da ^ b) + blocks[3] - 722521979;\n c = (c << 16 | c >>> 16) + d << 0;\n b += (da ^ c) + blocks[6] + 76029189;\n b = (b << 23 | b >>> 9) + c << 0;\n bc = b ^ c;\n a += (bc ^ d) + blocks[9] - 640364487;\n a = (a << 4 | a >>> 28) + b << 0;\n d += (bc ^ a) + blocks[12] - 421815835;\n d = (d << 11 | d >>> 21) + a << 0;\n da = d ^ a;\n c += (da ^ b) + blocks[15] + 530742520;\n c = (c << 16 | c >>> 16) + d << 0;\n b += (da ^ c) + blocks[2] - 995338651;\n b = (b << 23 | b >>> 9) + c << 0;\n a += (c ^ (b | ~d)) + blocks[0] - 198630844;\n a = (a << 6 | a >>> 26) + b << 0;\n d += (b ^ (a | ~c)) + blocks[7] + 1126891415;\n d = (d << 10 | d >>> 22) + a << 0;\n c += (a ^ (d | ~b)) + blocks[14] - 1416354905;\n c = (c << 15 | c >>> 17) + d << 0;\n b += (d ^ (c | ~a)) + blocks[5] - 57434055;\n b = (b << 21 | b >>> 11) + c << 0;\n a += (c ^ (b | ~d)) + blocks[12] + 1700485571;\n a = (a << 6 | a >>> 26) + b << 0;\n d += (b ^ (a | ~c)) + blocks[3] - 1894986606;\n d = (d << 10 | d >>> 22) + a << 0;\n c += (a ^ (d | ~b)) + blocks[10] - 1051523;\n c = (c << 15 | c >>> 17) + d << 0;\n b += (d ^ (c | ~a)) + blocks[1] - 2054922799;\n b = (b << 21 | b >>> 11) + c << 0;\n a += (c ^ (b | ~d)) + blocks[8] + 1873313359;\n a = (a << 6 | a >>> 26) + b << 0;\n d += (b ^ (a | ~c)) + blocks[15] - 30611744;\n d = (d << 10 | d >>> 22) + a << 0;\n c += (a ^ (d | ~b)) + blocks[6] - 1560198380;\n c = (c << 15 | c >>> 17) + d << 0;\n b += (d ^ (c | ~a)) + blocks[13] + 1309151649;\n b = (b << 21 | b >>> 11) + c << 0;\n a += (c ^ (b | ~d)) + blocks[4] - 145523070;\n a = (a << 6 | a >>> 26) + b << 0;\n d += (b ^ (a | ~c)) + blocks[11] - 1120210379;\n d = (d << 10 | d >>> 22) + a << 0;\n c += (a ^ (d | ~b)) + blocks[2] + 718787259;\n c = (c << 15 | c >>> 17) + d << 0;\n b += (d ^ (c | ~a)) + blocks[9] - 343485551;\n b = (b << 21 | b >>> 11) + c << 0;\n if (this.first) {\n this.h0 = a + 1732584193 << 0;\n this.h1 = b - 271733879 << 0;\n this.h2 = c - 1732584194 << 0;\n this.h3 = d + 271733878 << 0;\n this.first = false;\n } else {\n this.h0 = this.h0 + a << 0;\n this.h1 = this.h1 + b << 0;\n this.h2 = this.h2 + c << 0;\n this.h3 = this.h3 + d << 0;\n }\n };\n\n /**\n * @method hex\n * @memberof Md5\n * @instance\n * @description Output hash as hex string\n * @returns {String} Hex string\n * @see {@link md5.hex}\n * @example\n * hash.hex();\n */\n Md5.prototype.hex = function () {\n this.finalize();\n var h0 = this.h0,\n h1 = this.h1,\n h2 = this.h2,\n h3 = this.h3;\n return HEX_CHARS[h0 >> 4 & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[h0 >> 12 & 0x0F] + HEX_CHARS[h0 >> 8 & 0x0F] + HEX_CHARS[h0 >> 20 & 0x0F] + HEX_CHARS[h0 >> 16 & 0x0F] + HEX_CHARS[h0 >> 28 & 0x0F] + HEX_CHARS[h0 >> 24 & 0x0F] + HEX_CHARS[h1 >> 4 & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[h1 >> 12 & 0x0F] + HEX_CHARS[h1 >> 8 & 0x0F] + HEX_CHARS[h1 >> 20 & 0x0F] + HEX_CHARS[h1 >> 16 & 0x0F] + HEX_CHARS[h1 >> 28 & 0x0F] + HEX_CHARS[h1 >> 24 & 0x0F] + HEX_CHARS[h2 >> 4 & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[h2 >> 12 & 0x0F] + HEX_CHARS[h2 >> 8 & 0x0F] + HEX_CHARS[h2 >> 20 & 0x0F] + HEX_CHARS[h2 >> 16 & 0x0F] + HEX_CHARS[h2 >> 28 & 0x0F] + HEX_CHARS[h2 >> 24 & 0x0F] + HEX_CHARS[h3 >> 4 & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[h3 >> 12 & 0x0F] + HEX_CHARS[h3 >> 8 & 0x0F] + HEX_CHARS[h3 >> 20 & 0x0F] + HEX_CHARS[h3 >> 16 & 0x0F] + HEX_CHARS[h3 >> 28 & 0x0F] + HEX_CHARS[h3 >> 24 & 0x0F];\n };\n\n /**\n * @method toString\n * @memberof Md5\n * @instance\n * @description Output hash as hex string\n * @returns {String} Hex string\n * @see {@link md5.hex}\n * @example\n * hash.toString();\n */\n Md5.prototype.toString = Md5.prototype.hex;\n\n /**\n * @method digest\n * @memberof Md5\n * @instance\n * @description Output hash as bytes array\n * @returns {Array} Bytes array\n * @see {@link md5.digest}\n * @example\n * hash.digest();\n */\n Md5.prototype.digest = function (format) {\n if (format === 'hex') return this.hex();\n this.finalize();\n var h0 = this.h0,\n h1 = this.h1,\n h2 = this.h2,\n h3 = this.h3;\n var res = [h0 & 0xFF, h0 >> 8 & 0xFF, h0 >> 16 & 0xFF, h0 >> 24 & 0xFF, h1 & 0xFF, h1 >> 8 & 0xFF, h1 >> 16 & 0xFF, h1 >> 24 & 0xFF, h2 & 0xFF, h2 >> 8 & 0xFF, h2 >> 16 & 0xFF, h2 >> 24 & 0xFF, h3 & 0xFF, h3 >> 8 & 0xFF, h3 >> 16 & 0xFF, h3 >> 24 & 0xFF];\n return res;\n };\n\n /**\n * @method array\n * @memberof Md5\n * @instance\n * @description Output hash as bytes array\n * @returns {Array} Bytes array\n * @see {@link md5.array}\n * @example\n * hash.array();\n */\n Md5.prototype.array = Md5.prototype.digest;\n\n /**\n * @method arrayBuffer\n * @memberof Md5\n * @instance\n * @description Output hash as ArrayBuffer\n * @returns {ArrayBuffer} ArrayBuffer\n * @see {@link md5.arrayBuffer}\n * @example\n * hash.arrayBuffer();\n */\n Md5.prototype.arrayBuffer = function () {\n this.finalize();\n var buffer = new ArrayBuffer(16);\n var blocks = new Uint32Array(buffer);\n blocks[0] = this.h0;\n blocks[1] = this.h1;\n blocks[2] = this.h2;\n blocks[3] = this.h3;\n return buffer;\n };\n\n /**\n * @method buffer\n * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.\n * @memberof Md5\n * @instance\n * @description Output hash as ArrayBuffer\n * @returns {ArrayBuffer} ArrayBuffer\n * @see {@link md5.buffer}\n * @example\n * hash.buffer();\n */\n Md5.prototype.buffer = Md5.prototype.arrayBuffer;\n\n /**\n * @method base64\n * @memberof Md5\n * @instance\n * @description Output hash as base64 string\n * @returns {String} base64 string\n * @see {@link md5.base64}\n * @example\n * hash.base64();\n */\n Md5.prototype.base64 = function () {\n var v1,\n v2,\n v3,\n base64Str = '',\n bytes = this.array();\n for (var i = 0; i < 15;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[(v1 << 4 | v2 >>> 4) & 63] + BASE64_ENCODE_CHAR[(v2 << 2 | v3 >>> 6) & 63] + BASE64_ENCODE_CHAR[v3 & 63];\n }\n v1 = bytes[i];\n base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[v1 << 4 & 63] + '==';\n return base64Str;\n };\n var exports = createMethod();\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n /**\n * @method md5\b\n * @description Md5 hash function, export to global in browsers.\n * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash\n * @returns {String} md5 hashes\n * @example\n * md5(''); // d41d8cd98f00b204e9800998ecf8427e\n * md5('The quick brown fox jumps over the lazy dog'); // 9e107d9d372bb6826bd81d3542a419d6\n * md5('The quick brown fox jumps over the lazy dog.'); // e4d909c290d0fb1ca068ffaddf22cbd0\n *\n * // It also supports UTF-8 encoding\n * md5('\u4E2D\u6587'); // a7bac2239fcdcb3a067903d8077c4a07\n *\n * // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer`\n * md5([]); // d41d8cd98f00b204e9800998ecf8427e\n * md5(new Uint8Array([])); // d41d8cd98f00b204e9800998ecf8427e\n */\n root.md5 = exports;\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return exports;\n }).call(exports, __webpack_require__, exports, module),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/module.js */ \"./node_modules/webpack/buildin/module.js\")(module)))\n\n/***/ }),\n\n/***/ \"./lib/request.js\":\n/*!************************!*\\\n !*** ./lib/request.js ***!\n \\************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\nvar stringifyPrimitive = function stringifyPrimitive(v) {\n switch (_typeof(v)) {\n case 'string':\n return v;\n case 'boolean':\n return v ? 'true' : 'false';\n case 'number':\n return isFinite(v) ? v : '';\n default:\n return '';\n }\n};\nvar queryStringify = function queryStringify(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n if (_typeof(obj) === 'object') {\n return Object.keys(obj).map(function (k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function (v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).filter(Boolean).join(sep);\n }\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));\n};\nvar xhrRes = function xhrRes(err, xhr, body) {\n var headers = {};\n var strHeaders = xhr.getAllResponseHeaders();\n if (strHeaders && strHeaders.length > 0) {\n strHeaders.trim().split('\\n').forEach(function (item) {\n if (item) {\n var index = item.indexOf(':');\n var key = item.substr(0, index).trim().toLowerCase();\n var val = item.substr(index + 1).trim();\n headers[key] = val;\n }\n });\n }\n return {\n error: err,\n statusCode: xhr.status,\n statusMessage: xhr.statusText,\n headers: headers,\n body: body\n };\n};\nvar xhrBody = function xhrBody(xhr, dataType) {\n return !dataType && dataType === 'text' ? xhr.responseText : xhr.response;\n};\nvar request = function request(opt, callback) {\n // method\n var method = (opt.method || 'GET').toUpperCase();\n\n // url\u3001qs\n var url = opt.url;\n if (opt.qs) {\n var qsStr = queryStringify(opt.qs);\n if (qsStr) {\n url += (url.indexOf('?') === -1 ? '?' : '&') + qsStr;\n }\n }\n\n // \u521B\u5EFA ajax \u5B9E\u4F8B\n var xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n xhr.responseType = opt.dataType || 'text';\n\n // \u5904\u7406 xhrFields \u5C5E\u6027\n if (opt.xhrFields) {\n for (var xhrField in opt.xhrFields) {\n xhr[xhrField] = opt.xhrFields[xhrField];\n }\n }\n\n // \u5904\u7406 headers\n var headers = opt.headers;\n if (headers) {\n for (var key in headers) {\n if (headers.hasOwnProperty(key) && key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'user-agent' && key.toLowerCase() !== 'origin' && key.toLowerCase() !== 'host') {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n }\n\n // onprogress\n if (opt.onProgress && xhr.upload) xhr.upload.onprogress = opt.onProgress;\n if (opt.onDownloadProgress) xhr.onprogress = opt.onDownloadProgress;\n\n // timeout\n if (opt.timeout) xhr.timeout = opt.timeout;\n xhr.ontimeout = function (event) {\n var error = new Error('timeout');\n callback(xhrRes(error, xhr));\n };\n\n // success 2xx/3xx/4xx\n xhr.onload = function () {\n callback(xhrRes(null, xhr, xhrBody(xhr, opt.dataType)));\n };\n\n // error 5xx/0 (\u7F51\u7EDC\u9519\u8BEF\u3001\u8DE8\u57DF\u62A5\u9519\u3001Https connect-src \u9650\u5236\u7684\u62A5\u9519\u65F6 statusCode \u4E3A 0)\n xhr.onerror = function (err) {\n var body = xhrBody(xhr, opt.dataType);\n if (body) {\n // 5xx\n callback(xhrRes(null, xhr, body));\n } else {\n // 0\n var error = xhr.statusText;\n if (!error && xhr.status === 0) error = new Error('CORS blocked or network error');\n callback(xhrRes(error, xhr, body));\n }\n };\n\n // send\n xhr.send(opt.body || '');\n\n // \u8FD4\u56DE ajax \u5B9E\u4F8B\uFF0C\u7528\u4E8E\u5916\u90E8\u8C03\u7528 xhr.abort\n return xhr;\n};\nmodule.exports = request;\n\n/***/ }),\n\n/***/ \"./node_modules/@babel/runtime/helpers/classCallCheck.js\":\n/*!***************************************************************!*\\\n !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!\n \\***************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n\n/***/ }),\n\n/***/ \"./node_modules/@babel/runtime/helpers/createClass.js\":\n/*!************************************************************!*\\\n !*** ./node_modules/@babel/runtime/helpers/createClass.js ***!\n \\************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ \"./node_modules/@babel/runtime/helpers/toPropertyKey.js\");\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n\n/***/ }),\n\n/***/ \"./node_modules/@babel/runtime/helpers/toPrimitive.js\":\n/*!************************************************************!*\\\n !*** ./node_modules/@babel/runtime/helpers/toPrimitive.js ***!\n \\************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _typeof = __webpack_require__(/*! ./typeof.js */ \"./node_modules/@babel/runtime/helpers/typeof.js\")[\"default\"];\nfunction _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}\nmodule.exports = _toPrimitive, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n\n/***/ }),\n\n/***/ \"./node_modules/@babel/runtime/helpers/toPropertyKey.js\":\n/*!**************************************************************!*\\\n !*** ./node_modules/@babel/runtime/helpers/toPropertyKey.js ***!\n \\**************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _typeof = __webpack_require__(/*! ./typeof.js */ \"./node_modules/@babel/runtime/helpers/typeof.js\")[\"default\"];\nvar toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ \"./node_modules/@babel/runtime/helpers/toPrimitive.js\");\nfunction _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}\nmodule.exports = _toPropertyKey, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n\n/***/ }),\n\n/***/ \"./node_modules/@babel/runtime/helpers/typeof.js\":\n/*!*******************************************************!*\\\n !*** ./node_modules/@babel/runtime/helpers/typeof.js ***!\n \\*******************************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(o);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/fxp.js\":\n/*!*************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/fxp.js ***!\n \\*************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nconst validator = __webpack_require__(/*! ./validator */ \"./node_modules/fast-xml-parser/src/validator.js\");\nconst XMLParser = __webpack_require__(/*! ./xmlparser/XMLParser */ \"./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js\");\nconst XMLBuilder = __webpack_require__(/*! ./xmlbuilder/json2xml */ \"./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js\");\n\nmodule.exports = {\n XMLParser: XMLParser,\n XMLValidator: validator,\n XMLBuilder: XMLBuilder\n}\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/ignoreAttributes.js\":\n/*!**************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/ignoreAttributes.js ***!\n \\**************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nfunction getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}\n\nmodule.exports = getIgnoreAttributesFn\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/util.js\":\n/*!**************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/util.js ***!\n \\**************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nconst nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nconst getAllMatches = function(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n};\n\nconst isName = function(string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n};\n\nexports.isExist = function(v) {\n return typeof v !== 'undefined';\n};\n\nexports.isEmptyObject = function(obj) {\n return Object.keys(obj).length === 0;\n};\n\n/**\n * Copy all the properties of a into b.\n * @param {*} target\n * @param {*} a\n */\nexports.merge = function(target, a, arrayMode) {\n if (a) {\n const keys = Object.keys(a); // will return an array of own properties\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n if (arrayMode === 'strict') {\n target[keys[i]] = [ a[keys[i]] ];\n } else {\n target[keys[i]] = a[keys[i]];\n }\n }\n }\n};\n/* exports.merge =function (b,a){\n return Object.assign(b,a);\n} */\n\nexports.getValue = function(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n};\n\n// const fakeCall = function(a) {return a;};\n// const fakeCallNoReturn = function() {};\n\nexports.isName = isName;\nexports.getAllMatches = getAllMatches;\nexports.nameRegexp = nameRegexp;\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/validator.js\":\n/*!*******************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/validator.js ***!\n \\*******************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nconst util = __webpack_require__(/*! ./util */ \"./node_modules/fast-xml-parser/src/util.js\");\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexports.validate = function (xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n \n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i+1] === '?') {\n i+=2;\n i = readPI(xmlData,i);\n if (i.err) return i;\n }else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n \n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\"+tagName+\"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\"+tagName+\"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\"+otg.tagName+\"' (opened in line \"+openPos.line+\", col \"+openPos.col+\") instead of closing tag '\"+tagName+\"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if(options.unpairedTags.indexOf(tagName) !== -1){\n //don't push into stack\n } else {\n tags.push({tagName, tagStartPos});\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i+1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else{\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n }else{\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if ( isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\"+xmlData[i]+\"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n }else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\"+tags[0].tagName+\"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n }else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\"+\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '')+\n \"' found.\", {line: 1, col: 1});\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char){\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = util.getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\"+matches[i][2]+\"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!attrNames.hasOwnProperty(attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return util.isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return util.isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js\":\n/*!*****************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js ***!\n \\*****************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n//parse Empty Node as self closing node\nconst buildFromOrderedJs = __webpack_require__(/*! ./orderedJs2Xml */ \"./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js\");\nconst getIgnoreAttributesFn = __webpack_require__(/*! ../ignoreAttributes */ \"./node_modules/fast-xml-parser/src/ignoreAttributes.js\")\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function(key, a) {\n return a;\n },\n attributeValueProcessor: function(attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false\n};\n\nfunction Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function(/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function() {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function(jObj) {\n if(this.options.preserveOrder){\n return buildFromOrderedJs(jObj, this.options);\n }else {\n if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){\n jObj = {\n [this.options.arrayNodeName] : jObj\n }\n }\n return this.j2x(jObj, 0, []).val;\n }\n};\n\nBuilder.prototype.j2x = function(jObj, level, ajPath) {\n let attrStr = '';\n let val = '';\n const jPath = ajPath.join('.')\n for (let key in jObj) {\n if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n val += this.buildTextValNode(jObj[key], key, '', level);\n }\n }\n } else if (Array.isArray(jObj[key])) {\n //repeated nodes\n const arrLen = jObj[key].length;\n let listTagVal = \"\";\n let listTagAttr = \"\";\n for (let j = 0; j < arrLen; j++) {\n const item = jObj[key][j];\n if (typeof item === 'undefined') {\n // supress undefined node\n } else if (item === null) {\n if(key[0] === \"?\") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (typeof item === 'object') {\n if(this.options.oneListGroup){\n const result = this.j2x(item, level + 1, ajPath.concat(key));\n listTagVal += result.val;\n if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {\n listTagAttr += result.attrStr\n }\n }else{\n listTagVal += this.processTextOrObjNode(item, key, level, ajPath)\n }\n } else {\n if (this.options.oneListGroup) {\n let textValue = this.options.tagValueProcessor(key, item);\n textValue = this.replaceEntitiesValue(textValue);\n listTagVal += textValue;\n } else {\n listTagVal += this.buildTextValNode(item, key, '', level);\n }\n }\n }\n if(this.options.oneListGroup){\n listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);\n }\n val += listTagVal;\n } else {\n //nested node\n if (this.options.attributesGroupName && key === this.options.attributesGroupName) {\n const Ks = Object.keys(jObj[key]);\n const L = Ks.length;\n for (let j = 0; j < L; j++) {\n attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);\n }\n } else {\n val += this.processTextOrObjNode(jObj[key], key, level, ajPath)\n }\n }\n }\n return {attrStr: attrStr, val: val};\n};\n\nBuilder.prototype.buildAttrPairStr = function(attrName, val){\n val = this.options.attributeValueProcessor(attrName, '' + val);\n val = this.replaceEntitiesValue(val);\n if (this.options.suppressBooleanAttributes && val === \"true\") {\n return ' ' + attrName;\n } else return ' ' + attrName + '=\"' + val + '\"';\n}\n\nfunction processTextOrObjNode (object, key, level, ajPath) {\n const result = this.j2x(object, level + 1, ajPath.concat(key));\n if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {\n return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);\n } else {\n return this.buildObjectNode(result.val, key, result.attrStr, level);\n }\n}\n\nBuilder.prototype.buildObjectNode = function(val, key, attrStr, level) {\n if(val === \"\"){\n if(key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n }else{\n\n let tagEndExp = '' + val + tagEndExp );\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n }else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp );\n }\n }\n}\n\nBuilder.prototype.closeTag = function(key){\n let closeTag = \"\";\n if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired\n if(!this.options.suppressUnpairedNode) closeTag = \"/\"\n }else if(this.options.suppressEmptyNode){ //empty\n closeTag = \"/\";\n }else{\n closeTag = `>` + this.newLine;\n }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n return this.indentate(level) + `` + this.newLine;\n }else if(key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; \n }else{\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n \n if( textValue === ''){\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }else{\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities){\n for (let i=0; i 0) {\n indentation = EOL;\n }\n return arrToStr(jArray, options, \"\", indentation);\n}\n\nfunction arrToStr(arr, options, jPath, indentation) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if(tagName === undefined) continue;\n\n let newJPath = \"\";\n if (jPath.length === 0) newJPath = tagName\n else newJPath = `${jPath}.${tagName}`;\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode(newJPath, options)) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += ``;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.commentPropName) {\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n continue;\n }\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tagStart = indentation + `<${tagName}${attStr}`;\n const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n }\n\n return xmlStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(!obj.hasOwnProperty(key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if(!attrMap.hasOwnProperty(attr)) continue;\n let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction isStopNode(jPath, options) {\n jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);\n let tagName = jPath.substr(jPath.lastIndexOf(\".\") + 1);\n for (let index in options.stopNodes) {\n if (options.stopNodes[index] === jPath || options.stopNodes[index] === \"*.\" + tagName) return true;\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\nmodule.exports = toXml;\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js\":\n/*!*********************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js ***!\n \\*********************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nconst util = __webpack_require__(/*! ../util */ \"./node_modules/fast-xml-parser/src/util.js\");\n\n//TODO: handle comments\nfunction readDocType(xmlData, i){\n \n const entities = {};\n if( xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E')\n { \n i = i+9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for(;i') { //Read tag content\n if(comment){\n if( xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\"){\n comment = false;\n angleBracketsCount--;\n }\n }else{\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n }else if( xmlData[i] === '['){\n hasBody = true;\n }else{\n exp += xmlData[i];\n }\n }\n if(angleBracketsCount !== 0){\n throw new Error(`Unclosed DOCTYPE`);\n }\n }else{\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return {entities, i};\n}\n\nfunction readEntityExp(xmlData,i){\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n \n //read EntityName\n let entityName = \"\";\n for (; i < xmlData.length && (xmlData[i] !== \"'\" && xmlData[i] !== '\"' ); i++) {\n // if(xmlData[i] === \" \") continue;\n // else \n entityName += xmlData[i];\n }\n entityName = entityName.trim();\n if(entityName.indexOf(\" \") !== -1) throw new Error(\"External entites are not supported\");\n\n //read Entity Value\n const startChar = xmlData[i++];\n let val = \"\"\n for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {\n val += xmlData[i];\n }\n return [entityName, val, i];\n}\n\nfunction isComment(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === '-' &&\n xmlData[i+3] === '-') return true\n return false\n}\nfunction isEntity(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'N' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'I' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'Y') return true\n return false\n}\nfunction isElement(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'L' &&\n xmlData[i+4] === 'E' &&\n xmlData[i+5] === 'M' &&\n xmlData[i+6] === 'E' &&\n xmlData[i+7] === 'N' &&\n xmlData[i+8] === 'T') return true\n return false\n}\n\nfunction isAttlist(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'A' &&\n xmlData[i+3] === 'T' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'L' &&\n xmlData[i+6] === 'I' &&\n xmlData[i+7] === 'S' &&\n xmlData[i+8] === 'T') return true\n return false\n}\nfunction isNotation(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'N' &&\n xmlData[i+3] === 'O' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'A' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'I' &&\n xmlData[i+8] === 'O' &&\n xmlData[i+9] === 'N') return true\n return false\n}\n\nfunction validateEntityName(name){\n if (util.isName(name))\n\treturn name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}\n\nmodule.exports = readDocType;\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js\":\n/*!**********************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js ***!\n \\**********************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\n\nconst defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function(tagName, val) {\n return val;\n },\n attributeValueProcessor: function(attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function(tagName, jPath, attrs){\n return tagName\n },\n // skipEmptyListItem: false\n};\n \nconst buildOptions = function(options) {\n return Object.assign({}, defaultOptions, options);\n};\n\nexports.buildOptions = buildOptions;\nexports.defaultOptions = defaultOptions;\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js\":\n/*!************************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js ***!\n \\************************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n///@ts-check\n\nconst util = __webpack_require__(/*! ../util */ \"./node_modules/fast-xml-parser/src/util.js\");\nconst xmlNode = __webpack_require__(/*! ./xmlNode */ \"./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js\");\nconst readDocType = __webpack_require__(/*! ./DocTypeReader */ \"./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js\");\nconst toNumber = __webpack_require__(/*! strnum */ \"./node_modules/strnum/strnum.js\");\nconst getIgnoreAttributesFn = __webpack_require__(/*! ../ignoreAttributes */ \"./node_modules/fast-xml-parser/src/ignoreAttributes.js\")\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\nclass OrderedObjParser{\n constructor(options){\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.docTypeEntities = {};\n this.lastEntities = {\n \"apos\" : { regex: /&(apos|#39|#x27);/g, val : \"'\"},\n \"gt\" : { regex: /&(gt|#62|#x3E);/g, val : \">\"},\n \"lt\" : { regex: /&(lt|#60|#x3C);/g, val : \"<\"},\n \"quot\" : { regex: /&(quot|#34|#x22);/g, val : \"\\\"\"},\n };\n this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : \"&\"};\n this.htmlEntities = {\n \"space\": { regex: /&(nbsp|#160);/g, val: \" \" },\n // \"lt\" : { regex: /&(lt|#60);/g, val: \"<\" },\n // \"gt\" : { regex: /&(gt|#62);/g, val: \">\" },\n // \"amp\" : { regex: /&(amp|#38);/g, val: \"&\" },\n // \"quot\" : { regex: /&(quot|#34);/g, val: \"\\\"\" },\n // \"apos\" : { regex: /&(apos|#39);/g, val: \"'\" },\n \"cent\" : { regex: /&(cent|#162);/g, val: \"\u00A2\" },\n \"pound\" : { regex: /&(pound|#163);/g, val: \"\u00A3\" },\n \"yen\" : { regex: /&(yen|#165);/g, val: \"\u00A5\" },\n \"euro\" : { regex: /&(euro|#8364);/g, val: \"\u20AC\" },\n \"copyright\" : { regex: /&(copy|#169);/g, val: \"\u00A9\" },\n \"reg\" : { regex: /&(reg|#174);/g, val: \"\u00AE\" },\n \"inr\" : { regex: /&(inr|#8377);/g, val: \"\u20B9\" },\n \"num_dec\": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },\n \"num_hex\": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },\n };\n this.addExternalEntities = addExternalEntities;\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n }\n\n}\n\nfunction addExternalEntities(externalEntities){\n const entKeys = Object.keys(externalEntities);\n for (let i = 0; i < entKeys.length; i++) {\n const ent = entKeys[i];\n this.lastEntities[ent] = {\n regex: new RegExp(\"&\"+ent+\";\",\"g\"),\n val : externalEntities[ent]\n }\n }\n}\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string} jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n if (val !== undefined) {\n if (this.options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if(val.length > 0){\n if(!escapeEntities) val = this.replaceEntitiesValue(val);\n \n const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);\n if(newval === null || newval === undefined){\n //don't parse\n return val;\n }else if(typeof newval !== typeof val || newval !== val){\n //overwrite\n return newval;\n }else if(this.options.trimValues){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n const trimmedVal = val.trim();\n if(trimmedVal === val){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName) {\n if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = util.getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n if (this.ignoreAttributesFn(attrName, jPath)) {\n continue\n }\n let oldVal = matches[i][4];\n let aName = this.options.attributeNamePrefix + attrName;\n if (attrName.length) {\n if (this.options.transformAttributeName) {\n aName = this.options.transformAttributeName(aName);\n }\n if(aName === \"__proto__\") aName = \"#__proto__\";\n if (oldVal !== undefined) {\n if (this.options.trimValues) {\n oldVal = oldVal.trim();\n }\n oldVal = this.replaceEntitiesValue(oldVal);\n const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);\n if(newVal === null || newVal === undefined){\n //don't parse\n attrs[aName] = oldVal;\n }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){\n //overwrite\n attrs[aName] = newVal;\n }else{\n //parse\n attrs[aName] = parseValue(\n oldVal,\n this.options.parseAttributeValue,\n this.options.numberParseOptions\n );\n }\n } else if (this.options.allowBooleanAttributes) {\n attrs[aName] = true;\n }\n }\n }\n if (!Object.keys(attrs).length) {\n return;\n }\n if (this.options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[this.options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs\n }\n}\n\nconst parseXml = function(xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n let jPath = \"\";\n for(let i=0; i< xmlData.length; i++){//for each char in XML data\n const ch = xmlData[i];\n if(ch === '<'){\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n if( xmlData[i+1] === '/') {//Closing Tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i+2,closeIndex).trim();\n\n if(this.options.removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n }\n }\n\n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n if(currentNode){\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = jPath.substring(jPath.lastIndexOf(\".\")+1);\n if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n let propIndex = 0\n if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){\n propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)\n this.tagsNodeStack.pop();\n }else{\n propIndex = jPath.lastIndexOf(\".\");\n }\n jPath = jPath.substring(0, propIndex);\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if( xmlData[i+1] === '?') {\n\n let tagData = readTagExp(xmlData,i, false, \"?>\");\n if(!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n if( (this.options.ignoreDeclaration && tagData.tagName === \"?xml\") || this.options.ignorePiTags){\n\n }else{\n \n const childNode = new xmlNode(tagData.tagName);\n childNode.add(this.options.textNodeName, \"\");\n \n if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n\n }\n\n\n i = tagData.closeIndex + 1;\n } else if(xmlData.substr(i + 1, 3) === '!--') {\n const endIndex = findClosingIndex(xmlData, \"-->\", i+4, \"Comment is not closed.\")\n if(this.options.commentPropName){\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);\n }\n i = endIndex;\n } else if( xmlData.substr(i + 1, 2) === '!D') {\n const result = readDocType(xmlData, i);\n this.docTypeEntities = result.entities;\n i = result.i;\n }else if(xmlData.substr(i + 1, 2) === '![') {\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9,closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);\n if(val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if(this.options.cdataPropName){\n currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);\n }else{\n currentNode.add(this.options.textNodeName, val);\n }\n \n i = closeIndex + 2;\n }else {//Opening tag\n let result = readTagExp(xmlData,i, this.options.removeNSPrefix);\n let tagName= result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n if (this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n \n //save text as child node\n if (currentNode && textData) {\n if(currentNode.tagname !== '!xml'){\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, jPath, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){\n currentNode = this.tagsNodeStack.pop();\n jPath = jPath.substring(0, jPath.lastIndexOf(\".\"));\n }\n if(tagName !== xmlObj.tagname){\n jPath += jPath ? \".\" + tagName : tagName;\n }\n if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {\n let tagContent = \"\";\n //self-closing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n i = result.closeIndex;\n }\n //unpaired tag\n else if(this.options.unpairedTags.indexOf(tagName) !== -1){\n \n i = result.closeIndex;\n }\n //normal tag\n else{\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if(!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n if(tagContent) {\n tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);\n }\n \n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n childNode.add(this.options.textNodeName, tagContent);\n \n this.addChild(currentNode, childNode, jPath)\n }else{\n //selfClosing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n \n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n }\n //opening tag\n else{\n const childNode = new xmlNode( tagName);\n this.tagsNodeStack.push(currentNode);\n \n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n }else{\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, jPath){\n const result = this.options.updateTag(childNode.tagname, jPath, childNode[\":@\"])\n if(result === false){\n }else if(typeof result === \"string\"){\n childNode.tagname = result\n currentNode.addChild(childNode);\n }else{\n currentNode.addChild(childNode);\n }\n}\n\nconst replaceEntitiesValue = function(val){\n\n if(this.options.processEntities){\n for(let entityName in this.docTypeEntities){\n const entity = this.docTypeEntities[entityName];\n val = val.replace( entity.regx, entity.val);\n }\n for(let entityName in this.lastEntities){\n const entity = this.lastEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n if(this.options.htmlEntities){\n for(let entityName in this.htmlEntities){\n const entity = this.htmlEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n }\n val = val.replace( this.ampEntity.regex, this.ampEntity.val);\n }\n return val;\n}\nfunction saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0\n \n textData = this.parseTextData(textData,\n currentNode.tagname,\n jPath,\n false,\n currentNode[\":@\"] ? Object.keys(currentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n currentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n//TODO: use jPath to simplify the logic\n/**\n * \n * @param {string[]} stopNodes \n * @param {string} jPath\n * @param {string} currentTagName \n */\nfunction isItStopNode(stopNodes, jPath, currentTagName){\n const allNodesExp = \"*.\" + currentTagName;\n for (const stopNodePath in stopNodes) {\n const stopNodeExp = stopNodes[stopNodePath];\n if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;\n }\n return false;\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\"){\n let attrBoundary;\n let tagExp = \"\";\n for (let index = i; index < xmlData.length; index++) {\n let ch = xmlData[index];\n if (attrBoundary) {\n if (ch === attrBoundary) attrBoundary = \"\";//reset\n } else if (ch === '\"' || ch === \"'\") {\n attrBoundary = ch;\n } else if (ch === closingChar[0]) {\n if(closingChar[1]){\n if(xmlData[index + 1] === closingChar[1]){\n return {\n data: tagExp,\n index: index\n }\n }\n }else{\n return {\n data: tagExp,\n index: index\n }\n }\n } else if (ch === '\\t') {\n ch = \" \"\n }\n tagExp += ch;\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg){\n const closingIndex = xmlData.indexOf(str, i);\n if(closingIndex === -1){\n throw new Error(errMsg)\n }else{\n return closingIndex + str.length - 1;\n }\n}\n\nfunction readTagExp(xmlData,i, removeNSPrefix, closingChar = \">\"){\n const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);\n if(!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if(separatorIndex !== -1){//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if(removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i){\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n for (; i < xmlData.length; i++) {\n if( xmlData[i] === \"<\"){ \n if (xmlData[i+1] === \"/\") {//close tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i+2,closeIndex).trim();\n if(closeTagName === tagName){\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i : closeIndex\n }\n }\n }\n i=closeIndex;\n } else if(xmlData[i+1] === '?') { \n const closeIndex = findClosingIndex(xmlData, \"?>\", i+1, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 3) === '!--') { \n const closeIndex = findClosingIndex(xmlData, \"-->\", i+3, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 2) === '![') { \n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i=closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== \"/\") {\n openTagCount++;\n }\n i=tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if(newval === 'true' ) return true;\n else if(newval === 'false' ) return false;\n else return toNumber(val, options);\n } else {\n if (util.isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\n\nmodule.exports = OrderedObjParser;\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js\":\n/*!*****************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js ***!\n \\*****************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nconst { buildOptions} = __webpack_require__(/*! ./OptionsBuilder */ \"./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js\");\nconst OrderedObjParser = __webpack_require__(/*! ./OrderedObjParser */ \"./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js\");\nconst { prettify} = __webpack_require__(/*! ./node2json */ \"./node_modules/fast-xml-parser/src/xmlparser/node2json.js\");\nconst validator = __webpack_require__(/*! ../validator */ \"./node_modules/fast-xml-parser/src/validator.js\");\n\nclass XMLParser{\n \n constructor(options){\n this.externalEntities = {};\n this.options = buildOptions(options);\n \n }\n /**\n * Parse XML dats to JS object \n * @param {string|Buffer} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData,validationOption){\n if(typeof xmlData === \"string\"){\n }else if( xmlData.toString){\n xmlData = xmlData.toString();\n }else{\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n if( validationOption){\n if(validationOption === true) validationOption = {}; //validate with default options\n \n const result = validator.validate(xmlData, validationOption);\n if (result !== true) {\n throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options);\n orderedObjParser.addExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value){\n if(value.indexOf(\"&\") !== -1){\n throw new Error(\"Entity value can't have '&'\")\n }else if(key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1){\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n }else if(value === \"&\"){\n throw new Error(\"An entity with value '&' is not permitted\");\n }else{\n this.externalEntities[key] = value;\n }\n }\n}\n\nmodule.exports = XMLParser;\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/node2json.js\":\n/*!*****************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/node2json.js ***!\n \\*****************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @returns \n */\nfunction prettify(node, options){\n return compress( node, options);\n}\n\n/**\n * \n * @param {array} arr \n * @param {object} options \n * @param {string} jPath \n * @returns object\n */\nfunction compress(arr, options, jPath){\n let text;\n const compressedObj = {};\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n let newJpath = \"\";\n if(jPath === undefined) newJpath = property;\n else newJpath = jPath + \".\" + property;\n\n if(property === options.textNodeName){\n if(text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n }else if(property === undefined){\n continue;\n }else if(tagObj[property]){\n \n let val = compress(tagObj[property], options, newJpath);\n const isLeaf = isLeafTag(val, options);\n\n if(tagObj[\":@\"]){\n assignAttributes( val, tagObj[\":@\"], newJpath, options);\n }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){\n val = val[options.textNodeName];\n }else if(Object.keys(val).length === 0){\n if(options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {\n if(!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [ compressedObj[property] ];\n }\n compressedObj[property].push(val);\n }else{\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n if (options.isArray(property, newJpath, isLeaf )) {\n compressedObj[property] = [val];\n }else{\n compressedObj[property] = val;\n }\n }\n }\n \n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if(typeof text === \"string\"){\n if(text.length > 0) compressedObj[options.textNodeName] = text;\n }else if(text !== undefined) compressedObj[options.textNodeName] = text;\n return compressedObj;\n}\n\nfunction propName(obj){\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, jpath, options){\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i];\n if (options.isArray(atrrName, jpath + \".\" + atrrName, true, true)) {\n obj[atrrName] = [ attrMap[atrrName] ];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options){\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n \n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}\nexports.prettify = prettify;\n\n\n/***/ }),\n\n/***/ \"./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js\":\n/*!***************************************************************!*\\\n !*** ./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js ***!\n \\***************************************************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nclass XmlNode{\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = {}; //attributes map\n }\n add(key,val){\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if(key === \"__proto__\") key = \"#__proto__\";\n this.child.push( {[key]: val });\n }\n addChild(node) {\n if(node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if(node[\":@\"] && Object.keys(node[\":@\"]).length > 0){\n this.child.push( { [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n }else{\n this.child.push( { [node.tagname]: node.child });\n }\n };\n};\n\n\nmodule.exports = XmlNode;\n\n/***/ }),\n\n/***/ \"./node_modules/process/browser.js\":\n/*!*****************************************!*\\\n !*** ./node_modules/process/browser.js ***!\n \\*****************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n/***/ }),\n\n/***/ \"./node_modules/strnum/strnum.js\":\n/*!***************************************!*\\\n !*** ./node_modules/strnum/strnum.js ***!\n \\***************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nconst hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)(\\.[0-9]+([eE]\\-?[0-9]+)?|[0-9]+(\\.[0-9]+([eE]\\-?[0-9]+)?)?)$/;\n// const octRegex = /0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\n//polyfill\nif (!Number.parseInt && window.parseInt) {\n Number.parseInt = window.parseInt;\n}\nif (!Number.parseFloat && window.parseFloat) {\n Number.parseFloat = window.parseFloat;\n}\n\n \nconst consider = {\n hex : true,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true\n //skipLike: /regex/\n};\n\nfunction toNumber(str, options = {}){\n // const options = Object.assign({}, consider);\n // if(opt.leadingZeros === false){\n // options.leadingZeros = false;\n // }else if(opt.hex === false){\n // options.hex = false;\n // }\n\n options = Object.assign({}, consider, options );\n if(!str || typeof str !== \"string\" ) return str;\n \n let trimmedStr = str.trim();\n // if(trimmedStr === \"0.0\") return 0;\n // else if(trimmedStr === \"+0.0\") return 0;\n // else if(trimmedStr === \"-0.0\") return -0;\n\n if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return Number.parseInt(trimmedStr, 16);\n // } else if (options.parseOct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n }else{\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n if(match){\n const sign = match[1];\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n //trim ending zeros for floating number\n \n const eNotation = match[4] || match[6];\n if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== \".\") return str; //-0123\n else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== \".\") return str; //0123\n else{//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const numStr = \"\" + num;\n if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation\n if(options.eNotation) return num;\n else return str;\n }else if(eNotation){ //given number has enotation\n if(options.eNotation) return num;\n else return str;\n }else if(trimmedStr.indexOf(\".\") !== -1){ //floating number\n // const decimalPart = match[5].substr(1);\n // const intPart = trimmedStr.substr(0,trimmedStr.indexOf(\".\"));\n\n \n // const p = numStr.indexOf(\".\");\n // const givenIntPart = numStr.substr(0,p);\n // const givenDecPart = numStr.substr(p+1);\n if(numStr === \"0\" && (numTrimmedByZeros === \"\") ) return num; //0.0\n else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if( sign && numStr === \"-\"+numTrimmedByZeros) return num;\n else return str;\n }\n \n if(leadingZeros){\n // if(numTrimmedByZeros === numStr){\n // if(options.leadingZeros) return num;\n // else return str;\n // }else return str;\n if(numTrimmedByZeros === numStr) return num;\n else if(sign+numTrimmedByZeros === numStr) return num;\n else return str;\n }\n\n if(trimmedStr === numStr) return num;\n else if(trimmedStr === sign+numStr) return num;\n // else{\n // //number with +/- sign\n // trimmedStr.test(/[-+][0-9]);\n\n // }\n return str;\n }\n // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;\n \n }else{ //non-numeric string\n return str;\n }\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr){\n if(numStr && numStr.indexOf(\".\") !== -1){//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if(numStr === \".\") numStr = \"0\";\n else if(numStr[0] === \".\") numStr = \"0\"+numStr;\n else if(numStr[numStr.length-1] === \".\") numStr = numStr.substr(0,numStr.length-1);\n return numStr;\n }\n return numStr;\n}\nmodule.exports = toNumber\n\n\n/***/ }),\n\n/***/ \"./node_modules/webpack/buildin/amd-options.js\":\n/*!****************************************!*\\\n !*** (webpack)/buildin/amd-options.js ***!\n \\****************************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\n/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */\nmodule.exports = __webpack_amd_options__;\n\n/* WEBPACK VAR INJECTION */}.call(this, {}))\n\n/***/ }),\n\n/***/ \"./node_modules/webpack/buildin/module.js\":\n/*!***********************************!*\\\n !*** (webpack)/buildin/module.js ***!\n \\***********************************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nmodule.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n\n\n/***/ }),\n\n/***/ \"./package.json\":\n/*!**********************!*\\\n !*** ./package.json ***!\n \\**********************/\n/*! exports provided: name, version, description, main, types, scripts, repository, keywords, author, license, bugs, homepage, dependencies, devDependencies, default */\n/***/ (function(module) {\n\nmodule.exports = JSON.parse(\"{\\\"name\\\":\\\"cos-js-sdk-v5\\\",\\\"version\\\":\\\"1.8.7\\\",\\\"description\\\":\\\"JavaScript SDK for [\u817E\u8BAF\u4E91\u5BF9\u8C61\u5B58\u50A8](https://cloud.tencent.com/product/cos)\\\",\\\"main\\\":\\\"dist/cos-js-sdk-v5.js\\\",\\\"types\\\":\\\"index.d.ts\\\",\\\"scripts\\\":{\\\"prettier\\\":\\\"prettier --write src demo/demo.js demo/CIDemos/*.js test/test.js server/sts.js lib/request.js index.d.ts\\\",\\\"server\\\":\\\"node server/sts.js\\\",\\\"dev\\\":\\\"cross-env NODE_ENV=development webpack -w --mode=development\\\",\\\"build\\\":\\\"cross-env NODE_ENV=production webpack --mode=production\\\",\\\"cos-auth.min.js\\\":\\\"uglifyjs ./demo/common/cos-auth.js -o ./demo/common/cos-auth.min.js -c -m\\\",\\\"test\\\":\\\"jest --runInBand --coverage\\\"},\\\"repository\\\":{\\\"type\\\":\\\"git\\\",\\\"url\\\":\\\"git+https://github.com/tencentyun/cos-js-sdk-v5.git\\\"},\\\"keywords\\\":[],\\\"author\\\":\\\"carsonxu\\\",\\\"license\\\":\\\"ISC\\\",\\\"bugs\\\":{\\\"url\\\":\\\"https://github.com/tencentyun/cos-js-sdk-v5/issues\\\"},\\\"homepage\\\":\\\"https://github.com/tencentyun/cos-js-sdk-v5#readme\\\",\\\"dependencies\\\":{\\\"fast-xml-parser\\\":\\\"4.5.0\\\"},\\\"devDependencies\\\":{\\\"@babel/core\\\":\\\"7.17.9\\\",\\\"@babel/plugin-transform-runtime\\\":\\\"7.18.10\\\",\\\"@babel/preset-env\\\":\\\"7.16.11\\\",\\\"babel-loader\\\":\\\"8.2.5\\\",\\\"body-parser\\\":\\\"^1.18.3\\\",\\\"cross-env\\\":\\\"^5.2.0\\\",\\\"express\\\":\\\"^4.16.4\\\",\\\"jest\\\":\\\"^29.3.1\\\",\\\"jest-environment-jsdom\\\":\\\"^29.3.1\\\",\\\"prettier\\\":\\\"^3.0.1\\\",\\\"qcloud-cos-sts\\\":\\\"^3.0.2\\\",\\\"request\\\":\\\"^2.87.0\\\",\\\"terser-webpack-plugin\\\":\\\"4.2.3\\\",\\\"uglifyjs\\\":\\\"^2.4.11\\\",\\\"webpack\\\":\\\"4.46.0\\\",\\\"webpack-cli\\\":\\\"4.10.0\\\"}}\");\n\n/***/ }),\n\n/***/ \"./src/advance.js\":\n/*!************************!*\\\n !*** ./src/advance.js ***!\n \\************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\nvar session = __webpack_require__(/*! ./session */ \"./src/session.js\");\nvar Async = __webpack_require__(/*! ./async */ \"./src/async.js\");\nvar EventProxy = __webpack_require__(/*! ./event */ \"./src/event.js\").EventProxy;\nvar util = __webpack_require__(/*! ./util */ \"./src/util.js\");\nvar Tracker = __webpack_require__(/*! ./tracker */ \"./src/tracker.js\");\n\n// \u6587\u4EF6\u5206\u5757\u4E0A\u4F20\u5168\u8FC7\u7A0B\uFF0C\u66B4\u9732\u7684\u5206\u5757\u4E0A\u4F20\u63A5\u53E3\nfunction sliceUploadFile(params, callback) {\n var self = this;\n var ep = new EventProxy();\n var TaskId = params.TaskId;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var Body = params.Body;\n var ChunkSize = params.ChunkSize || params.SliceSize || self.options.ChunkSize;\n var AsyncLimit = params.AsyncLimit;\n var StorageClass = params.StorageClass;\n var ServerSideEncryption = params.ServerSideEncryption;\n var FileSize;\n var onProgress;\n var onHashProgress = params.onHashProgress;\n var tracker = params.tracker;\n tracker && tracker.setParams({\n chunkSize: ChunkSize\n });\n\n // \u4E0A\u4F20\u8FC7\u7A0B\u4E2D\u51FA\u73B0\u9519\u8BEF\uFF0C\u8FD4\u56DE\u9519\u8BEF\n ep.on('error', function (err) {\n if (!self._isRunningTask(TaskId)) return;\n if (params.UploadData.UploadId) {\n session.removeUsing(params.UploadData.UploadId);\n }\n err.UploadId = params.UploadData.UploadId || '';\n return callback(err);\n });\n\n // \u4E0A\u4F20\u5206\u5757\u5B8C\u6210\uFF0C\u5F00\u59CB uploadSliceComplete \u64CD\u4F5C\n ep.on('upload_complete', function (UploadCompleteData) {\n var _UploadCompleteData = util.extend({\n UploadId: params.UploadData.UploadId || ''\n }, UploadCompleteData);\n callback(null, _UploadCompleteData);\n });\n\n // \u4E0A\u4F20\u5206\u5757\u5B8C\u6210\uFF0C\u5F00\u59CB uploadSliceComplete \u64CD\u4F5C\n ep.on('upload_slice_complete', function (UploadData) {\n var metaHeaders = {};\n util.each(params.Headers, function (val, k) {\n var shortKey = k.toLowerCase();\n if (shortKey.indexOf('x-cos-meta-') === 0 || ['pic-operations', 'x-cos-callback', 'x-cos-callback-var', 'x-cos-return-body'].includes(shortKey)) {\n metaHeaders[k] = val;\n }\n });\n uploadSliceComplete.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadData.UploadId,\n SliceList: UploadData.SliceList,\n Headers: metaHeaders,\n tracker: tracker\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n session.removeUsing(UploadData.UploadId);\n if (err) {\n onProgress(null, true);\n return ep.emit('error', err);\n }\n session.removeUploadId.call(self, UploadData.UploadId);\n onProgress({\n loaded: FileSize,\n total: FileSize\n }, true);\n ep.emit('upload_complete', data);\n });\n });\n\n // \u83B7\u53D6 UploadId \u5B8C\u6210\uFF0C\u5F00\u59CB\u4E0A\u4F20\u6BCF\u4E2A\u5206\u7247\n ep.on('get_upload_data_finish', function (UploadData) {\n // \u5904\u7406 UploadId \u7F13\u5B58\n var uuid = session.getFileId(Body, params.ChunkSize, Bucket, Key);\n uuid && session.saveUploadId.call(self, uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // \u7F13\u5B58 UploadId\n session.setUsing(UploadData.UploadId); // \u6807\u8BB0 UploadId \u4E3A\u6B63\u5728\u4F7F\u7528\n\n // \u83B7\u53D6 UploadId\n onProgress(null, true); // \u4EFB\u52A1\u72B6\u6001\u5F00\u59CB uploading\n uploadSliceList.call(self, {\n TaskId: TaskId,\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n Body: Body,\n FileSize: FileSize,\n SliceSize: ChunkSize,\n AsyncLimit: AsyncLimit,\n ServerSideEncryption: ServerSideEncryption,\n UploadData: UploadData,\n Headers: params.Headers,\n onProgress: onProgress,\n tracker: tracker\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) {\n onProgress(null, true);\n return ep.emit('error', err);\n }\n ep.emit('upload_slice_complete', data);\n });\n });\n\n // \u5F00\u59CB\u83B7\u53D6\u6587\u4EF6 UploadId\uFF0C\u91CC\u9762\u4F1A\u89C6\u60C5\u51B5\u8BA1\u7B97 ETag\uFF0C\u5E76\u6BD4\u5BF9\uFF0C\u4FDD\u8BC1\u6587\u4EF6\u4E00\u81F4\u6027\uFF0C\u4E5F\u4F18\u5316\u4E0A\u4F20\n ep.on('get_file_size_finish', function () {\n onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);\n if (params.UploadData.UploadId) {\n ep.emit('get_upload_data_finish', params.UploadData);\n } else {\n var _params = util.extend({\n TaskId: TaskId,\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n Headers: params.Headers,\n StorageClass: StorageClass,\n Body: Body,\n FileSize: FileSize,\n SliceSize: ChunkSize,\n onHashProgress: onHashProgress,\n tracker: tracker\n }, params);\n getUploadIdAndPartList.call(self, _params, function (err, UploadData) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return ep.emit('error', err);\n params.UploadData.UploadId = UploadData.UploadId;\n params.UploadData.PartList = UploadData.PartList;\n ep.emit('get_upload_data_finish', params.UploadData);\n });\n }\n });\n\n // \u83B7\u53D6\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\n FileSize = params.ContentLength;\n delete params.ContentLength;\n !params.Headers && (params.Headers = {});\n util.each(params.Headers, function (item, key) {\n if (key.toLowerCase() === 'content-length') {\n delete params.Headers[key];\n }\n });\n\n // \u63A7\u5236\u5206\u7247\u5927\u5C0F\n (function () {\n var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];\n var AutoChunkSize = 1024 * 1024;\n for (var i = 0; i < SIZE.length; i++) {\n AutoChunkSize = SIZE[i] * 1024 * 1024;\n if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;\n }\n params.ChunkSize = params.SliceSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);\n })();\n\n // \u5F00\u59CB\u4E0A\u4F20\n if (FileSize === 0) {\n params.Body = '';\n params.ContentLength = 0;\n params.SkipTask = true;\n self.putObject(params, callback);\n } else {\n ep.emit('get_file_size_finish');\n }\n}\n\n// \u83B7\u53D6\u4E0A\u4F20\u4EFB\u52A1\u7684 UploadId\nfunction getUploadIdAndPartList(params, callback) {\n var TaskId = params.TaskId;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var StorageClass = params.StorageClass;\n var self = this;\n\n // \u8BA1\u7B97 ETag\n var ETagMap = {};\n var FileSize = params.FileSize;\n var SliceSize = params.SliceSize;\n var SliceCount = Math.ceil(FileSize / SliceSize);\n var FinishSliceCount = 0;\n var FinishSize = 0;\n var onHashProgress = util.throttleOnProgress.call(self, FileSize, params.onHashProgress);\n var getChunkETag = function getChunkETag(PartNumber, callback) {\n var start = SliceSize * (PartNumber - 1);\n var end = Math.min(start + SliceSize, FileSize);\n var ChunkSize = end - start;\n if (ETagMap[PartNumber]) {\n callback(null, {\n PartNumber: PartNumber,\n ETag: ETagMap[PartNumber],\n Size: ChunkSize\n });\n } else {\n util.fileSlice(params.Body, start, end, false, function (chunkItem) {\n util.getFileMd5(chunkItem, function (err, md5) {\n if (err) return callback(util.error(err));\n var ETag = '\"' + md5 + '\"';\n ETagMap[PartNumber] = ETag;\n FinishSliceCount += 1;\n FinishSize += ChunkSize;\n onHashProgress({\n loaded: FinishSize,\n total: FileSize\n });\n callback(null, {\n PartNumber: PartNumber,\n ETag: ETag,\n Size: ChunkSize\n });\n });\n });\n }\n };\n\n // \u901A\u8FC7\u548C\u6587\u4EF6\u7684 md5 \u5BF9\u6BD4\uFF0C\u5224\u65AD UploadId \u662F\u5426\u53EF\u7528\n var isAvailableUploadList = function isAvailableUploadList(PartList, callback) {\n var PartCount = PartList.length;\n // \u5982\u679C\u6CA1\u6709\u5206\u7247\uFF0C\u901A\u8FC7\n if (PartCount === 0) {\n return callback(null, true);\n }\n // \u68C0\u67E5\u5206\u7247\u6570\u91CF\n if (PartCount > SliceCount) {\n return callback(null, false);\n }\n // \u68C0\u67E5\u5206\u7247\u5927\u5C0F\n if (PartCount > 1) {\n var PartSliceSize = Math.max(PartList[0].Size, PartList[1].Size);\n if (PartSliceSize !== SliceSize) {\n return callback(null, false);\n }\n }\n // \u9010\u4E2A\u5206\u7247\u8BA1\u7B97\u5E76\u68C0\u67E5 ETag \u662F\u5426\u4E00\u81F4\n var next = function next(index) {\n if (index < PartCount) {\n var Part = PartList[index];\n getChunkETag(Part.PartNumber, function (err, chunk) {\n if (chunk && chunk.ETag === Part.ETag && chunk.Size === Part.Size) {\n next(index + 1);\n } else {\n callback(null, false);\n }\n });\n } else {\n callback(null, true);\n }\n };\n next(0);\n };\n var ep = new EventProxy();\n ep.on('error', function (errData) {\n if (!self._isRunningTask(TaskId)) return;\n return callback(errData);\n });\n\n // \u5B58\u5728 UploadId\n ep.on('upload_id_available', function (UploadData) {\n // \u8F6C\u6362\u6210 map\n var map = {};\n var list = [];\n util.each(UploadData.PartList, function (item) {\n map[item.PartNumber] = item;\n });\n for (var PartNumber = 1; PartNumber <= SliceCount; PartNumber++) {\n var item = map[PartNumber];\n if (item) {\n item.PartNumber = PartNumber;\n item.Uploaded = true;\n } else {\n item = {\n PartNumber: PartNumber,\n ETag: null,\n Uploaded: false\n };\n }\n list.push(item);\n }\n UploadData.PartList = list;\n callback(null, UploadData);\n });\n\n // \u4E0D\u5B58\u5728 UploadId, \u521D\u59CB\u5316\u751F\u6210 UploadId\n ep.on('no_available_upload_id', function () {\n if (!self._isRunningTask(TaskId)) return;\n var _params = util.extend({\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n Query: util.clone(params.Query),\n StorageClass: StorageClass,\n Body: params.Body,\n calledBySdk: 'sliceUploadFile',\n tracker: params.tracker\n }, params);\n var headers = util.clone(params.Headers);\n delete headers['x-cos-mime-limit'];\n _params.Headers = headers;\n self.multipartInit(_params, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return ep.emit('error', err);\n var UploadId = data.UploadId;\n if (!UploadId) {\n return callback(util.error(new Error('no such upload id')));\n }\n ep.emit('upload_id_available', {\n UploadId: UploadId,\n PartList: []\n });\n });\n });\n\n // \u5982\u679C\u5DF2\u5B58\u5728 UploadId\uFF0C\u627E\u4E00\u4E2A\u53EF\u4EE5\u7528\u7684 UploadId\n ep.on('has_and_check_upload_id', function (UploadIdList) {\n // \u4E32\u884C\u5730\uFF0C\u627E\u4E00\u4E2A\u5185\u5BB9\u4E00\u81F4\u7684 UploadId\n UploadIdList = UploadIdList.reverse();\n Async.eachLimit(UploadIdList, 1, function (UploadId, asyncCallback) {\n if (!self._isRunningTask(TaskId)) return;\n // \u5982\u679C\u6B63\u5728\u4E0A\u4F20\uFF0C\u8DF3\u8FC7\n if (session.using[UploadId]) {\n asyncCallback(); // \u68C0\u67E5\u4E0B\u4E00\u4E2A UploadId\n return;\n }\n // \u5224\u65AD UploadId \u662F\u5426\u53EF\u7528\n wholeMultipartListPart.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadId,\n tracker: params.tracker\n }, function (err, PartListData) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) {\n session.removeUsing(UploadId);\n return ep.emit('error', err);\n }\n var PartList = PartListData.PartList;\n PartList.forEach(function (item) {\n item.PartNumber *= 1;\n item.Size *= 1;\n item.ETag = item.ETag || '';\n });\n isAvailableUploadList(PartList, function (err, isAvailable) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return ep.emit('error', err);\n if (isAvailable) {\n asyncCallback({\n UploadId: UploadId,\n PartList: PartList\n }); // \u9A6C\u4E0A\u7ED3\u675F\n } else {\n asyncCallback(); // \u68C0\u67E5\u4E0B\u4E00\u4E2A UploadId\n }\n });\n });\n }, function (AvailableUploadData) {\n if (!self._isRunningTask(TaskId)) return;\n onHashProgress(null, true);\n if (AvailableUploadData && AvailableUploadData.UploadId) {\n ep.emit('upload_id_available', AvailableUploadData);\n } else {\n ep.emit('no_available_upload_id');\n }\n });\n });\n\n // \u5728\u672C\u5730\u7F13\u5B58\u627E\u53EF\u7528\u7684 UploadId\n ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) {\n // \u5728\u672C\u5730\u627E\u53EF\u7528\u7684 UploadId\n var uuid = session.getFileId(params.Body, params.ChunkSize, Bucket, Key);\n var LocalUploadIdList = session.getUploadIdList.call(self, uuid);\n if (!uuid || !LocalUploadIdList) {\n ep.emit('has_and_check_upload_id', RemoteUploadIdList);\n return;\n }\n var next = function next(index) {\n // \u5982\u679C\u672C\u5730\u627E\u4E0D\u5230\u53EF\u7528 UploadId\uFF0C\u518D\u4E00\u4E2A\u4E2A\u904D\u5386\u6821\u9A8C\u8FDC\u7AEF\n if (index >= LocalUploadIdList.length) {\n ep.emit('has_and_check_upload_id', RemoteUploadIdList);\n return;\n }\n var UploadId = LocalUploadIdList[index];\n // \u5982\u679C\u4E0D\u5728\u8FDC\u7AEF UploadId \u5217\u8868\u91CC\uFF0C\u8DF3\u8FC7\u5E76\u5220\u9664\n if (!util.isInArray(RemoteUploadIdList, UploadId)) {\n session.removeUploadId.call(self, UploadId);\n next(index + 1);\n return;\n }\n // \u5982\u679C\u6B63\u5728\u4E0A\u4F20\uFF0C\u8DF3\u8FC7\n if (session.using[UploadId]) {\n next(index + 1);\n return;\n }\n // \u5224\u65AD UploadId \u662F\u5426\u5B58\u5728\u7EBF\u4E0A\n wholeMultipartListPart.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadId,\n tracker: params.tracker\n }, function (err, PartListData) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) {\n // \u5982\u679C UploadId \u83B7\u53D6\u4F1A\u51FA\u9519\uFF0C\u8DF3\u8FC7\u5E76\u5220\u9664\n session.removeUploadId.call(self, UploadId);\n next(index + 1);\n } else {\n // \u627E\u5230\u53EF\u7528 UploadId\n ep.emit('upload_id_available', {\n UploadId: UploadId,\n PartList: PartListData.PartList\n });\n }\n });\n };\n next(0);\n });\n\n // \u83B7\u53D6\u7EBF\u4E0A UploadId \u5217\u8868\n ep.on('get_remote_upload_id_list', function () {\n // \u83B7\u53D6\u7B26\u5408\u6761\u4EF6\u7684 UploadId \u5217\u8868\uFF0C\u56E0\u4E3A\u540C\u4E00\u4E2A\u6587\u4EF6\u53EF\u4EE5\u6709\u591A\u4E2A\u4E0A\u4F20\u4EFB\u52A1\u3002\n wholeMultipartList.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n tracker: params.tracker\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return ep.emit('error', err);\n // \u6574\u7406\u8FDC\u7AEF UploadId \u5217\u8868\n var RemoteUploadIdList = util.filter(data.UploadList, function (item) {\n return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase());\n }).reverse().map(function (item) {\n return item.UploadId || item.UploadID;\n });\n if (RemoteUploadIdList.length) {\n ep.emit('seek_local_avail_upload_id', RemoteUploadIdList);\n } else {\n // \u8FDC\u7AEF\u6CA1\u6709 UploadId\uFF0C\u6E05\u7406\u7F13\u5B58\u7684 UploadId\n var uuid = session.getFileId(params.Body, params.ChunkSize, Bucket, Key),\n LocalUploadIdList;\n if (uuid && (LocalUploadIdList = session.getUploadIdList.call(self, uuid))) {\n util.each(LocalUploadIdList, function (UploadId) {\n session.removeUploadId.call(self, UploadId);\n });\n }\n ep.emit('no_available_upload_id');\n }\n });\n });\n\n // \u5F00\u59CB\u627E\u53EF\u7528 UploadId\n ep.emit('get_remote_upload_id_list');\n}\n\n// \u83B7\u53D6\u7B26\u5408\u6761\u4EF6\u7684\u5168\u90E8\u4E0A\u4F20\u4EFB\u52A1 (\u6761\u4EF6\u5305\u62EC Bucket, Region, Prefix)\nfunction wholeMultipartList(params, callback) {\n var self = this;\n var UploadList = [];\n var sendParams = {\n Bucket: params.Bucket,\n Region: params.Region,\n Prefix: params.Key,\n calledBySdk: params.calledBySdk || 'sliceUploadFile',\n tracker: params.tracker\n };\n var next = function next() {\n self.multipartList(sendParams, function (err, data) {\n if (err) return callback(err);\n UploadList.push.apply(UploadList, data.Upload || []);\n if (data.IsTruncated === 'true') {\n // \u5217\u8868\u4E0D\u5B8C\u6574\n sendParams.KeyMarker = data.NextKeyMarker;\n sendParams.UploadIdMarker = data.NextUploadIdMarker;\n next();\n } else {\n callback(null, {\n UploadList: UploadList\n });\n }\n });\n };\n next();\n}\n\n// \u83B7\u53D6\u6307\u5B9A\u4E0A\u4F20\u4EFB\u52A1\u7684\u5206\u5757\u5217\u8868\nfunction wholeMultipartListPart(params, callback) {\n var self = this;\n var PartList = [];\n var sendParams = {\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n UploadId: params.UploadId,\n calledBySdk: 'sliceUploadFile',\n tracker: params.tracker\n };\n var next = function next() {\n self.multipartListPart(sendParams, function (err, data) {\n if (err) return callback(err);\n PartList.push.apply(PartList, data.Part || []);\n if (data.IsTruncated === 'true') {\n // \u5217\u8868\u4E0D\u5B8C\u6574\n sendParams.PartNumberMarker = data.NextPartNumberMarker;\n next();\n } else {\n callback(null, {\n PartList: PartList\n });\n }\n });\n };\n next();\n}\n\n// \u4E0A\u4F20\u6587\u4EF6\u5206\u5757\uFF0C\u5305\u62EC\n/*\n UploadId (\u4E0A\u4F20\u4EFB\u52A1\u7F16\u53F7)\n AsyncLimit (\u5E76\u53D1\u91CF)\uFF0C\n SliceList (\u4E0A\u4F20\u7684\u5206\u5757\u6570\u7EC4)\uFF0C\n FilePath (\u672C\u5730\u6587\u4EF6\u7684\u4F4D\u7F6E)\uFF0C\n SliceSize (\u6587\u4EF6\u5206\u5757\u5927\u5C0F)\n FileSize (\u6587\u4EF6\u5927\u5C0F)\n onProgress (\u4E0A\u4F20\u6210\u529F\u4E4B\u540E\u7684\u56DE\u8C03\u51FD\u6570)\n */\nfunction uploadSliceList(params, cb) {\n var self = this;\n var TaskId = params.TaskId;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var UploadData = params.UploadData;\n var FileSize = params.FileSize;\n var SliceSize = params.SliceSize;\n var ChunkParallel = Math.min(params.AsyncLimit || self.options.ChunkParallelLimit || 1, 256);\n var Body = params.Body;\n var SliceCount = Math.ceil(FileSize / SliceSize);\n var FinishSize = 0;\n var ServerSideEncryption = params.ServerSideEncryption;\n var Headers = params.Headers;\n var needUploadSlices = util.filter(UploadData.PartList, function (SliceItem) {\n if (SliceItem['Uploaded']) {\n FinishSize += SliceItem['PartNumber'] >= SliceCount ? FileSize % SliceSize || SliceSize : SliceSize;\n }\n return !SliceItem['Uploaded'];\n });\n var _onProgress2 = params.onProgress;\n Async.eachLimit(needUploadSlices, ChunkParallel, function (SliceItem, asyncCallback) {\n if (!self._isRunningTask(TaskId)) return;\n var PartNumber = SliceItem['PartNumber'];\n var currentSize = Math.min(FileSize, SliceItem['PartNumber'] * SliceSize) - (SliceItem['PartNumber'] - 1) * SliceSize;\n var preAddSize = 0;\n uploadSliceItem.call(self, {\n TaskId: TaskId,\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n SliceSize: SliceSize,\n FileSize: FileSize,\n PartNumber: PartNumber,\n ServerSideEncryption: ServerSideEncryption,\n Body: Body,\n UploadData: UploadData,\n Headers: Headers,\n onProgress: function onProgress(data) {\n FinishSize += data.loaded - preAddSize;\n preAddSize = data.loaded;\n _onProgress2({\n loaded: FinishSize,\n total: FileSize\n });\n },\n tracker: params.tracker\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n if (!err && !data.ETag) err = 'get ETag error, please add \"ETag\" to CORS ExposeHeader setting.( \u83B7\u53D6ETag\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0ETag\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 )';\n if (err) {\n FinishSize -= preAddSize;\n } else {\n FinishSize += currentSize - preAddSize;\n SliceItem.ETag = data.ETag;\n }\n _onProgress2({\n loaded: FinishSize,\n total: FileSize\n });\n asyncCallback(err || null, data);\n });\n }, function (err) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return cb(err);\n cb(null, {\n UploadId: UploadData.UploadId,\n SliceList: UploadData.PartList\n });\n });\n}\n\n// \u4E0A\u4F20\u6307\u5B9A\u5206\u7247\nfunction uploadSliceItem(params, callback) {\n var self = this;\n var TaskId = params.TaskId;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var FileSize = params.FileSize;\n var FileBody = params.Body;\n var PartNumber = params.PartNumber * 1;\n var SliceSize = params.SliceSize;\n var ServerSideEncryption = params.ServerSideEncryption;\n var UploadData = params.UploadData;\n var Headers = params.Headers || {};\n var ChunkRetryTimes = self.options.ChunkRetryTimes + 1;\n var start = SliceSize * (PartNumber - 1);\n var ContentLength = SliceSize;\n var end = start + SliceSize;\n if (end > FileSize) {\n end = FileSize;\n ContentLength = end - start;\n }\n var headersWhiteList = ['x-cos-traffic-limit', 'x-cos-mime-limit'];\n var headers = {};\n util.each(Headers, function (v, k) {\n if (headersWhiteList.indexOf(k) > -1) {\n headers[k] = v;\n }\n });\n var PartItem = UploadData.PartList[PartNumber - 1];\n Async.retry(ChunkRetryTimes, function (tryCallback) {\n if (!self._isRunningTask(TaskId)) return;\n util.fileSlice(FileBody, start, end, true, function (Body) {\n self.multipartUpload({\n TaskId: TaskId,\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n ContentLength: ContentLength,\n PartNumber: PartNumber,\n UploadId: UploadData.UploadId,\n ServerSideEncryption: ServerSideEncryption,\n Body: Body,\n Headers: headers,\n onProgress: params.onProgress,\n calledBySdk: 'sliceUploadFile',\n tracker: params.tracker\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n if (err) return tryCallback(err);\n PartItem.Uploaded = true;\n return tryCallback(null, data);\n });\n });\n }, function (err, data) {\n if (!self._isRunningTask(TaskId)) return;\n return callback(err, data);\n });\n}\n\n// \u5B8C\u6210\u5206\u5757\u4E0A\u4F20\nfunction uploadSliceComplete(params, callback) {\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var UploadId = params.UploadId;\n var SliceList = params.SliceList;\n var self = this;\n var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;\n var Headers = params.Headers;\n var Parts = SliceList.map(function (item) {\n return {\n PartNumber: item.PartNumber,\n ETag: item.ETag\n };\n });\n // \u5B8C\u6210\u4E0A\u4F20\u7684\u8BF7\u6C42\u4E5F\u505A\u91CD\u8BD5\n Async.retry(ChunkRetryTimes, function (tryCallback) {\n self.multipartComplete({\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadId,\n Parts: Parts,\n Headers: Headers,\n calledBySdk: 'sliceUploadFile',\n tracker: params.tracker\n }, tryCallback);\n }, function (err, data) {\n callback(err, data);\n });\n}\n\n// \u629B\u5F03\u5206\u5757\u4E0A\u4F20\u4EFB\u52A1\n/*\n AsyncLimit (\u629B\u5F03\u4E0A\u4F20\u4EFB\u52A1\u7684\u5E76\u53D1\u91CF)\uFF0C\n UploadId (\u4E0A\u4F20\u4EFB\u52A1\u7684\u7F16\u53F7\uFF0C\u5F53 Level \u4E3A task \u65F6\u5019\u9700\u8981)\n Level (\u629B\u5F03\u5206\u5757\u4E0A\u4F20\u4EFB\u52A1\u7684\u7EA7\u522B\uFF0Ctask : \u629B\u5F03\u6307\u5B9A\u7684\u4E0A\u4F20\u4EFB\u52A1\uFF0Cfile \uFF1A \u629B\u5F03\u6307\u5B9A\u7684\u6587\u4EF6\u5BF9\u5E94\u7684\u4E0A\u4F20\u4EFB\u52A1\uFF0C\u5176\u4ED6\u503C \uFF1A\u629B\u5F03\u6307\u5B9ABucket \u7684\u5168\u90E8\u4E0A\u4F20\u4EFB\u52A1)\n */\nfunction abortUploadTask(params, callback) {\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var UploadId = params.UploadId;\n var Level = params.Level || 'task';\n var AsyncLimit = params.AsyncLimit;\n var self = this;\n var ep = new EventProxy();\n ep.on('error', function (errData) {\n return callback(errData);\n });\n\n // \u5DF2\u7ECF\u83B7\u53D6\u5230\u9700\u8981\u629B\u5F03\u7684\u4EFB\u52A1\u5217\u8868\n ep.on('get_abort_array', function (AbortArray) {\n abortUploadTaskArray.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n Headers: params.Headers,\n AsyncLimit: AsyncLimit,\n AbortArray: AbortArray\n }, callback);\n });\n if (Level === 'bucket') {\n // Bucket \u7EA7\u522B\u7684\u4EFB\u52A1\u629B\u5F03\uFF0C\u629B\u5F03\u8BE5 Bucket \u4E0B\u7684\u5168\u90E8\u4E0A\u4F20\u4EFB\u52A1\n wholeMultipartList.call(self, {\n Bucket: Bucket,\n Region: Region,\n calledBySdk: 'abortUploadTask'\n }, function (err, data) {\n if (err) return callback(err);\n ep.emit('get_abort_array', data.UploadList || []);\n });\n } else if (Level === 'file') {\n // \u6587\u4EF6\u7EA7\u522B\u7684\u4EFB\u52A1\u629B\u5F03\uFF0C\u629B\u5F03\u8BE5\u6587\u4EF6\u7684\u5168\u90E8\u4E0A\u4F20\u4EFB\u52A1\n if (!Key) return callback(util.error(new Error('abort_upload_task_no_key')));\n wholeMultipartList.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n calledBySdk: 'abortUploadTask'\n }, function (err, data) {\n if (err) return callback(err);\n ep.emit('get_abort_array', data.UploadList || []);\n });\n } else if (Level === 'task') {\n // \u5355\u4E2A\u4EFB\u52A1\u7EA7\u522B\u7684\u4EFB\u52A1\u629B\u5F03\uFF0C\u629B\u5F03\u6307\u5B9A UploadId \u7684\u4E0A\u4F20\u4EFB\u52A1\n if (!UploadId) return callback(util.error(new Error('abort_upload_task_no_id')));\n if (!Key) return callback(util.error(new Error('abort_upload_task_no_key')));\n ep.emit('get_abort_array', [{\n Key: Key,\n UploadId: UploadId\n }]);\n } else {\n return callback(util.error(new Error('abort_unknown_level')));\n }\n}\n\n// \u6279\u91CF\u629B\u5F03\u5206\u5757\u4E0A\u4F20\u4EFB\u52A1\nfunction abortUploadTaskArray(params, callback) {\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var AbortArray = params.AbortArray;\n var AsyncLimit = params.AsyncLimit || 1;\n var self = this;\n var index = 0;\n var resultList = new Array(AbortArray.length);\n Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, nextItem) {\n var eachIndex = index;\n if (Key && Key !== AbortItem.Key) {\n resultList[eachIndex] = {\n error: {\n KeyNotMatch: true\n }\n };\n nextItem(null);\n return;\n }\n var UploadId = AbortItem.UploadId || AbortItem.UploadID;\n self.multipartAbort({\n Bucket: Bucket,\n Region: Region,\n Key: AbortItem.Key,\n Headers: params.Headers,\n UploadId: UploadId\n }, function (err) {\n var task = {\n Bucket: Bucket,\n Region: Region,\n Key: AbortItem.Key,\n UploadId: UploadId\n };\n resultList[eachIndex] = {\n error: err,\n task: task\n };\n nextItem(null);\n });\n index++;\n }, function (err) {\n if (err) return callback(err);\n var successList = [];\n var errorList = [];\n for (var i = 0, len = resultList.length; i < len; i++) {\n var item = resultList[i];\n if (item['task']) {\n if (item['error']) {\n errorList.push(item['task']);\n } else {\n successList.push(item['task']);\n }\n }\n }\n return callback(null, {\n successList: successList,\n errorList: errorList\n });\n });\n}\n\n// \u9AD8\u7EA7\u4E0A\u4F20\nfunction uploadFile(params, callback) {\n var self = this;\n\n // \u5224\u65AD\u591A\u5927\u7684\u6587\u4EF6\u4F7F\u7528\u5206\u7247\u4E0A\u4F20\n var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;\n var taskList = [];\n var Body = params.Body;\n var FileSize = Body.size || Body.length || 0;\n var fileInfo = {\n TaskId: ''\n };\n\n // \u4E0A\u4F20\u94FE\u8DEF\n if (self.options.EnableReporter) {\n var accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');\n var realApi = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';\n params.tracker = new Tracker({\n Beacon: self.options.BeaconReporter,\n clsReporter: self.options.ClsReporter,\n bucket: params.Bucket,\n region: params.Region,\n apiName: 'uploadFile',\n realApi: realApi,\n fileKey: params.Key,\n fileSize: FileSize,\n accelerate: accelerate,\n deepTracker: self.options.DeepTracker,\n customId: self.options.CustomId,\n delay: self.options.TrackerDelay\n });\n }\n\n // \u6574\u7406 option\uFF0C\u7528\u4E8E\u8FD4\u56DE\u7ED9\u56DE\u8C03\n util.each(params, function (v, k) {\n if (_typeof(v) !== 'object' && typeof v !== 'function') {\n fileInfo[k] = v;\n }\n });\n\n // \u5904\u7406\u6587\u4EF6 TaskReady\n var _onTaskReady = params.onTaskReady;\n var onTaskReady = function onTaskReady(tid) {\n fileInfo.TaskId = tid;\n _onTaskReady && _onTaskReady(tid);\n };\n params.onTaskReady = onTaskReady;\n\n // \u6DFB\u52A0\u4E0A\u4F20\u4EFB\u52A1,\u8D85\u8FC7\u9608\u503C\u4F7F\u7528\u5206\u5757\u4E0A\u4F20\uFF0C\u5C0F\u4E8E\u7B49\u4E8E\u5219\u7B80\u5355\u4E0A\u4F20\n var api = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';\n\n // \u5904\u7406\u6587\u4EF6\u5B8C\u6210\n var _onFileFinish = params.onFileFinish;\n var onFileFinish = function onFileFinish(err, data) {\n // \u683C\u5F0F\u5316\u4E0A\u62A5\u53C2\u6570\u5E76\u4E0A\u62A5\n params.tracker && params.tracker.report(err, data);\n _onFileFinish && _onFileFinish(err, data, fileInfo);\n callback && callback(err, data);\n };\n taskList.push({\n api: api,\n params: params,\n callback: onFileFinish\n });\n self._addTasks(taskList);\n}\n\n// \u6279\u91CF\u4E0A\u4F20\u6587\u4EF6\nfunction uploadFiles(params, callback) {\n var self = this;\n\n // \u5224\u65AD\u591A\u5927\u7684\u6587\u4EF6\u4F7F\u7528\u5206\u7247\u4E0A\u4F20\n var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;\n\n // \u6C47\u603B\u8FD4\u56DE\u8FDB\u5EA6\n var TotalSize = 0;\n var TotalFinish = 0;\n var onTotalProgress = util.throttleOnProgress.call(self, TotalFinish, params.onProgress);\n\n // \u6C47\u603B\u8FD4\u56DE\u56DE\u8C03\n var unFinishCount = params.files.length;\n var _onTotalFileFinish = params.onFileFinish;\n var resultList = Array(unFinishCount);\n var onTotalFileFinish = function onTotalFileFinish(err, data, options) {\n onTotalProgress(null, true);\n _onTotalFileFinish && _onTotalFileFinish(err, data, options);\n resultList[options.Index] = {\n options: options,\n error: err,\n data: data\n };\n if (--unFinishCount <= 0 && callback) {\n callback(null, {\n files: resultList\n });\n }\n };\n\n // \u5F00\u59CB\u5904\u7406\u6BCF\u4E2A\u6587\u4EF6\n var taskList = [];\n util.each(params.files, function (fileParams, index) {\n (function () {\n var Body = fileParams.Body;\n var FileSize = Body.size || Body.length || 0;\n var fileInfo = {\n Index: index,\n TaskId: ''\n };\n\n // \u5982\u679C \u6279\u91CF\u4E0A\u4F20\u7684 Key \u662F / \u5F00\u5934\uFF0C\u5F3A\u5236\u53BB\u6389\u7B2C\u4E00\u4E2A /\n if (!self.options.UseRawKey && fileParams.Key && fileParams.Key.substr(0, 1) === '/') {\n fileParams.Key = fileParams.Key.substr(1);\n }\n\n // \u66F4\u65B0\u6587\u4EF6\u603B\u5927\u5C0F\n TotalSize += FileSize;\n\n // \u5355\u4E2A\u6587\u4EF6\u4E0A\u4F20\u94FE\u8DEF\n if (self.options.EnableReporter) {\n var accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');\n var realApi = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';\n fileParams.tracker = new Tracker({\n Beacon: self.options.BeaconReporter,\n clsReporter: self.options.ClsReporter,\n bucket: fileParams.Bucket,\n region: fileParams.Region,\n apiName: 'uploadFiles',\n realApi: realApi,\n fileKey: fileParams.Key,\n fileSize: FileSize,\n accelerate: accelerate,\n deepTracker: self.options.DeepTracker,\n customId: self.options.CustomId,\n delay: self.options.TrackerDelay\n });\n }\n\n // \u6574\u7406 option\uFF0C\u7528\u4E8E\u8FD4\u56DE\u7ED9\u56DE\u8C03\n util.each(fileParams, function (v, k) {\n if (_typeof(v) !== 'object' && typeof v !== 'function') {\n fileInfo[k] = v;\n }\n });\n\n // \u5904\u7406\u5355\u4E2A\u6587\u4EF6 TaskReady\n var _onTaskReady = fileParams.onTaskReady;\n var onTaskReady = function onTaskReady(tid) {\n fileInfo.TaskId = tid;\n _onTaskReady && _onTaskReady(tid);\n };\n fileParams.onTaskReady = onTaskReady;\n\n // \u5904\u7406\u5355\u4E2A\u6587\u4EF6\u8FDB\u5EA6\n var PreAddSize = 0;\n var _onProgress = fileParams.onProgress;\n var onProgress = function onProgress(info) {\n TotalFinish = TotalFinish - PreAddSize + info.loaded;\n PreAddSize = info.loaded;\n _onProgress && _onProgress(info);\n onTotalProgress({\n loaded: TotalFinish,\n total: TotalSize\n });\n };\n fileParams.onProgress = onProgress;\n\n // \u6DFB\u52A0\u4E0A\u4F20\u4EFB\u52A1\n var api = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';\n\n // \u5904\u7406\u5355\u4E2A\u6587\u4EF6\u5B8C\u6210\n var _onFileFinish = fileParams.onFileFinish;\n var onFileFinish = function onFileFinish(err, data) {\n // \u683C\u5F0F\u5316\u4E0A\u62A5\u53C2\u6570\u5E76\u4E0A\u62A5\n fileParams.tracker && fileParams.tracker.report(err, data);\n _onFileFinish && _onFileFinish(err, data);\n onTotalFileFinish && onTotalFileFinish(err, data, fileInfo);\n };\n taskList.push({\n api: api,\n params: fileParams,\n callback: onFileFinish\n });\n })();\n });\n self._addTasks(taskList);\n}\n\n// \u5206\u7247\u590D\u5236\u6587\u4EF6\nfunction sliceCopyFile(params, callback) {\n var ep = new EventProxy();\n var self = this;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var CopySource = params.CopySource;\n var m = util.getSourceParams.call(this, CopySource);\n if (!m) {\n callback(util.error(new Error('CopySource format error')));\n return;\n }\n var SourceBucket = m.Bucket;\n var SourceRegion = m.Region;\n var SourceKey = decodeURIComponent(m.Key);\n var CopySliceSize = params.CopySliceSize === undefined ? self.options.CopySliceSize : params.CopySliceSize;\n CopySliceSize = Math.max(0, CopySliceSize);\n var ChunkSize = params.CopyChunkSize || this.options.CopyChunkSize;\n var ChunkParallel = this.options.CopyChunkParallelLimit;\n var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;\n var ChunkCount = 0;\n var FinishSize = 0;\n var FileSize;\n var onProgress;\n var SourceResHeaders = {};\n var SourceHeaders = {};\n var TargetHeader = {};\n\n // \u5206\u7247\u590D\u5236\u5B8C\u6210\uFF0C\u5F00\u59CB multipartComplete \u64CD\u4F5C\n ep.on('copy_slice_complete', function (UploadData) {\n var metaHeaders = {};\n util.each(params.Headers, function (val, k) {\n if (k.toLowerCase().indexOf('x-cos-meta-') === 0) metaHeaders[k] = val;\n });\n var Parts = util.map(UploadData.PartList, function (item) {\n return {\n PartNumber: item.PartNumber,\n ETag: item.ETag\n };\n });\n // \u5B8C\u6210\u4E0A\u4F20\u7684\u8BF7\u6C42\u4E5F\u505A\u91CD\u8BD5\n Async.retry(ChunkRetryTimes, function (tryCallback) {\n self.multipartComplete({\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadData.UploadId,\n Parts: Parts,\n tracker: params.tracker,\n calledBySdk: 'sliceCopyFile'\n }, tryCallback);\n }, function (err, data) {\n session.removeUsing(UploadData.UploadId); // \u6807\u8BB0 UploadId \u6CA1\u88AB\u4F7F\u7528\u4E86\uFF0C\u56E0\u4E3A\u590D\u5236\u6CA1\u63D0\u4F9B\u91CD\u8BD5\uFF0C\u6240\u4EE5\u53EA\u8981\u51FA\u9519\uFF0C\u5C31\u662F UploadId \u505C\u7528\u4E86\u3002\n if (err) {\n onProgress(null, true);\n return callback(err);\n }\n session.removeUploadId(UploadData.UploadId);\n onProgress({\n loaded: FileSize,\n total: FileSize\n }, true);\n callback(null, data);\n });\n });\n ep.on('get_copy_data_finish', function (UploadData) {\n // \u5904\u7406 UploadId \u7F13\u5B58\n var uuid = session.getCopyFileId(CopySource, SourceResHeaders, ChunkSize, Bucket, Key);\n uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // \u7F13\u5B58 UploadId\n session.setUsing(UploadData.UploadId); // \u6807\u8BB0 UploadId \u4E3A\u6B63\u5728\u4F7F\u7528\n\n var needCopySlices = util.filter(UploadData.PartList, function (SliceItem) {\n if (SliceItem['Uploaded']) {\n FinishSize += SliceItem['PartNumber'] >= ChunkCount ? FileSize % ChunkSize || ChunkSize : ChunkSize;\n }\n return !SliceItem['Uploaded'];\n });\n Async.eachLimit(needCopySlices, ChunkParallel, function (SliceItem, asyncCallback) {\n var PartNumber = SliceItem.PartNumber;\n var CopySourceRange = SliceItem.CopySourceRange;\n var currentSize = SliceItem.end - SliceItem.start;\n Async.retry(ChunkRetryTimes, function (tryCallback) {\n copySliceItem.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n CopySource: CopySource,\n UploadId: UploadData.UploadId,\n PartNumber: PartNumber,\n CopySourceRange: CopySourceRange,\n tracker: params.tracker,\n calledBySdk: 'sliceCopyFile'\n }, tryCallback);\n }, function (err, data) {\n if (err) return asyncCallback(err);\n FinishSize += currentSize;\n onProgress({\n loaded: FinishSize,\n total: FileSize\n });\n SliceItem.ETag = data.ETag;\n asyncCallback(err || null, data);\n });\n }, function (err) {\n if (err) {\n session.removeUsing(UploadData.UploadId); // \u6807\u8BB0 UploadId \u6CA1\u88AB\u4F7F\u7528\u4E86\uFF0C\u56E0\u4E3A\u590D\u5236\u6CA1\u63D0\u4F9B\u91CD\u8BD5\uFF0C\u6240\u4EE5\u53EA\u8981\u51FA\u9519\uFF0C\u5C31\u662F UploadId \u505C\u7528\u4E86\u3002\n onProgress(null, true);\n return callback(err);\n }\n ep.emit('copy_slice_complete', UploadData);\n });\n });\n ep.on('get_chunk_size_finish', function () {\n var createNewUploadId = function createNewUploadId() {\n self.multipartInit({\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n Headers: TargetHeader,\n tracker: params.tracker,\n calledBySdk: 'sliceCopyFile'\n }, function (err, data) {\n if (err) return callback(err);\n params.UploadId = data.UploadId;\n ep.emit('get_copy_data_finish', {\n UploadId: params.UploadId,\n PartList: params.PartList\n });\n });\n };\n\n // \u5728\u672C\u5730\u627E\u53EF\u7528\u7684 UploadId\n var uuid = session.getCopyFileId(CopySource, SourceResHeaders, ChunkSize, Bucket, Key);\n var LocalUploadIdList = session.getUploadIdList(uuid);\n if (!uuid || !LocalUploadIdList) return createNewUploadId();\n var next = function next(index) {\n // \u5982\u679C\u672C\u5730\u627E\u4E0D\u5230\u53EF\u7528 UploadId\uFF0C\u518D\u4E00\u4E2A\u4E2A\u904D\u5386\u6821\u9A8C\u8FDC\u7AEF\n if (index >= LocalUploadIdList.length) return createNewUploadId();\n var UploadId = LocalUploadIdList[index];\n // \u5982\u679C\u6B63\u5728\u88AB\u4F7F\u7528\uFF0C\u8DF3\u8FC7\n if (session.using[UploadId]) return next(index + 1);\n // \u5224\u65AD UploadId \u662F\u5426\u5B58\u5728\u7EBF\u4E0A\n wholeMultipartListPart.call(self, {\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n UploadId: UploadId,\n tracker: params.tracker,\n calledBySdk: 'sliceCopyFile'\n }, function (err, PartListData) {\n if (err) {\n // \u5982\u679C UploadId \u83B7\u53D6\u4F1A\u51FA\u9519\uFF0C\u8DF3\u8FC7\u5E76\u5220\u9664\n session.removeUploadId(UploadId);\n next(index + 1);\n } else {\n // \u5982\u679C\u5F02\u6B65\u56DE\u6765 UploadId \u5DF2\u7ECF\u88AB\u7528\u4E86\uFF0C\u4E5F\u8DF3\u8FC7\n if (session.using[UploadId]) return next(index + 1);\n // \u627E\u5230\u53EF\u7528 UploadId\n var finishETagMap = {};\n var offset = 0;\n util.each(PartListData.PartList, function (PartItem) {\n var size = parseInt(PartItem.Size);\n var end = offset + size - 1;\n finishETagMap[PartItem.PartNumber + '|' + offset + '|' + end] = PartItem.ETag;\n offset += size;\n });\n util.each(params.PartList, function (PartItem) {\n var ETag = finishETagMap[PartItem.PartNumber + '|' + PartItem.start + '|' + PartItem.end];\n if (ETag) {\n PartItem.ETag = ETag;\n PartItem.Uploaded = true;\n }\n });\n ep.emit('get_copy_data_finish', {\n UploadId: UploadId,\n PartList: params.PartList\n });\n }\n });\n };\n next(0);\n });\n ep.on('get_file_size_finish', function () {\n // \u63A7\u5236\u5206\u7247\u5927\u5C0F\n (function () {\n var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];\n var AutoChunkSize = 1024 * 1024;\n for (var i = 0; i < SIZE.length; i++) {\n AutoChunkSize = SIZE[i] * 1024 * 1024;\n if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;\n }\n params.ChunkSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);\n ChunkCount = Math.ceil(FileSize / ChunkSize);\n var list = [];\n for (var partNumber = 1; partNumber <= ChunkCount; partNumber++) {\n var start = (partNumber - 1) * ChunkSize;\n var end = partNumber * ChunkSize < FileSize ? partNumber * ChunkSize - 1 : FileSize - 1;\n var item = {\n PartNumber: partNumber,\n start: start,\n end: end,\n CopySourceRange: 'bytes=' + start + '-' + end\n };\n list.push(item);\n }\n params.PartList = list;\n })();\n if (params.Headers['x-cos-metadata-directive'] === 'Replaced') {\n TargetHeader = params.Headers;\n } else {\n TargetHeader = SourceHeaders;\n }\n TargetHeader['x-cos-storage-class'] = params.Headers['x-cos-storage-class'] || SourceHeaders['x-cos-storage-class'];\n TargetHeader = util.clearKey(TargetHeader);\n /**\n * \u5BF9\u4E8E\u5F52\u6863\u5B58\u50A8\u7684\u5BF9\u8C61\uFF0C\u5982\u679C\u672A\u6062\u590D\u526F\u672C\uFF0C\u5219\u4E0D\u5141\u8BB8 Copy\n */\n if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') {\n var restoreHeader = SourceHeaders['x-cos-restore'];\n if (!restoreHeader || restoreHeader === 'ongoing-request=\"true\"') {\n callback(util.error(new Error('Unrestored archive object is not allowed to be copied')));\n return;\n }\n }\n /**\n * \u53BB\u9664\u4E00\u4E9B\u65E0\u7528\u7684\u5934\u90E8\uFF0C\u89C4\u907F multipartInit \u51FA\u9519\n * \u8FD9\u4E9B\u5934\u90E8\u901A\u5E38\u662F\u5728 putObjectCopy \u65F6\u624D\u4F7F\u7528\n */\n delete TargetHeader['x-cos-copy-source'];\n delete TargetHeader['x-cos-metadata-directive'];\n delete TargetHeader['x-cos-copy-source-If-Modified-Since'];\n delete TargetHeader['x-cos-copy-source-If-Unmodified-Since'];\n delete TargetHeader['x-cos-copy-source-If-Match'];\n delete TargetHeader['x-cos-copy-source-If-None-Match'];\n ep.emit('get_chunk_size_finish');\n });\n\n // \u83B7\u53D6\u8FDC\u7AEF\u590D\u5236\u6E90\u6587\u4EF6\u7684\u5927\u5C0F\n self.headObject({\n Bucket: SourceBucket,\n Region: SourceRegion,\n Key: SourceKey,\n tracker: params.tracker,\n calledBySdk: 'sliceCopyFile'\n }, function (err, data) {\n if (err) {\n if (err.statusCode && err.statusCode === 404) {\n callback(util.error(err, {\n ErrorStatus: SourceKey + ' Not Exist'\n }));\n } else {\n callback(err);\n }\n return;\n }\n FileSize = params.FileSize = data.headers['content-length'];\n if (FileSize === undefined || !FileSize) {\n callback(util.error(new Error('get Content-Length error, please add \"Content-Length\" to CORS ExposeHeader setting.\uFF08 \u83B7\u53D6Content-Length\u5931\u8D25\uFF0C\u8BF7\u5728CORS ExposeHeader\u8BBE\u7F6E\u4E2D\u6DFB\u52A0Content-Length\uFF0C\u8BF7\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/13318 \uFF09')));\n return;\n }\n params.tracker && params.tracker.setParams({\n httpSize: FileSize\n });\n onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);\n\n // \u5F00\u59CB\u4E0A\u4F20\n if (FileSize <= CopySliceSize) {\n if (!params.Headers['x-cos-metadata-directive']) {\n params.Headers['x-cos-metadata-directive'] = 'Copy';\n }\n self.putObjectCopy(Object.assign(params, {\n calledBySdk: 'sliceCopyFile'\n }), function (err, data) {\n if (err) {\n onProgress(null, true);\n return callback(err);\n }\n onProgress({\n loaded: FileSize,\n total: FileSize\n }, true);\n callback(err, data);\n });\n } else {\n var resHeaders = data.headers;\n SourceResHeaders = resHeaders;\n SourceHeaders = {\n 'Cache-Control': resHeaders['cache-control'],\n 'Content-Disposition': resHeaders['content-disposition'],\n 'Content-Encoding': resHeaders['content-encoding'],\n 'Content-Type': resHeaders['content-type'],\n Expires: resHeaders['expires'],\n 'x-cos-storage-class': resHeaders['x-cos-storage-class']\n };\n util.each(resHeaders, function (v, k) {\n var metaPrefix = 'x-cos-meta-';\n if (k.indexOf(metaPrefix) === 0 && k.length > metaPrefix.length) {\n SourceHeaders[k] = v;\n }\n });\n ep.emit('get_file_size_finish');\n }\n });\n}\n\n// \u590D\u5236\u6307\u5B9A\u5206\u7247\nfunction copySliceItem(params, callback) {\n var TaskId = params.TaskId;\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var CopySource = params.CopySource;\n var UploadId = params.UploadId;\n var PartNumber = params.PartNumber * 1;\n var CopySourceRange = params.CopySourceRange;\n var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;\n var self = this;\n Async.retry(ChunkRetryTimes, function (tryCallback) {\n self.uploadPartCopy({\n TaskId: TaskId,\n Bucket: Bucket,\n Region: Region,\n Key: Key,\n CopySource: CopySource,\n UploadId: UploadId,\n PartNumber: PartNumber,\n CopySourceRange: CopySourceRange,\n tracker: params.tracker,\n calledBySdk: params.calledBySdk\n }, function (err, data) {\n tryCallback(err || null, data);\n });\n }, function (err, data) {\n return callback(err, data);\n });\n}\nvar API_MAP = {\n sliceUploadFile: sliceUploadFile,\n abortUploadTask: abortUploadTask,\n uploadFile: uploadFile,\n uploadFiles: uploadFiles,\n sliceCopyFile: sliceCopyFile\n};\nmodule.exports.init = function (COS, task) {\n task.transferToTaskMethod(API_MAP, 'sliceUploadFile');\n util.each(API_MAP, function (fn, apiName) {\n COS.prototype[apiName] = util.apiWrapper(apiName, fn);\n });\n};\n\n/***/ }),\n\n/***/ \"./src/async.js\":\n/*!**********************!*\\\n !*** ./src/async.js ***!\n \\**********************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nvar eachLimit = function eachLimit(arr, limit, iterator, callback) {\n callback = callback || function () {};\n if (!arr.length || limit <= 0) {\n return callback();\n }\n var completed = 0;\n var started = 0;\n var running = 0;\n (function replenish() {\n if (completed >= arr.length) {\n return callback();\n }\n while (running < limit && started < arr.length) {\n started += 1;\n running += 1;\n iterator(arr[started - 1], function (err) {\n if (err) {\n callback(err);\n callback = function callback() {};\n } else {\n completed += 1;\n running -= 1;\n if (completed >= arr.length) {\n callback();\n } else {\n replenish();\n }\n }\n });\n }\n })();\n};\nvar retry = function retry(times, iterator, callback) {\n var next = function next(index) {\n iterator(function (err, data) {\n if (err && index < times) {\n next(index + 1);\n } else {\n callback(err, data);\n }\n });\n };\n if (times < 1) {\n callback();\n } else {\n next(1);\n }\n};\nvar async = {\n eachLimit: eachLimit,\n retry: retry\n};\nmodule.exports = async;\n\n/***/ }),\n\n/***/ \"./src/base.js\":\n/*!*********************!*\\\n !*** ./src/base.js ***!\n \\*********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\nvar REQUEST = __webpack_require__(/*! ../lib/request */ \"./lib/request.js\");\nvar util = __webpack_require__(/*! ./util */ \"./src/util.js\");\n\n// Bucket \u76F8\u5173\n\n/**\n * \u83B7\u53D6\u7528\u6237\u7684 bucket \u5217\u8868\n * @param {Object} params \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\uFF0C\u4E0B\u9762\u4E3A\u53C2\u6570\u5217\u8868\n * \u65E0\u7279\u6B8A\u53C2\u6570\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n */\nfunction getService(params, callback) {\n var protocol = this.options.Protocol || (util.isBrowser && (typeof location === \"undefined\" ? \"undefined\" : _typeof(location)) === 'object' && location.protocol === 'http:' ? 'http:' : 'https:');\n var domain = this.options.ServiceDomain;\n var appId = params.AppId || this.options.appId;\n var region = params.Region;\n if (domain) {\n domain = domain.replace(/\\{\\{AppId\\}\\}/gi, appId || '').replace(/\\{\\{Region\\}\\}/gi, region || '').replace(/\\{\\{.*?\\}\\}/gi, '');\n if (!/^[a-zA-Z]+:\\/\\//.test(domain)) {\n domain = protocol + '//' + domain;\n }\n if (domain.slice(-1) === '/') {\n domain = domain.slice(0, -1);\n }\n } else if (region) {\n domain = protocol + '//cos.' + region + '.myqcloud.com';\n } else {\n domain = protocol + '//service.cos.myqcloud.com';\n }\n var SignHost = '';\n var standardHost = region ? 'cos.' + region + '.myqcloud.com' : 'service.cos.myqcloud.com';\n var urlHost = domain.replace(/^https?:\\/\\/([^/]+)(\\/.*)?$/, '$1');\n if (standardHost === urlHost) SignHost = standardHost;\n submitRequest.call(this, {\n Action: 'name/cos:GetService',\n url: domain,\n method: 'GET',\n headers: params.Headers,\n SignHost: SignHost,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var buckets = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Buckets && data.ListAllMyBucketsResult.Buckets.Bucket || [];\n buckets = util.isArray(buckets) ? buckets : [buckets];\n var owner = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Owner || {};\n callback(null, {\n Buckets: buckets,\n Owner: owner,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u521B\u5EFA Bucket\uFF0C\u5E76\u521D\u59CB\u5316\u8BBF\u95EE\u6743\u9650\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.ACL \u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\uFF0C\u53EF\u4EE5\u8BBE\u7F6E\uFF1Aprivate\uFF0Cpublic-read\uFF1B\u9ED8\u8BA4\u503C\uFF1Aprivate\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u7684\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-read: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantWrite \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u7684\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-write: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u5199\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-full-control: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {String} data.Location \u64CD\u4F5C\u5730\u5740\n */\nfunction putBucket(params, callback) {\n var self = this;\n var xml = '';\n if (params['BucketAZConfig']) {\n var CreateBucketConfiguration = {\n BucketAZConfig: params.BucketAZConfig\n };\n xml = util.json2xml({\n CreateBucketConfiguration: CreateBucketConfiguration\n });\n }\n submitRequest.call(this, {\n Action: 'name/cos:PutBucket',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n body: xml,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var url = getUrl({\n protocol: self.options.Protocol,\n domain: self.options.Domain,\n bucket: params.Bucket,\n region: params.Region,\n isLocation: true\n });\n callback(null, {\n Location: url,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u67E5\u770B\u662F\u5426\u5B58\u5728\u8BE5Bucket\uFF0C\u662F\u5426\u6709\u6743\u9650\u8BBF\u95EE\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Boolean} data.BucketExist Bucket\u662F\u5426\u5B58\u5728\n * @return {Boolean} data.BucketAuth \u662F\u5426\u6709 Bucket \u7684\u8BBF\u95EE\u6743\u9650\n */\nfunction headBucket(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:HeadBucket',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n method: 'HEAD',\n tracker: params.tracker\n }, callback);\n}\n\n/**\n * \u83B7\u53D6 Bucket \u4E0B\u7684 object \u5217\u8868\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Prefix \u524D\u7F00\u5339\u914D\uFF0C\u7528\u6765\u89C4\u5B9A\u8FD4\u56DE\u7684\u6587\u4EF6\u524D\u7F00\u5730\u5740\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Delimiter \u5B9A\u754C\u7B26\u4E3A\u4E00\u4E2A\u7B26\u53F7\uFF0C\u5982\u679C\u6709Prefix\uFF0C\u5219\u5C06Prefix\u5230delimiter\u4E4B\u95F4\u7684\u76F8\u540C\u8DEF\u5F84\u5F52\u4E3A\u4E00\u7C7B\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Marker \u9ED8\u8BA4\u4EE5UTF-8\u4E8C\u8FDB\u5236\u987A\u5E8F\u5217\u51FA\u6761\u76EE\uFF0C\u6240\u6709\u5217\u51FA\u6761\u76EE\u4ECEmarker\u5F00\u59CB\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.MaxKeys \u5355\u6B21\u8FD4\u56DE\u6700\u5927\u7684\u6761\u76EE\u6570\u91CF\uFF0C\u9ED8\u8BA41000\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.EncodingType \u89C4\u5B9A\u8FD4\u56DE\u503C\u7684\u7F16\u7801\u65B9\u5F0F\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.ListBucketResult \u8FD4\u56DE\u7684 object \u5217\u8868\u4FE1\u606F\n */\nfunction getBucket(params, callback) {\n var reqParams = {};\n reqParams['prefix'] = params['Prefix'] || '';\n reqParams['delimiter'] = params['Delimiter'];\n reqParams['marker'] = params['Marker'];\n reqParams['max-keys'] = params['MaxKeys'];\n reqParams['encoding-type'] = params['EncodingType'];\n submitRequest.call(this, {\n Action: 'name/cos:GetBucket',\n ResourceKey: reqParams['prefix'],\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n qs: reqParams,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var ListBucketResult = data.ListBucketResult || {};\n var Contents = ListBucketResult.Contents || [];\n var CommonPrefixes = ListBucketResult.CommonPrefixes || [];\n Contents = util.isArray(Contents) ? Contents : [Contents];\n CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];\n var result = util.clone(ListBucketResult);\n util.extend(result, {\n Contents: Contents,\n CommonPrefixes: CommonPrefixes,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u5220\u9664 Bucket\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {String} data.Location \u64CD\u4F5C\u5730\u5740\n */\nfunction deleteBucket(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucket',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n method: 'DELETE',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684 \u6743\u9650\u5217\u8868\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.ACL \u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\uFF0C\u53EF\u4EE5\u8BBE\u7F6E\uFF1Aprivate\uFF0Cpublic-read\uFF1B\u9ED8\u8BA4\u503C\uFF1Aprivate\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u7684\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-read: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantWrite \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u7684\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-write: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u5199\u6743\u9650\uFF0C\u683C\u5F0Fx-cos-grant-full-control: uin=\" \",uin=\" \"\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction putBucketAcl(params, callback) {\n var headers = params.Headers;\n var xml = '';\n if (params['AccessControlPolicy']) {\n var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});\n var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;\n Grants = util.isArray(Grants) ? Grants : [Grants];\n delete AccessControlPolicy.Grant;\n delete AccessControlPolicy.Grants;\n AccessControlPolicy.AccessControlList = {\n Grant: Grants\n };\n xml = util.json2xml({\n AccessControlPolicy: AccessControlPolicy\n });\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n }\n\n // Grant Header \u53BB\u91CD\n util.each(headers, function (val, key) {\n if (key.indexOf('x-cos-grant-') === 0) {\n headers[key] = uniqGrant(headers[key]);\n }\n });\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketACL',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: headers,\n action: 'acl',\n body: xml,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684 \u6743\u9650\u5217\u8868\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.AccessControlPolicy \u8BBF\u95EE\u6743\u9650\u4FE1\u606F\n */\nfunction getBucketAcl(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketACL',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'acl',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var AccessControlPolicy = data.AccessControlPolicy || {};\n var Owner = AccessControlPolicy.Owner || {};\n var Grant = AccessControlPolicy.AccessControlList.Grant || [];\n Grant = util.isArray(Grant) ? Grant : [Grant];\n var result = decodeAcl(AccessControlPolicy);\n if (data.headers && data.headers['x-cos-acl']) {\n result.ACL = data.headers['x-cos-acl'];\n }\n result = util.extend(result, {\n Owner: Owner,\n Grants: Grant,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684 \u8DE8\u57DF\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} params.CORSConfiguration \u76F8\u5173\u7684\u8DE8\u57DF\u8BBE\u7F6E\uFF0C\u5FC5\u987B\n * @param {Array} params.CORSConfiguration.CORSRules \u5BF9\u5E94\u7684\u8DE8\u57DF\u89C4\u5219\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction putBucketCors(params, callback) {\n var CORSConfiguration = params['CORSConfiguration'] || {};\n var CORSRules = CORSConfiguration['CORSRules'] || params['CORSRules'] || [];\n CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);\n util.each(CORSRules, function (rule) {\n util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {\n var sKey = key + 's';\n var val = rule[sKey] || rule[key] || [];\n delete rule[sKey];\n rule[key] = util.isArray(val) ? val : [val];\n });\n });\n var Conf = {\n CORSRule: CORSRules\n };\n if (params.ResponseVary) Conf.ResponseVary = params.ResponseVary;\n var xml = util.json2xml({\n CORSConfiguration: Conf\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketCORS',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'cors',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684 \u8DE8\u57DF\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.CORSRules Bucket\u7684\u8DE8\u57DF\u8BBE\u7F6E\n */\nfunction getBucketCors(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketCORS',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'cors',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchCORSConfiguration') {\n var result = {\n CORSRules: [],\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var CORSConfiguration = data.CORSConfiguration || {};\n var CORSRules = CORSConfiguration.CORSRules || CORSConfiguration.CORSRule || [];\n CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);\n var ResponseVary = CORSConfiguration.ResponseVary;\n util.each(CORSRules, function (rule) {\n util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {\n var sKey = key + 's';\n var val = rule[sKey] || rule[key] || [];\n delete rule[key];\n rule[sKey] = util.isArray(val) ? val : [val];\n });\n });\n callback(null, {\n CORSRules: CORSRules,\n ResponseVary: ResponseVary,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684 \u8DE8\u57DF\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction deleteBucketCors(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketCORS',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'cors',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode || err.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684 \u5730\u57DF\u4FE1\u606F\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\uFF0C\u5305\u542B\u5730\u57DF\u4FE1\u606F LocationConstraint\n */\nfunction getBucketLocation(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketLocation',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'location',\n tracker: params.tracker\n }, callback);\n}\nfunction putBucketPolicy(params, callback) {\n var Policy = params['Policy'];\n try {\n if (typeof Policy === 'string') Policy = JSON.parse(Policy);\n } catch (e) {}\n if (!Policy || typeof Policy === 'string') return callback(util.error(new Error('Policy format error')));\n var PolicyStr = JSON.stringify(Policy);\n if (!Policy.version) Policy.version = '2.0';\n var headers = params.Headers;\n headers['Content-Type'] = 'application/json';\n headers['Content-MD5'] = util.b64(util.md5(PolicyStr));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketPolicy',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n action: 'policy',\n body: PolicyStr,\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u8BFB\u53D6\u6743\u9650\u7B56\u7565\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketPolicy(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketPolicy',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'policy',\n rawBody: true,\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode && err.statusCode === 403) {\n return callback(util.error(err, {\n ErrorStatus: 'Access Denied'\n }));\n }\n if (err.statusCode && err.statusCode === 405) {\n return callback(util.error(err, {\n ErrorStatus: 'Method Not Allowed'\n }));\n }\n if (err.statusCode && err.statusCode === 404) {\n return callback(util.error(err, {\n ErrorStatus: 'Policy Not Found'\n }));\n }\n return callback(err);\n }\n var Policy = {};\n try {\n Policy = JSON.parse(data.body);\n } catch (e) {}\n callback(null, {\n Policy: Policy,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684 \u8DE8\u57DF\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction deleteBucketPolicy(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketPolicy',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'policy',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode || err.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684\u6807\u7B7E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Array} params.TagSet \u6807\u7B7E\u8BBE\u7F6E\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketTagging(params, callback) {\n var Tagging = params['Tagging'] || {};\n var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];\n Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);\n var xml = util.json2xml({\n Tagging: {\n TagSet: {\n Tag: Tags\n }\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketTagging',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'tagging',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u6807\u7B7E\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketTagging(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketTagging',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'tagging',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'NoSuchTagSet')) {\n var result = {\n Tags: [],\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var Tags = [];\n try {\n Tags = data.Tagging.TagSet.Tag || [];\n } catch (e) {}\n Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);\n callback(null, {\n Tags: Tags,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684 \u6807\u7B7E\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction deleteBucketTagging(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketTagging',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'tagging',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction putBucketLifecycle(params, callback) {\n var LifecycleConfiguration = params['LifecycleConfiguration'] || {};\n var Rules = LifecycleConfiguration.Rules || params.Rules || [];\n Rules = util.clone(Rules);\n var xml = util.json2xml({\n LifecycleConfiguration: {\n Rule: Rules\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketLifecycle',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'lifecycle',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction getBucketLifecycle(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketLifecycle',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'lifecycle',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchLifecycleConfiguration') {\n var result = {\n Rules: [],\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var Rules = [];\n try {\n Rules = data.LifecycleConfiguration.Rule || [];\n } catch (e) {}\n Rules = util.clone(util.isArray(Rules) ? Rules : [Rules]);\n callback(null, {\n Rules: Rules,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction deleteBucketLifecycle(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketLifecycle',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'lifecycle',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction putBucketVersioning(params, callback) {\n if (!params['VersioningConfiguration']) {\n callback(util.error(new Error('missing param VersioningConfiguration')));\n return;\n }\n var VersioningConfiguration = params['VersioningConfiguration'] || {};\n var xml = util.json2xml({\n VersioningConfiguration: VersioningConfiguration\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketVersioning',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'versioning',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction getBucketVersioning(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketVersioning',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'versioning',\n tracker: params.tracker\n }, function (err, data) {\n if (!err) {\n !data.VersioningConfiguration && (data.VersioningConfiguration = {});\n }\n callback(err, data);\n });\n}\nfunction putBucketReplication(params, callback) {\n var ReplicationConfiguration = util.clone(params.ReplicationConfiguration);\n var xml = util.json2xml({\n ReplicationConfiguration: ReplicationConfiguration\n });\n xml = xml.replace(/<(\\/?)Rules>/gi, '<$1Rule>');\n xml = xml.replace(/<(\\/?)Tags>/gi, '<$1Tag>');\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketReplication',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'replication',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction getBucketReplication(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketReplication',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'replication',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'ReplicationConfigurationnotFoundError')) {\n var result = {\n ReplicationConfiguration: {\n Rules: []\n },\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n !data.ReplicationConfiguration && (data.ReplicationConfiguration = {});\n if (data.ReplicationConfiguration.Rule) {\n data.ReplicationConfiguration.Rules = util.makeArray(data.ReplicationConfiguration.Rule);\n delete data.ReplicationConfiguration.Rule;\n }\n callback(err, data);\n });\n}\nfunction deleteBucketReplication(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketReplication',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'replication',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u9759\u6001\u7F51\u7AD9\u914D\u7F6E\u4FE1\u606F\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} params.WebsiteConfiguration \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} WebsiteConfiguration.IndexDocument \u7D22\u5F15\u6587\u6863\uFF0C\u5FC5\u987B\n * @param {Object} WebsiteConfiguration.ErrorDocument \u9519\u8BEF\u6587\u6863\uFF0C\u975E\u5FC5\u987B\n * @param {Object} WebsiteConfiguration.RedirectAllRequestsTo \u91CD\u5B9A\u5411\u6240\u6709\u8BF7\u6C42\uFF0C\u975E\u5FC5\u987B\n * @param {Array} params.RoutingRules \u91CD\u5B9A\u5411\u89C4\u5219\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketWebsite(params, callback) {\n if (!params['WebsiteConfiguration']) {\n callback(util.error(new Error('missing param WebsiteConfiguration')));\n return;\n }\n var WebsiteConfiguration = util.clone(params['WebsiteConfiguration'] || {});\n var RoutingRules = WebsiteConfiguration['RoutingRules'] || WebsiteConfiguration['RoutingRule'] || [];\n RoutingRules = util.isArray(RoutingRules) ? RoutingRules : [RoutingRules];\n delete WebsiteConfiguration.RoutingRule;\n delete WebsiteConfiguration.RoutingRules;\n if (RoutingRules.length) WebsiteConfiguration.RoutingRules = {\n RoutingRule: RoutingRules\n };\n var xml = util.json2xml({\n WebsiteConfiguration: WebsiteConfiguration\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketWebsite',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'website',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u9759\u6001\u7F51\u7AD9\u914D\u7F6E\u4FE1\u606F\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketWebsite(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketWebsite',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n action: 'website',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error.Code === 'NoSuchWebsiteConfiguration') {\n var result = {\n WebsiteConfiguration: {},\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var WebsiteConfiguration = data.WebsiteConfiguration || {};\n if (WebsiteConfiguration['RoutingRules']) {\n var RoutingRules = util.clone(WebsiteConfiguration['RoutingRules'].RoutingRule || []);\n RoutingRules = util.makeArray(RoutingRules);\n WebsiteConfiguration.RoutingRules = RoutingRules;\n }\n callback(null, {\n WebsiteConfiguration: WebsiteConfiguration,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684\u9759\u6001\u7F51\u7AD9\u914D\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction deleteBucketWebsite(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketWebsite',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'website',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684\u9632\u76D7\u94FE\u767D\u540D\u5355\u6216\u8005\u9ED1\u540D\u5355\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} params.RefererConfiguration \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} RefererConfiguration.Status \u662F\u5426\u5F00\u542F\u9632\u76D7\u94FE\uFF0C\u679A\u4E3E\u503C\uFF1AEnabled\u3001Disabled\n * @param {String} RefererConfiguration.RefererType \u9632\u76D7\u94FE\u7C7B\u578B\uFF0C\u679A\u4E3E\u503C\uFF1ABlack-List\u3001White-List\uFF0C\u5FC5\u987B\n * @param {Array} RefererConfiguration.DomianList.Domain \u751F\u6548\u57DF\u540D\uFF0C\u5FC5\u987B\n * @param {String} RefererConfiguration.EmptyReferConfiguration \uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketReferer(params, callback) {\n if (!params['RefererConfiguration']) {\n callback(util.error(new Error('missing param RefererConfiguration')));\n return;\n }\n var RefererConfiguration = util.clone(params['RefererConfiguration'] || {});\n var DomainList = RefererConfiguration['DomainList'] || {};\n var Domains = DomainList['Domains'] || DomainList['Domain'] || [];\n Domains = util.isArray(Domains) ? Domains : [Domains];\n if (Domains.length) RefererConfiguration.DomainList = {\n Domain: Domains\n };\n var xml = util.json2xml({\n RefererConfiguration: RefererConfiguration\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketReferer',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'referer',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u9632\u76D7\u94FE\u767D\u540D\u5355\u6216\u8005\u9ED1\u540D\u5355\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketReferer(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketReferer',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n action: 'referer',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error.Code === 'NoSuchRefererConfiguration') {\n var result = {\n WebsiteConfiguration: {},\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var RefererConfiguration = data.RefererConfiguration || {};\n if (RefererConfiguration['DomainList']) {\n var Domains = util.makeArray(RefererConfiguration['DomainList'].Domain || []);\n RefererConfiguration.DomainList = {\n Domains: Domains\n };\n }\n callback(null, {\n RefererConfiguration: RefererConfiguration,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u81EA\u5B9A\u4E49\u57DF\u540D\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketDomain(params, callback) {\n var DomainConfiguration = params['DomainConfiguration'] || {};\n var DomainRule = DomainConfiguration.DomainRule || params.DomainRule || [];\n DomainRule = util.clone(DomainRule);\n var xml = util.json2xml({\n DomainConfiguration: {\n DomainRule: DomainRule\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketDomain',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'domain',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u81EA\u5B9A\u4E49\u57DF\u540D\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketDomain(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketDomain',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'domain',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var DomainRule = [];\n try {\n DomainRule = data.DomainConfiguration.DomainRule || [];\n } catch (e) {}\n DomainRule = util.clone(util.isArray(DomainRule) ? DomainRule : [DomainRule]);\n callback(null, {\n DomainRule: DomainRule,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u81EA\u5B9A\u4E49\u57DF\u540D\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction deleteBucketDomain(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketDomain',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'domain',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684\u56DE\u6E90\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketOrigin(params, callback) {\n var OriginConfiguration = params['OriginConfiguration'] || {};\n var OriginRule = OriginConfiguration.OriginRule || params.OriginRule || [];\n OriginRule = util.clone(OriginRule);\n var xml = util.json2xml({\n OriginConfiguration: {\n OriginRule: OriginRule\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketOrigin',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'origin',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u56DE\u6E90\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketOrigin(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketOrigin',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'origin',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var OriginRule = [];\n try {\n OriginRule = data.OriginConfiguration.OriginRule || [];\n } catch (e) {}\n OriginRule = util.clone(util.isArray(OriginRule) ? OriginRule : [OriginRule]);\n callback(null, {\n OriginRule: OriginRule,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684\u56DE\u6E90\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction deleteBucketOrigin(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketOrigin',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'origin',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u8BBE\u7F6E Bucket \u7684\u65E5\u5FD7\u8BB0\u5F55\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {(Object|String)} params.BucketLoggingStatus \u8BF4\u660E\u65E5\u5FD7\u8BB0\u5F55\u914D\u7F6E\u7684\u72B6\u6001\uFF0C\u5982\u679C\u65E0\u5B50\u8282\u70B9\u4FE1\u606F\u5219\u610F\u4E3A\u5173\u95ED\u65E5\u5FD7\u8BB0\u5F55\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putBucketLogging(params, callback) {\n var xml = util.json2xml({\n BucketLoggingStatus: params['BucketLoggingStatus'] || ''\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketLogging',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'logging',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u65E5\u5FD7\u8BB0\u5F55\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketLogging(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketLogging',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'logging',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n BucketLoggingStatus: data.BucketLoggingStatus,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u521B\u5EFA/\u7F16\u8F91 Bucket \u7684\u6E05\u5355\u4EFB\u52A1\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Id \u6E05\u5355\u4EFB\u52A1\u7684\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} params.InventoryConfiguration \u5305\u542B\u6E05\u5355\u7684\u914D\u7F6E\u53C2\u6570\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction submitBucketInventory(method, params, callback) {\n var InventoryConfiguration = util.clone(params['InventoryConfiguration']);\n if (InventoryConfiguration.OptionalFields) {\n var Field = InventoryConfiguration.OptionalFields || [];\n InventoryConfiguration.OptionalFields = {\n Field: Field\n };\n }\n if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {\n var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;\n if (Object.keys(Encryption).indexOf('SSECOS') > -1) {\n Encryption['SSE-COS'] = Encryption['SSECOS'];\n delete Encryption['SSECOS'];\n }\n }\n var xml = util.json2xml({\n InventoryConfiguration: InventoryConfiguration\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n var action = method === 'PUT' ? 'name/cos:PutBucketInventory' : 'name/cos:PostBucketInventory';\n submitRequest.call(this, {\n Action: action,\n method: method,\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'inventory',\n qs: {\n id: params['Id']\n },\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u521B\u5EFA\u4E00\u4E2A\u6E05\u5355\u4EFB\u52A1\n */\nfunction putBucketInventory(params, callback) {\n return submitBucketInventory.call(this, 'PUT', params, callback);\n}\n\n/**\n * \u521B\u5EFA\u4E00\u4E2A\u4E00\u6B21\u6027\u6E05\u5355\u4EFB\u52A1 \u4F1A\u7ACB\u5373\u6267\u884C\n */\nfunction postBucketInventory(params, callback) {\n return submitBucketInventory.call(this, 'POST', params, callback);\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u6E05\u5355\u4EFB\u52A1\u4FE1\u606F\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Id \u6E05\u5355\u4EFB\u52A1\u7684\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getBucketInventory(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketInventory',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'inventory',\n qs: {\n id: params['Id']\n },\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var InventoryConfiguration = data['InventoryConfiguration'];\n if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {\n var Field = InventoryConfiguration.OptionalFields.Field;\n if (!util.isArray(Field)) {\n Field = [Field];\n }\n InventoryConfiguration.OptionalFields = Field;\n }\n if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {\n var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;\n if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {\n Encryption['SSECOS'] = Encryption['SSE-COS'];\n delete Encryption['SSE-COS'];\n }\n }\n callback(null, {\n InventoryConfiguration: InventoryConfiguration,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Bucket \u7684\u6E05\u5355\u4EFB\u52A1\u4FE1\u606F\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.ContinuationToken \u5F53 COS \u54CD\u5E94\u4F53\u4E2D IsTruncated \u4E3A true\uFF0C\u4E14 NextContinuationToken \u8282\u70B9\u4E2D\u5B58\u5728\u53C2\u6570\u503C\u65F6\uFF0C\u60A8\u53EF\u4EE5\u5C06\u8FD9\u4E2A\u53C2\u6570\u4F5C\u4E3A continuation-token \u53C2\u6570\u503C\uFF0C\u4EE5\u83B7\u53D6\u4E0B\u4E00\u9875\u7684\u6E05\u5355\u4EFB\u52A1\u4FE1\u606F\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction listBucketInventory(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:ListBucketInventory',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'inventory',\n qs: {\n 'continuation-token': params['ContinuationToken']\n },\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var ListInventoryConfigurationResult = data['ListInventoryConfigurationResult'];\n var InventoryConfigurations = ListInventoryConfigurationResult.InventoryConfiguration || [];\n InventoryConfigurations = util.isArray(InventoryConfigurations) ? InventoryConfigurations : [InventoryConfigurations];\n delete ListInventoryConfigurationResult['InventoryConfiguration'];\n util.each(InventoryConfigurations, function (InventoryConfiguration) {\n if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {\n var Field = InventoryConfiguration.OptionalFields.Field;\n if (!util.isArray(Field)) {\n Field = [Field];\n }\n InventoryConfiguration.OptionalFields = Field;\n }\n if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {\n var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;\n if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {\n Encryption['SSECOS'] = Encryption['SSE-COS'];\n delete Encryption['SSE-COS'];\n }\n }\n });\n ListInventoryConfigurationResult.InventoryConfigurations = InventoryConfigurations;\n util.extend(ListInventoryConfigurationResult, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, ListInventoryConfigurationResult);\n });\n}\n\n/**\n * \u5220\u9664 Bucket \u7684\u6E05\u5355\u4EFB\u52A1\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Id \u6E05\u5355\u4EFB\u52A1\u7684\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction deleteBucketInventory(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketInventory',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'inventory',\n qs: {\n id: params['Id']\n },\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/* \u5168\u7403\u52A0\u901F */\nfunction putBucketAccelerate(params, callback) {\n if (!params['AccelerateConfiguration']) {\n callback(util.error(new Error('missing param AccelerateConfiguration')));\n return;\n }\n var configuration = {\n AccelerateConfiguration: params.AccelerateConfiguration || {}\n };\n var xml = util.json2xml(configuration);\n var headers = {};\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketAccelerate',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'accelerate',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction getBucketAccelerate(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketAccelerate',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n action: 'accelerate',\n tracker: params.tracker\n }, function (err, data) {\n if (!err) {\n !data.AccelerateConfiguration && (data.AccelerateConfiguration = {});\n }\n callback(err, data);\n });\n}\nfunction putBucketEncryption(params, callback) {\n var conf = params.ServerSideEncryptionConfiguration || {};\n var Rules = conf.Rule || conf.Rules || [];\n var xml = util.json2xml({\n ServerSideEncryptionConfiguration: {\n Rule: Rules\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutBucketEncryption',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'encryption',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\nfunction getBucketEncryption(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketEncryption',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'encryption',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.code === 'NoSuchEncryptionConfiguration') {\n var result = {\n EncryptionConfiguration: {\n Rules: []\n },\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var Rules = util.makeArray(data.EncryptionConfiguration && data.EncryptionConfiguration.Rule || []);\n data.EncryptionConfiguration = {\n Rules: Rules\n };\n callback(err, data);\n });\n}\nfunction deleteBucketEncryption(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteBucketReplication',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'encryption',\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n// Object \u76F8\u5173\n\n/**\n * \u53D6\u56DE\u5BF9\u5E94Object\u7684\u5143\u6570\u636E\uFF0CHead\u7684\u6743\u9650\u4E0EGet\u7684\u6743\u9650\u4E00\u81F4\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key \u6587\u4EF6\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.IfModifiedSince \u5F53Object\u5728\u6307\u5B9A\u65F6\u95F4\u540E\u88AB\u4FEE\u6539\uFF0C\u5219\u8FD4\u56DE\u5BF9\u5E94Object\u5143\u4FE1\u606F\uFF0C\u5426\u5219\u8FD4\u56DE304\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u4E3A\u6307\u5B9A object \u7684\u5143\u6570\u636E\uFF0C\u5982\u679C\u8BBE\u7F6E\u4E86 IfModifiedSince \uFF0C\u4E14\u6587\u4EF6\u672A\u4FEE\u6539\uFF0C\u5219\u8FD4\u56DE\u4E00\u4E2A\u5BF9\u8C61\uFF0CNotModified \u5C5E\u6027\u4E3A true\n * @return {Boolean} data.NotModified \u662F\u5426\u5728 IfModifiedSince \u65F6\u95F4\u70B9\u4E4B\u540E\u672A\u4FEE\u6539\u8BE5 object\uFF0C\u5219\u4E3A true\n */\nfunction headObject(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:HeadObject',\n method: 'HEAD',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n VersionId: params.VersionId,\n headers: params.Headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n var statusCode = err.statusCode;\n if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {\n return callback(null, {\n NotModified: true,\n statusCode: statusCode\n });\n }\n return callback(err);\n }\n data.ETag = util.attr(data.headers, 'etag', '');\n callback(null, data);\n });\n}\nfunction listObjectVersions(params, callback) {\n var reqParams = {};\n reqParams['prefix'] = params['Prefix'] || '';\n reqParams['delimiter'] = params['Delimiter'];\n reqParams['key-marker'] = params['KeyMarker'];\n reqParams['version-id-marker'] = params['VersionIdMarker'];\n reqParams['max-keys'] = params['MaxKeys'];\n reqParams['encoding-type'] = params['EncodingType'];\n submitRequest.call(this, {\n Action: 'name/cos:GetBucketObjectVersions',\n ResourceKey: reqParams['prefix'],\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n qs: reqParams,\n action: 'versions',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var ListVersionsResult = data.ListVersionsResult || {};\n var DeleteMarkers = ListVersionsResult.DeleteMarker || [];\n DeleteMarkers = util.isArray(DeleteMarkers) ? DeleteMarkers : [DeleteMarkers];\n var Versions = ListVersionsResult.Version || [];\n Versions = util.isArray(Versions) ? Versions : [Versions];\n var result = util.clone(ListVersionsResult);\n delete result.DeleteMarker;\n delete result.Version;\n util.extend(result, {\n DeleteMarkers: DeleteMarkers,\n Versions: Versions,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u4E0B\u8F7D object\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key \u6587\u4EF6\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {WriteStream} params.Output \u6587\u4EF6\u5199\u5165\u6D41\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.IfModifiedSince \u5F53Object\u5728\u6307\u5B9A\u65F6\u95F4\u540E\u88AB\u4FEE\u6539\uFF0C\u5219\u8FD4\u56DE\u5BF9\u5E94Object\u5143\u4FE1\u606F\uFF0C\u5426\u5219\u8FD4\u56DE304\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.IfUnmodifiedSince \u5982\u679C\u6587\u4EF6\u4FEE\u6539\u65F6\u95F4\u65E9\u4E8E\u6216\u7B49\u4E8E\u6307\u5B9A\u65F6\u95F4\uFF0C\u624D\u8FD4\u56DE\u6587\u4EF6\u5185\u5BB9\u3002\u5426\u5219\u8FD4\u56DE 412 (precondition failed)\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.IfMatch \u5F53 ETag \u4E0E\u6307\u5B9A\u7684\u5185\u5BB9\u4E00\u81F4\uFF0C\u624D\u8FD4\u56DE\u6587\u4EF6\u3002\u5426\u5219\u8FD4\u56DE 412 (precondition failed)\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.IfNoneMatch \u5F53 ETag \u4E0E\u6307\u5B9A\u7684\u5185\u5BB9\u4E0D\u4E00\u81F4\uFF0C\u624D\u8FD4\u56DE\u6587\u4EF6\u3002\u5426\u5219\u8FD4\u56DE304 (not modified)\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseContentType \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Content-Type \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseContentLanguage \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Content-Language \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseExpires \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Content-Expires \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseCacheControl \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Cache-Control \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseContentDisposition \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Content-Disposition \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ResponseContentEncoding \u8BBE\u7F6E\u8FD4\u56DE\u5934\u90E8\u4E2D\u7684 Content-Encoding \u53C2\u6570\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @param {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @param {Object} data \u4E3A\u5BF9\u5E94\u7684 object \u6570\u636E\uFF0C\u5305\u62EC body \u548C headers\n */\nfunction getObject(params, callback) {\n if (this.options.ObjectKeySimplifyCheck) {\n // getObject \u7684 Key \u9700\u8981\u6821\u9A8C\uFF0C\u907F\u514D\u8C03\u7528\u6210 getBucket\n var formatKey = util.simplifyPath(params.Key);\n if (formatKey === '/') {\n callback(util.error(new Error('The Getobject Key is illegal')));\n return;\n }\n }\n var reqParams = params.Query || {};\n var reqParamsStr = params.QueryString || '';\n var onProgress = util.throttleOnProgress.call(this, 0, params.onProgress);\n var tracker = params.tracker;\n tracker && tracker.setParams({\n signStartTime: new Date().getTime()\n });\n reqParams['response-content-type'] = params['ResponseContentType'];\n reqParams['response-content-language'] = params['ResponseContentLanguage'];\n reqParams['response-expires'] = params['ResponseExpires'];\n reqParams['response-cache-control'] = params['ResponseCacheControl'];\n reqParams['response-content-disposition'] = params['ResponseContentDisposition'];\n reqParams['response-content-encoding'] = params['ResponseContentEncoding'];\n\n // \u5982\u679C\u7528\u6237\u81EA\u5DF1\u4F20\u5165\u4E86 output\n submitRequest.call(this, {\n Action: 'name/cos:GetObject',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n VersionId: params.VersionId,\n DataType: params.DataType,\n headers: params.Headers,\n qs: reqParams,\n qsStr: reqParamsStr,\n rawBody: true,\n onDownloadProgress: onProgress,\n tracker: tracker\n }, function (err, data) {\n onProgress(null, true);\n if (err) {\n var statusCode = err.statusCode;\n if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {\n return callback(null, {\n NotModified: true\n });\n }\n return callback(err);\n }\n callback(null, {\n Body: data.body,\n ETag: util.attr(data.headers, 'etag', ''),\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u4E0A\u4F20 object\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key \u6587\u4EF6\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {File || Blob || String} params.Body \u4E0A\u4F20\u6587\u4EF6\u5BF9\u8C61\u6216\u5B57\u7B26\u4E32\uFF0C\u5FC5\u987B\n * @param {String} params.CacheControl RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F13\u5B58\u7B56\u7565\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentDisposition RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u6587\u4EF6\u540D\u79F0\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentEncoding RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F16\u7801\u683C\u5F0F\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentLength RFC 2616 \u4E2D\u5B9A\u4E49\u7684 HTTP \u8BF7\u6C42\u5185\u5BB9\u957F\u5EA6\uFF08\u5B57\u8282\uFF09\uFF0C\u5FC5\u987B\n * @param {String} params.ContentType RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u5185\u5BB9\u7C7B\u578B\uFF08MIME\uFF09\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expect \u5F53\u4F7F\u7528 Expect: 100-continue \u65F6\uFF0C\u5728\u6536\u5230\u670D\u52A1\u7AEF\u786E\u8BA4\u540E\uFF0C\u624D\u4F1A\u53D1\u9001\u8BF7\u6C42\u5185\u5BB9\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expires RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u8FC7\u671F\u65F6\u95F4\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ACL \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\uFF0C\u6709\u6548\u503C\uFF1Aprivate | public-read\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u53D6\u5BF9\u8C61\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantReadAcp \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u53D6\u5BF9\u8C61\u7684\u8BBF\u95EE\u63A7\u5236\u5217\u8868\uFF08ACL\uFF09\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantWriteAcp \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u5165\u5BF9\u8C61\u7684\u8BBF\u95EE\u63A7\u5236\u5217\u8868\uFF08ACL\uFF09\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u64CD\u4F5C\u5BF9\u8C61\u7684\u6240\u6709\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.StorageClass \u8BBE\u7F6E\u5BF9\u8C61\u7684\u5B58\u50A8\u7EA7\u522B\uFF0C\u679A\u4E3E\u503C\uFF1ASTANDARD\u3001STANDARD_IA\u3001ARCHIVE\uFF0C\u9ED8\u8BA4\u503C\uFF1ASTANDARD\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.x-cos-meta-* \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u7684\u5934\u90E8\u4FE1\u606F\uFF0C\u5C06\u4F5C\u4E3A\u5BF9\u8C61\u7684\u5143\u6570\u636E\u4FDD\u5B58\u3002\u5927\u5C0F\u9650\u52362KB\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentSha1 RFC 3174 \u4E2D\u5B9A\u4E49\u7684 160-bit \u5185\u5BB9 SHA-1 \u7B97\u6CD5\u6821\u9A8C\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ServerSideEncryption \u652F\u6301\u6309\u7167\u6307\u5B9A\u7684\u52A0\u5BC6\u7B97\u6CD5\u8FDB\u884C\u670D\u52A1\u7AEF\u6570\u636E\u52A0\u5BC6\uFF0C\u683C\u5F0F x-cos-server-side-encryption: \"AES256\"\uFF0C\u975E\u5FC5\u987B\n * @param {Function} params.onProgress \u4E0A\u4F20\u8FDB\u5EA6\u56DE\u8C03\u51FD\u6570\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u4E3A\u5BF9\u5E94\u7684 object \u6570\u636E\n * @return {String} data.ETag \u4E3A\u5BF9\u5E94\u4E0A\u4F20\u6587\u4EF6\u7684 ETag \u503C\n */\nfunction putObject(params, callback) {\n var self = this;\n var FileSize = params.ContentLength;\n var onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);\n\n // \u7279\u6B8A\u5904\u7406 Cache-Control\u3001Content-Type\uFF0C\u907F\u514D\u4EE3\u7406\u66F4\u6539\u8FD9\u4E24\u4E2A\u5B57\u6BB5\u5BFC\u81F4\u5199\u5165\u5230 Object \u5C5E\u6027\u91CC\n var headers = params.Headers;\n if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';\n if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = params.Body && params.Body.type || '';\n var needCalcMd5 = params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5 || self.options.UploadCheckContentMd5;\n var tracker = params.tracker;\n needCalcMd5 && tracker && tracker.setParams({\n md5StartTime: new Date().getTime()\n });\n util.getBodyMd5(needCalcMd5, params.Body, function (md5) {\n if (md5) {\n tracker && tracker.setParams({\n md5EndTime: new Date().getTime()\n });\n if (self.options.UploadCheckContentMd5) headers['Content-MD5'] = util.b64(md5);\n if (params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5) headers['x-cos-meta-md5'] = md5;\n }\n if (params.ContentLength !== undefined) headers['Content-Length'] = params.ContentLength;\n onProgress(null, true); // \u4EFB\u52A1\u72B6\u6001\u5F00\u59CB uploading\n submitRequest.call(self, {\n Action: 'name/cos:PutObject',\n TaskId: params.TaskId,\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n qs: params.Query,\n body: params.Body,\n onProgress: onProgress,\n tracker: tracker\n }, function (err, data) {\n if (err) {\n onProgress(null, true);\n return callback(err);\n }\n onProgress({\n loaded: FileSize,\n total: FileSize\n }, true);\n var url = getUrl({\n ForcePathStyle: self.options.ForcePathStyle,\n protocol: self.options.Protocol,\n domain: self.options.Domain,\n bucket: params.Bucket,\n region: !self.options.UseAccelerate ? params.Region : 'accelerate',\n object: params.Key\n });\n url = url.substr(url.indexOf('://') + 3);\n data.Location = url;\n data.ETag = util.attr(data.headers, 'etag', '');\n callback(null, data);\n });\n }, params.onHashProgress);\n}\n\n/**\n * \u5220\u9664 object\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @param {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @param {Object} data \u5220\u9664\u64CD\u4F5C\u6210\u529F\u4E4B\u540E\u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction deleteObject(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteObject',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n VersionId: params.VersionId,\n action: params.Recursive ? 'recursive' : '',\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n var statusCode = err.statusCode;\n if (statusCode && statusCode === 404) {\n return callback(null, {\n BucketNotFound: true,\n statusCode: statusCode\n });\n } else {\n return callback(err);\n }\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 object \u7684 \u6743\u9650\u5217\u8868\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.AccessControlPolicy \u6743\u9650\u5217\u8868\n */\nfunction getObjectAcl(params, callback) {\n var reqParams = {};\n if (params.VersionId) {\n reqParams.versionId = params.VersionId;\n }\n submitRequest.call(this, {\n Action: 'name/cos:GetObjectACL',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n qs: reqParams,\n action: 'acl',\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var AccessControlPolicy = data.AccessControlPolicy || {};\n var Owner = AccessControlPolicy.Owner || {};\n var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || [];\n Grant = util.isArray(Grant) ? Grant : [Grant];\n var result = decodeAcl(AccessControlPolicy);\n delete result.GrantWrite;\n if (data.headers && data.headers['x-cos-acl']) {\n result.ACL = data.headers['x-cos-acl'];\n }\n result = util.extend(result, {\n Owner: Owner,\n Grants: Grant,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u8BBE\u7F6E object \u7684 \u6743\u9650\u5217\u8868\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction putObjectAcl(params, callback) {\n var headers = params.Headers;\n var xml = '';\n if (params['AccessControlPolicy']) {\n var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});\n var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;\n Grants = util.isArray(Grants) ? Grants : [Grants];\n delete AccessControlPolicy.Grant;\n delete AccessControlPolicy.Grants;\n AccessControlPolicy.AccessControlList = {\n Grant: Grants\n };\n xml = util.json2xml({\n AccessControlPolicy: AccessControlPolicy\n });\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n }\n\n // Grant Header \u53BB\u91CD\n util.each(headers, function (val, key) {\n if (key.indexOf('x-cos-grant-') === 0) {\n headers[key] = uniqGrant(headers[key]);\n }\n });\n submitRequest.call(this, {\n Action: 'name/cos:PutObjectACL',\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n action: 'acl',\n headers: headers,\n body: xml,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * Options Object\u8BF7\u6C42\u5B9E\u73B0\u8DE8\u57DF\u8BBF\u95EE\u7684\u9884\u8BF7\u6C42\u3002\u5373\u53D1\u51FA\u4E00\u4E2A OPTIONS \u8BF7\u6C42\u7ED9\u670D\u52A1\u5668\u4EE5\u786E\u8BA4\u662F\u5426\u53EF\u4EE5\u8FDB\u884C\u8DE8\u57DF\u64CD\u4F5C\u3002\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction optionsObject(params, callback) {\n var headers = params.Headers;\n headers['Origin'] = params['Origin'];\n headers['Access-Control-Request-Method'] = params['AccessControlRequestMethod'];\n headers['Access-Control-Request-Headers'] = params['AccessControlRequestHeaders'];\n submitRequest.call(this, {\n Action: 'name/cos:OptionsObject',\n method: 'OPTIONS',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode && err.statusCode === 403) {\n return callback(null, {\n OptionsForbidden: true,\n statusCode: err.statusCode\n });\n }\n return callback(err);\n }\n var headers = data.headers || {};\n callback(null, {\n AccessControlAllowOrigin: headers['access-control-allow-origin'],\n AccessControlAllowMethods: headers['access-control-allow-methods'],\n AccessControlAllowHeaders: headers['access-control-allow-headers'],\n AccessControlExposeHeaders: headers['access-control-expose-headers'],\n AccessControlMaxAge: headers['access-control-max-age'],\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * @param {Object} \u53C2\u6570\u5217\u8868\n * @param {String} Bucket Bucket \u540D\u79F0\n * @param {String} Region \u5730\u57DF\u540D\u79F0\n * @param {String} Key \u6587\u4EF6\u540D\u79F0\n * @param {String} CopySource \u6E90\u6587\u4EF6URL\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u53EF\u4EE5\u901A\u8FC7versionid\u5B50\u8D44\u6E90\u6307\u5B9A\u5386\u53F2\u7248\u672C\n * @param {String} ACL \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\u3002\u6709\u6548\u503C\uFF1Aprivate\uFF0Cpublic-read\u9ED8\u8BA4\u503C\uFF1Aprivate\u3002\n * @param {String} GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u7684\u6743\u9650\uFF0C\u683C\u5F0F x-cos-grant-read: uin=\" \",uin=\" \"\uFF0C\u5F53\u9700\u8981\u7ED9\u5B50\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID/SubAccountID\"\uFF0C\u5F53\u9700\u8981\u7ED9\u6839\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID\"\u3002\n * @param {String} GrantWrite \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u7684\u6743\u9650\uFF0C\u683C\u5F0F x-cos-grant-write: uin=\" \",uin=\" \"\uFF0C\u5F53\u9700\u8981\u7ED9\u5B50\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID/SubAccountID\"\uFF0C\u5F53\u9700\u8981\u7ED9\u6839\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID\"\u3002\n * @param {String} GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u5199\u6743\u9650\uFF0C\u683C\u5F0F x-cos-grant-full-control: uin=\" \",uin=\" \"\uFF0C\u5F53\u9700\u8981\u7ED9\u5B50\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID/SubAccountID\"\uFF0C\u5F53\u9700\u8981\u7ED9\u6839\u8D26\u6237\u6388\u6743\u65F6\uFF0Cuin=\"RootAcountID\"\u3002\n * @param {String} MetadataDirective \u662F\u5426\u62F7\u8D1D\u5143\u6570\u636E\uFF0C\u679A\u4E3E\u503C\uFF1ACopy, Replaced\uFF0C\u9ED8\u8BA4\u503CCopy\u3002\u5047\u5982\u6807\u8BB0\u4E3ACopy\uFF0C\u5FFD\u7565Header\u4E2D\u7684\u7528\u6237\u5143\u6570\u636E\u4FE1\u606F\u76F4\u63A5\u590D\u5236\uFF1B\u5047\u5982\u6807\u8BB0\u4E3AReplaced\uFF0C\u6309Header\u4FE1\u606F\u4FEE\u6539\u5143\u6570\u636E\u3002\u5F53\u76EE\u6807\u8DEF\u5F84\u548C\u539F\u8DEF\u5F84\u4E00\u81F4\uFF0C\u5373\u7528\u6237\u8BD5\u56FE\u4FEE\u6539\u5143\u6570\u636E\u65F6\uFF0C\u5FC5\u987B\u4E3AReplaced\n * @param {String} CopySourceIfModifiedSince \u5F53Object\u5728\u6307\u5B9A\u65F6\u95F4\u540E\u88AB\u4FEE\u6539\uFF0C\u5219\u6267\u884C\u64CD\u4F5C\uFF0C\u5426\u5219\u8FD4\u56DE412\u3002\u53EF\u4E0Ex-cos-copy-source-If-None-Match\u4E00\u8D77\u4F7F\u7528\uFF0C\u4E0E\u5176\u4ED6\u6761\u4EF6\u8054\u5408\u4F7F\u7528\u8FD4\u56DE\u51B2\u7A81\u3002\n * @param {String} CopySourceIfUnmodifiedSince \u5F53Object\u5728\u6307\u5B9A\u65F6\u95F4\u540E\u672A\u88AB\u4FEE\u6539\uFF0C\u5219\u6267\u884C\u64CD\u4F5C\uFF0C\u5426\u5219\u8FD4\u56DE412\u3002\u53EF\u4E0Ex-cos-copy-source-If-Match\u4E00\u8D77\u4F7F\u7528\uFF0C\u4E0E\u5176\u4ED6\u6761\u4EF6\u8054\u5408\u4F7F\u7528\u8FD4\u56DE\u51B2\u7A81\u3002\n * @param {String} CopySourceIfMatch \u5F53Object\u7684ETag\u548C\u7ED9\u5B9A\u4E00\u81F4\u65F6\uFF0C\u5219\u6267\u884C\u64CD\u4F5C\uFF0C\u5426\u5219\u8FD4\u56DE412\u3002\u53EF\u4E0Ex-cos-copy-source-If-Unmodified-Since\u4E00\u8D77\u4F7F\u7528\uFF0C\u4E0E\u5176\u4ED6\u6761\u4EF6\u8054\u5408\u4F7F\u7528\u8FD4\u56DE\u51B2\u7A81\u3002\n * @param {String} CopySourceIfNoneMatch \u5F53Object\u7684ETag\u548C\u7ED9\u5B9A\u4E0D\u4E00\u81F4\u65F6\uFF0C\u5219\u6267\u884C\u64CD\u4F5C\uFF0C\u5426\u5219\u8FD4\u56DE412\u3002\u53EF\u4E0Ex-cos-copy-source-If-Modified-Since\u4E00\u8D77\u4F7F\u7528\uFF0C\u4E0E\u5176\u4ED6\u6761\u4EF6\u8054\u5408\u4F7F\u7528\u8FD4\u56DE\u51B2\u7A81\u3002\n * @param {String} StorageClass \u5B58\u50A8\u7EA7\u522B\uFF0C\u679A\u4E3E\u503C\uFF1A\u5B58\u50A8\u7EA7\u522B\uFF0C\u679A\u4E3E\u503C\uFF1AStandard, Standard_IA\uFF0CArchive\uFF1B\u9ED8\u8BA4\u503C\uFF1AStandard\n * @param {String} CacheControl \u6307\u5B9A\u6240\u6709\u7F13\u5B58\u673A\u5236\u5728\u6574\u4E2A\u8BF7\u6C42/\u54CD\u5E94\u94FE\u4E2D\u5FC5\u987B\u670D\u4ECE\u7684\u6307\u4EE4\u3002\n * @param {String} ContentDisposition MIME \u534F\u8BAE\u7684\u6269\u5C55\uFF0CMIME \u534F\u8BAE\u6307\u793A MIME \u7528\u6237\u4EE3\u7406\u5982\u4F55\u663E\u793A\u9644\u52A0\u7684\u6587\u4EF6\n * @param {String} ContentEncoding HTTP \u4E2D\u7528\u6765\u5BF9\u300C\u91C7\u7528\u4F55\u79CD\u7F16\u7801\u683C\u5F0F\u4F20\u8F93\u6B63\u6587\u300D\u8FDB\u884C\u534F\u5B9A\u7684\u4E00\u5BF9\u5934\u90E8\u5B57\u6BB5\n * @param {String} ContentLength \u8BBE\u7F6E\u54CD\u5E94\u6D88\u606F\u7684\u5B9E\u4F53\u5185\u5BB9\u7684\u5927\u5C0F\uFF0C\u5355\u4F4D\u4E3A\u5B57\u8282\n * @param {String} ContentType RFC 2616 \u4E2D\u5B9A\u4E49\u7684 HTTP \u8BF7\u6C42\u5185\u5BB9\u7C7B\u578B\uFF08MIME\uFF09\uFF0C\u4F8B\u5982text/plain\n * @param {String} Expect \u8BF7\u6C42\u7684\u7279\u5B9A\u7684\u670D\u52A1\u5668\u884C\u4E3A\n * @param {String} Expires \u54CD\u5E94\u8FC7\u671F\u7684\u65E5\u671F\u548C\u65F6\u95F4\n * @param {String} params.ServerSideEncryption \u652F\u6301\u6309\u7167\u6307\u5B9A\u7684\u52A0\u5BC6\u7B97\u6CD5\u8FDB\u884C\u670D\u52A1\u7AEF\u6570\u636E\u52A0\u5BC6\uFF0C\u683C\u5F0F x-cos-server-side-encryption: \"AES256\"\uFF0C\u975E\u5FC5\u987B\n * @param {String} ContentLanguage \u6307\u5B9A\u5185\u5BB9\u8BED\u8A00\n * @param {String} x-cos-meta-* \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u7684\u5934\u90E8\u4FE1\u606F\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u8FD4\u56DE\u3002\u5927\u5C0F\u9650\u52362K\u3002\n */\nfunction putObjectCopy(params, callback) {\n // \u7279\u6B8A\u5904\u7406 Cache-Control\n var self = this;\n var headers = params.Headers;\n if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';\n var CopySource = params.CopySource || '';\n var m = util.getSourceParams.call(this, CopySource);\n if (!m) {\n callback(util.error(new Error('CopySource format error')));\n return;\n }\n var SourceBucket = m.Bucket;\n var SourceRegion = m.Region;\n var SourceKey = decodeURIComponent(m.Key);\n submitRequest.call(this, {\n Scope: [{\n action: 'name/cos:GetObject',\n bucket: SourceBucket,\n region: SourceRegion,\n prefix: SourceKey\n }, {\n action: 'name/cos:PutObject',\n bucket: params.Bucket,\n region: params.Region,\n prefix: params.Key\n }],\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n VersionId: params.VersionId,\n headers: params.Headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var result = util.clone(data.CopyObjectResult || {});\n var url = getUrl({\n ForcePathStyle: self.options.ForcePathStyle,\n protocol: self.options.Protocol,\n domain: self.options.Domain,\n bucket: params.Bucket,\n region: params.Region,\n object: params.Key,\n isLocation: true\n });\n util.extend(result, {\n Location: url,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\nfunction uploadPartCopy(params, callback) {\n var CopySource = params.CopySource || '';\n var m = util.getSourceParams.call(this, CopySource);\n if (!m) {\n callback(util.error(new Error('CopySource format error')));\n return;\n }\n var SourceBucket = m.Bucket;\n var SourceRegion = m.Region;\n var SourceKey = decodeURIComponent(m.Key);\n submitRequest.call(this, {\n Scope: [{\n action: 'name/cos:GetObject',\n bucket: SourceBucket,\n region: SourceRegion,\n prefix: SourceKey\n }, {\n action: 'name/cos:PutObject',\n bucket: params.Bucket,\n region: params.Region,\n prefix: params.Key\n }],\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n VersionId: params.VersionId,\n qs: {\n partNumber: params['PartNumber'],\n uploadId: params['UploadId']\n },\n headers: params.Headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var result = util.clone(data.CopyPartResult || {});\n util.extend(result, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\nfunction deleteMultipleObject(params, callback) {\n var Objects = params.Objects || [];\n var Quiet = params.Quiet;\n Objects = util.isArray(Objects) ? Objects : [Objects];\n var xml = util.json2xml({\n Delete: {\n Object: Objects,\n Quiet: Quiet || false\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n var Scope = util.map(Objects, function (v) {\n return {\n action: 'name/cos:DeleteObject',\n bucket: params.Bucket,\n region: params.Region,\n prefix: v.Key\n };\n });\n submitRequest.call(this, {\n Scope: Scope,\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n body: xml,\n action: 'delete',\n headers: headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n var DeleteResult = data.DeleteResult || {};\n var Deleted = DeleteResult.Deleted || [];\n var Errors = DeleteResult.Error || [];\n Deleted = util.isArray(Deleted) ? Deleted : [Deleted];\n Errors = util.isArray(Errors) ? Errors : [Errors];\n var result = util.clone(DeleteResult);\n util.extend(result, {\n Error: Errors,\n Deleted: Deleted,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\nfunction restoreObject(params, callback) {\n var headers = params.Headers;\n if (!params['RestoreRequest']) {\n callback(util.error(new Error('missing param RestoreRequest')));\n return;\n }\n var RestoreRequest = params.RestoreRequest || {};\n var xml = util.json2xml({\n RestoreRequest: RestoreRequest\n });\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:RestoreObject',\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n VersionId: params.VersionId,\n body: xml,\n action: 'restore',\n headers: headers,\n tracker: params.tracker\n }, callback);\n}\n\n/**\n * \u8BBE\u7F6E Object \u7684\u6807\u7B7E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Array} params.TagSet \u6807\u7B7E\u8BBE\u7F6E\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/42998\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction putObjectTagging(params, callback) {\n var Tagging = params['Tagging'] || {};\n var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];\n Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);\n var xml = util.json2xml({\n Tagging: {\n TagSet: {\n Tag: Tags\n }\n }\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:PutObjectTagging',\n method: 'PUT',\n Bucket: params.Bucket,\n Key: params.Key,\n Region: params.Region,\n body: xml,\n action: 'tagging',\n headers: headers,\n VersionId: params.VersionId,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u83B7\u53D6 Object \u7684\u6807\u7B7E\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/42998\n * @return {Object} data \u8FD4\u56DE\u6570\u636E\n */\nfunction getObjectTagging(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:GetObjectTagging',\n method: 'GET',\n Key: params.Key,\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n action: 'tagging',\n VersionId: params.VersionId,\n tracker: params.tracker\n }, function (err, data) {\n if (err) {\n if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'NoSuchTagSet')) {\n var result = {\n Tags: [],\n statusCode: err.statusCode\n };\n err.headers && (result.headers = err.headers);\n callback(null, result);\n } else {\n callback(err);\n }\n return;\n }\n var Tags = [];\n try {\n Tags = data.Tagging.TagSet.Tag || [];\n } catch (e) {}\n Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);\n callback(null, {\n Tags: Tags,\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u5220\u9664 Object \u7684 \u6807\u7B7E\u8BBE\u7F6E\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/42998\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction deleteObjectTagging(params, callback) {\n submitRequest.call(this, {\n Action: 'name/cos:DeleteObjectTagging',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n action: 'tagging',\n VersionId: params.VersionId,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u4F7F\u7528 SQL \u8BED\u53E5\u4ECE\u6307\u5B9A\u5BF9\u8C61\uFF08CSV \u683C\u5F0F\u6216\u8005 JSON \u683C\u5F0F\uFF09\u4E2D\u68C0\u7D22\u5185\u5BB9\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Object} params.SelectRequest \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/42998\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction selectObjectContent(params, callback) {\n var SelectType = params['SelectType'];\n if (!SelectType) return callback(util.error(new Error('missing param SelectType')));\n var SelectRequest = params['SelectRequest'] || {};\n var xml = util.json2xml({\n SelectRequest: SelectRequest\n });\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:GetObject',\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n action: 'select',\n qs: {\n 'select-type': params['SelectType']\n },\n VersionId: params.VersionId,\n body: xml,\n DataType: 'arraybuffer',\n rawBody: true,\n tracker: params.tracker\n }, function (err, data) {\n if (err && err.statusCode === 204) {\n return callback(null, {\n statusCode: err.statusCode\n });\n } else if (err) {\n return callback(err);\n }\n var result = util.parseSelectPayload(data.body);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers,\n Body: result.body,\n Payload: result.payload\n });\n });\n}\n\n// \u5206\u5757\u4E0A\u4F20\n\n/**\n * \u521D\u59CB\u5316\u5206\u5757\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.UploadId object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.CacheControl RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F13\u5B58\u7B56\u7565\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentDisposition RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u6587\u4EF6\u540D\u79F0\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58 \uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentEncoding RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F16\u7801\u683C\u5F0F\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentType RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u5185\u5BB9\u7C7B\u578B\uFF08MIME\uFF09\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expires RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u8FC7\u671F\u65F6\u95F4\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ACL \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u7684\u6743\u9650 \uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantWrite \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u7684\u6743\u9650 \uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u5199\u6743\u9650 \uFF0C\u975E\u5FC5\u987B\n * @param {String} params.StorageClass \u8BBE\u7F6EObject\u7684\u5B58\u50A8\u7EA7\u522B\uFF0C\u679A\u4E3E\u503C\uFF1AStandard\uFF0CStandard_IA\uFF0CArchive\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ServerSideEncryption \u652F\u6301\u6309\u7167\u6307\u5B9A\u7684\u52A0\u5BC6\u7B97\u6CD5\u8FDB\u884C\u670D\u52A1\u7AEF\u6570\u636E\u52A0\u5BC6\uFF0C\u683C\u5F0F x-cos-server-side-encryption: \"AES256\"\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction multipartInit(params, callback) {\n var self = this;\n // \u7279\u6B8A\u5904\u7406 Cache-Control\n var headers = params.Headers;\n var tracker = params.tracker;\n\n // \u7279\u6B8A\u5904\u7406 Cache-Control\u3001Content-Type\n if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';\n if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = params.Body && params.Body.type || '';\n var needCalcMd5 = params.Body && (params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5);\n needCalcMd5 && tracker && tracker.setParams({\n md5StartTime: new Date().getTime()\n });\n util.getBodyMd5(needCalcMd5, params.Body, function (md5) {\n if (md5) params.Headers['x-cos-meta-md5'] = md5;\n needCalcMd5 && tracker && tracker.setParams({\n md5EndTime: new Date().getTime()\n });\n submitRequest.call(self, {\n Action: 'name/cos:InitiateMultipartUpload',\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n action: 'uploads',\n headers: params.Headers,\n qs: params.Query,\n tracker: tracker\n }, function (err, data) {\n if (err) {\n tracker && tracker.parent && tracker.parent.setParams({\n errorNode: 'multipartInit'\n });\n return callback(err);\n }\n data = util.clone(data || {});\n if (data && data.InitiateMultipartUploadResult) {\n return callback(null, util.extend(data.InitiateMultipartUploadResult, {\n statusCode: data.statusCode,\n headers: data.headers\n }));\n }\n callback(null, data);\n });\n }, params.onHashProgress);\n}\n\n/**\n * \u5206\u5757\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {File || Blob || String} params.Body \u4E0A\u4F20\u6587\u4EF6\u5BF9\u8C61\u6216\u5B57\u7B26\u4E32\n * @param {String} params.ContentLength RFC 2616 \u4E2D\u5B9A\u4E49\u7684 HTTP \u8BF7\u6C42\u5185\u5BB9\u957F\u5EA6\uFF08\u5B57\u8282\uFF09\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expect \u5F53\u4F7F\u7528 Expect: 100-continue \u65F6\uFF0C\u5728\u6536\u5230\u670D\u52A1\u7AEF\u786E\u8BA4\u540E\uFF0C\u624D\u4F1A\u53D1\u9001\u8BF7\u6C42\u5185\u5BB9\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ServerSideEncryption \u652F\u6301\u6309\u7167\u6307\u5B9A\u7684\u52A0\u5BC6\u7B97\u6CD5\u8FDB\u884C\u670D\u52A1\u7AEF\u6570\u636E\u52A0\u5BC6\uFF0C\u683C\u5F0F x-cos-server-side-encryption: \"AES256\"\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentSha1 RFC 3174 \u4E2D\u5B9A\u4E49\u7684 160-bit \u5185\u5BB9 SHA-1 \u7B97\u6CD5\u6821\u9A8C\u503C\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.ETag \u8FD4\u56DE\u7684\u6587\u4EF6\u5206\u5757 sha1 \u503C\n */\nfunction multipartUpload(params, callback) {\n var self = this;\n util.getFileSize('multipartUpload', params, function () {\n var tracker = params.tracker;\n var needCalcMd5 = self.options.UploadCheckContentMd5;\n needCalcMd5 && tracker && tracker.setParams({\n md5StartTime: new Date().getTime()\n });\n util.getBodyMd5(needCalcMd5, params.Body, function (md5) {\n if (md5) params.Headers['Content-MD5'] = util.b64(md5);\n needCalcMd5 && tracker && tracker.setParams({\n md5EndTime: new Date().getTime()\n });\n tracker && tracker.setParams({\n partNumber: params.PartNumber\n });\n submitRequest.call(self, {\n Action: 'name/cos:UploadPart',\n TaskId: params.TaskId,\n method: 'PUT',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n qs: {\n partNumber: params['PartNumber'],\n uploadId: params['UploadId']\n },\n headers: params.Headers,\n onProgress: params.onProgress,\n body: params.Body || null,\n tracker: tracker\n }, function (err, data) {\n if (err) {\n tracker && tracker.parent && tracker.parent.setParams({\n errorNode: 'multipartUpload'\n });\n return callback(err);\n }\n callback(null, {\n ETag: util.attr(data.headers, 'etag', ''),\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n });\n });\n}\n\n/**\n * \u5B8C\u6210\u5206\u5757\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {Array} params.Parts \u5206\u5757\u4FE1\u606F\u5217\u8868\uFF0C\u5FC5\u987B\n * @param {String} params.Parts[i].PartNumber \u5757\u7F16\u53F7\uFF0C\u5FC5\u987B\n * @param {String} params.Parts[i].ETag \u5206\u5757\u7684 sha1 \u6821\u9A8C\u503C\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.CompleteMultipartUpload \u5B8C\u6210\u5206\u5757\u4E0A\u4F20\u540E\u7684\u6587\u4EF6\u4FE1\u606F\uFF0C\u5305\u62ECLocation, Bucket, Key \u548C ETag\n */\nfunction multipartComplete(params, callback) {\n var self = this;\n var UploadId = params.UploadId;\n var Parts = params['Parts'];\n var tracker = params.tracker;\n for (var i = 0, len = Parts.length; i < len; i++) {\n if (Parts[i]['ETag'] && Parts[i]['ETag'].indexOf('\"') === 0) {\n continue;\n }\n Parts[i]['ETag'] = '\"' + Parts[i]['ETag'] + '\"';\n }\n var xml = util.json2xml({\n CompleteMultipartUpload: {\n Part: Parts\n }\n });\n // CSP/ceph CompleteMultipartUpload \u63A5\u53E3 body \u5199\u6B7B\u4E86\u9650\u5236 1MB\uFF0C\u8FD9\u91CC\u6700\u591A 10000 \u7247\u65F6\uFF0Cxml \u5B57\u7B26\u4E32\u53BB\u6389\u7A7A\u683C853KB\n xml = xml.replace(/\\n\\s*/g, '');\n var headers = params.Headers;\n headers['Content-Type'] = 'application/xml';\n headers['Content-MD5'] = util.b64(util.md5(xml));\n submitRequest.call(this, {\n Action: 'name/cos:CompleteMultipartUpload',\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n qs: {\n uploadId: UploadId\n },\n body: xml,\n headers: headers,\n tracker: tracker\n }, function (err, data) {\n if (err) {\n tracker && tracker.parent && tracker.parent.setParams({\n errorNode: 'multipartComplete'\n });\n return callback(err);\n }\n var url = getUrl({\n ForcePathStyle: self.options.ForcePathStyle,\n protocol: self.options.Protocol,\n domain: self.options.Domain,\n bucket: params.Bucket,\n region: params.Region,\n object: params.Key,\n isLocation: true\n });\n var res = data.CompleteMultipartUploadResult || {};\n // pic-operations \u5904\u7406\n if (res.ProcessResults) {\n res.UploadResult = {\n OriginalInfo: {\n Key: res.Key,\n Location: url,\n ETag: res.ETag,\n ImageInfo: res.ImageInfo\n },\n ProcessResults: res.ProcessResults\n };\n delete res.ImageInfo;\n delete res.ProcessResults;\n }\n // callback \u5904\u7406\n if (res.CallbackResult) {\n var callbackResult = res.CallbackResult;\n if (callbackResult.Status === '200' && callbackResult.CallbackBody) {\n try {\n res.CallbackBody = JSON.parse(util.decodeBase64(callbackResult.CallbackBody));\n } catch (e) {\n res.CallbackBody = {};\n }\n } else {\n res.CallbackError = callbackResult.Error || {};\n }\n delete res.CallbackResult;\n }\n // returnBody \u5904\u7406\n if (res.ReturnBodyResult) {\n var returnBodyResult = res.ReturnBodyResult;\n if (returnBodyResult.Status === '200' && returnBodyResult.ReturnBody) {\n try {\n res.ReturnBody = JSON.parse(util.decodeBase64(returnBodyResult.ReturnBody));\n } catch (e) {\n res.ReturnBody = {};\n }\n } else {\n res.ReturnError = {\n Code: returnBodyResult.Code,\n Message: returnBodyResult.Message,\n Status: returnBodyResult.Status\n };\n }\n delete res.ReturnBodyResult;\n }\n var result = util.extend(res, {\n Location: url,\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u5206\u5757\u4E0A\u4F20\u4EFB\u52A1\u5217\u8868\u67E5\u8BE2\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Delimiter \u5B9A\u754C\u7B26\u4E3A\u4E00\u4E2A\u7B26\u53F7\uFF0C\u5982\u679C\u6709Prefix\uFF0C\u5219\u5C06Prefix\u5230delimiter\u4E4B\u95F4\u7684\u76F8\u540C\u8DEF\u5F84\u5F52\u4E3A\u4E00\u7C7B\uFF0C\u5B9A\u4E49\u4E3ACommon Prefix\uFF0C\u7136\u540E\u5217\u51FA\u6240\u6709Common Prefix\u3002\u5982\u679C\u6CA1\u6709Prefix\uFF0C\u5219\u4ECE\u8DEF\u5F84\u8D77\u70B9\u5F00\u59CB\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.EncodingType \u89C4\u5B9A\u8FD4\u56DE\u503C\u7684\u7F16\u7801\u65B9\u5F0F\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Prefix \u524D\u7F00\u5339\u914D\uFF0C\u7528\u6765\u89C4\u5B9A\u8FD4\u56DE\u7684\u6587\u4EF6\u524D\u7F00\u5730\u5740\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.MaxUploads \u5355\u6B21\u8FD4\u56DE\u6700\u5927\u7684\u6761\u76EE\u6570\u91CF\uFF0C\u9ED8\u8BA41000\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.KeyMarker \u4E0Eupload-id-marker\u4E00\u8D77\u4F7F\u7528
\u5F53upload-id-marker\u672A\u88AB\u6307\u5B9A\u65F6\uFF0CObjectName\u5B57\u6BCD\u987A\u5E8F\u5927\u4E8Ekey-marker\u7684\u6761\u76EE\u5C06\u88AB\u5217\u51FA
\u5F53upload-id-marker\u88AB\u6307\u5B9A\u65F6\uFF0CObjectName\u5B57\u6BCD\u987A\u5E8F\u5927\u4E8Ekey-marker\u7684\u6761\u76EE\u88AB\u5217\u51FA\uFF0CObjectName\u5B57\u6BCD\u987A\u5E8F\u7B49\u4E8Ekey-marker\u540C\u65F6UploadId\u5927\u4E8Eupload-id-marker\u7684\u6761\u76EE\u5C06\u88AB\u5217\u51FA\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.UploadIdMarker \u4E0Ekey-marker\u4E00\u8D77\u4F7F\u7528
\u5F53key-marker\u672A\u88AB\u6307\u5B9A\u65F6\uFF0Cupload-id-marker\u5C06\u88AB\u5FFD\u7565
\u5F53key-marker\u88AB\u6307\u5B9A\u65F6\uFF0CObjectName\u5B57\u6BCD\u987A\u5E8F\u5927\u4E8Ekey-marker\u7684\u6761\u76EE\u88AB\u5217\u51FA\uFF0CObjectName\u5B57\u6BCD\u987A\u5E8F\u7B49\u4E8Ekey-marker\u540C\u65F6UploadId\u5927\u4E8Eupload-id-marker\u7684\u6761\u76EE\u5C06\u88AB\u5217\u51FA\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.ListMultipartUploadsResult \u5206\u5757\u4E0A\u4F20\u4EFB\u52A1\u4FE1\u606F\n */\nfunction multipartList(params, callback) {\n var reqParams = {};\n reqParams['delimiter'] = params['Delimiter'];\n reqParams['encoding-type'] = params['EncodingType'];\n reqParams['prefix'] = params['Prefix'] || '';\n reqParams['max-uploads'] = params['MaxUploads'];\n reqParams['key-marker'] = params['KeyMarker'];\n reqParams['upload-id-marker'] = params['UploadIdMarker'];\n reqParams = util.clearKey(reqParams);\n var tracker = params.tracker;\n tracker && tracker.setParams({\n signStartTime: new Date().getTime()\n });\n submitRequest.call(this, {\n Action: 'name/cos:ListMultipartUploads',\n ResourceKey: reqParams['prefix'],\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n headers: params.Headers,\n qs: reqParams,\n action: 'uploads',\n tracker: tracker\n }, function (err, data) {\n if (err) {\n tracker && tracker.parent && tracker.parent.setParams({\n errorNode: 'multipartList'\n });\n return callback(err);\n }\n if (data && data.ListMultipartUploadsResult) {\n var Upload = data.ListMultipartUploadsResult.Upload || [];\n Upload = util.isArray(Upload) ? Upload : [Upload];\n data.ListMultipartUploadsResult.Upload = Upload;\n }\n var result = util.clone(data.ListMultipartUploadsResult || {});\n util.extend(result, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u4E0A\u4F20\u7684\u5206\u5757\u5217\u8868\u67E5\u8BE2\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.UploadId \u6807\u793A\u672C\u6B21\u5206\u5757\u4E0A\u4F20\u7684ID\uFF0C\u5FC5\u987B\n * @param {String} params.EncodingType \u89C4\u5B9A\u8FD4\u56DE\u503C\u7684\u7F16\u7801\u65B9\u5F0F\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.MaxParts \u5355\u6B21\u8FD4\u56DE\u6700\u5927\u7684\u6761\u76EE\u6570\u91CF\uFF0C\u9ED8\u8BA41000\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.PartNumberMarker \u9ED8\u8BA4\u4EE5UTF-8\u4E8C\u8FDB\u5236\u987A\u5E8F\u5217\u51FA\u6761\u76EE\uFF0C\u6240\u6709\u5217\u51FA\u6761\u76EE\u4ECEmarker\u5F00\u59CB\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n * @return {Object} data.ListMultipartUploadsResult \u5206\u5757\u4FE1\u606F\n */\nfunction multipartListPart(params, callback) {\n var reqParams = {};\n var tracker = params.tracker;\n reqParams['uploadId'] = params['UploadId'];\n reqParams['encoding-type'] = params['EncodingType'];\n reqParams['max-parts'] = params['MaxParts'];\n reqParams['part-number-marker'] = params['PartNumberMarker'];\n submitRequest.call(this, {\n Action: 'name/cos:ListParts',\n method: 'GET',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n qs: reqParams,\n tracker: tracker\n }, function (err, data) {\n if (err) {\n tracker && tracker.parent && tracker.parent.setParams({\n errorNode: 'multipartListPart'\n });\n return callback(err);\n }\n var ListPartsResult = data.ListPartsResult || {};\n var Part = ListPartsResult.Part || [];\n Part = util.isArray(Part) ? Part : [Part];\n ListPartsResult.Part = Part;\n var result = util.clone(ListPartsResult);\n util.extend(result, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n callback(null, result);\n });\n}\n\n/**\n * \u629B\u5F03\u5206\u5757\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.UploadId \u6807\u793A\u672C\u6B21\u5206\u5757\u4E0A\u4F20\u7684ID\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction multipartAbort(params, callback) {\n var reqParams = {};\n reqParams['uploadId'] = params['UploadId'];\n submitRequest.call(this, {\n Action: 'name/cos:AbortMultipartUpload',\n method: 'DELETE',\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n headers: params.Headers,\n qs: reqParams,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, {\n statusCode: data.statusCode,\n headers: data.headers\n });\n });\n}\n\n/**\n * \u629B\u5F03\u5206\u5757\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.UploadId \u6807\u793A\u672C\u6B21\u5206\u5757\u4E0A\u4F20\u7684ID\uFF0C\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction request(params, callback) {\n submitRequest.call(this, {\n method: params.Method,\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n action: params.Action,\n headers: params.Headers,\n qs: params.Query,\n body: params.Body,\n Url: params.Url,\n rawBody: params.RawBody,\n DataType: params.DataType,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n if (data && data.body) {\n data.Body = data.body;\n delete data.body;\n }\n callback(err, data);\n });\n}\n\n/**\n * \u8FFD\u52A0\u4E0A\u4F20\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {File || Blob || String} params.Body \u4E0A\u4F20\u6587\u4EF6\u5BF9\u8C61\u6216\u5B57\u7B26\u4E32\n * @param {Number} params.Position \u8FFD\u52A0\u64CD\u4F5C\u7684\u8D77\u59CB\u70B9\uFF0C\u5355\u4F4D\u4E3A\u5B57\u8282\uFF0C\u5FC5\u987B\n * @param {String} params.CacheControl RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F13\u5B58\u7B56\u7565\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentDisposition RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u6587\u4EF6\u540D\u79F0\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentEncoding RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u7F16\u7801\u683C\u5F0F\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentLength RFC 2616 \u4E2D\u5B9A\u4E49\u7684 HTTP \u8BF7\u6C42\u5185\u5BB9\u957F\u5EA6\uFF08\u5B57\u8282\uFF09\uFF0C\u5FC5\u987B\n * @param {String} params.ContentType RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u5185\u5BB9\u7C7B\u578B\uFF08MIME\uFF09\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expect \u5F53\u4F7F\u7528 Expect: 100-continue \u65F6\uFF0C\u5728\u6536\u5230\u670D\u52A1\u7AEF\u786E\u8BA4\u540E\uFF0C\u624D\u4F1A\u53D1\u9001\u8BF7\u6C42\u5185\u5BB9\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.Expires RFC 2616 \u4E2D\u5B9A\u4E49\u7684\u8FC7\u671F\u65F6\u95F4\uFF0C\u5C06\u4F5C\u4E3A Object \u5143\u6570\u636E\u4FDD\u5B58\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ACL \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u6587\u4EF6\u6743\u9650\uFF0C\u6709\u6548\u503C\uFF1Aprivate | public-read\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantRead \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u53D6\u5BF9\u8C61\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantReadAcp \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u8BFB\u53D6\u5BF9\u8C61\u7684\u8BBF\u95EE\u63A7\u5236\u5217\u8868\uFF08ACL\uFF09\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantWriteAcp \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u5199\u5165\u5BF9\u8C61\u7684\u8BBF\u95EE\u63A7\u5236\u5217\u8868\uFF08ACL\uFF09\u7684\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.GrantFullControl \u8D4B\u4E88\u88AB\u6388\u6743\u8005\u64CD\u4F5C\u5BF9\u8C61\u7684\u6240\u6709\u6743\u9650\uFF0C\u683C\u5F0F\uFF1Aid=\"[OwnerUin]\"\uFF0C\u53EF\u4F7F\u7528\u534A\u89D2\u9017\u53F7\uFF08,\uFF09\u5206\u9694\u591A\u7EC4\u88AB\u6388\u6743\u8005\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.StorageClass \u8BBE\u7F6E\u5BF9\u8C61\u7684\u5B58\u50A8\u7EA7\u522B\uFF0C\u679A\u4E3E\u503C\uFF1ASTANDARD\u3001STANDARD_IA\u3001ARCHIVE\uFF0C\u9ED8\u8BA4\u503C\uFF1ASTANDARD\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.x-cos-meta-* \u5141\u8BB8\u7528\u6237\u81EA\u5B9A\u4E49\u7684\u5934\u90E8\u4FE1\u606F\uFF0C\u5C06\u4F5C\u4E3A\u5BF9\u8C61\u7684\u5143\u6570\u636E\u4FDD\u5B58\u3002\u5927\u5C0F\u9650\u52362KB\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ContentSha1 RFC 3174 \u4E2D\u5B9A\u4E49\u7684 160-bit \u5185\u5BB9 SHA-1 \u7B97\u6CD5\u6821\u9A8C\uFF0C\u975E\u5FC5\u987B\n * @param {String} params.ServerSideEncryption \u652F\u6301\u6309\u7167\u6307\u5B9A\u7684\u52A0\u5BC6\u7B97\u6CD5\u8FDB\u884C\u670D\u52A1\u7AEF\u6570\u636E\u52A0\u5BC6\uFF0C\u683C\u5F0F x-cos-server-side-encryption: \"AES256\"\uFF0C\u975E\u5FC5\u987B\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction appendObject(params, callback) {\n // \u7279\u6B8A\u5904\u7406 Cache-Control\u3001Content-Type\uFF0C\u907F\u514D\u4EE3\u7406\u66F4\u6539\u8FD9\u4E24\u4E2A\u5B57\u6BB5\u5BFC\u81F4\u5199\u5165\u5230 Object \u5C5E\u6027\u91CC\n var headers = params.Headers;\n if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';\n if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = params.Body && params.Body.type || '';\n submitRequest.call(this, {\n Action: 'name/cos:AppendObject',\n method: 'POST',\n Bucket: params.Bucket,\n Region: params.Region,\n action: 'append',\n Key: params.Key,\n body: params.Body,\n qs: {\n position: params.Position\n },\n headers: params.Headers,\n tracker: params.tracker\n }, function (err, data) {\n if (err) return callback(err);\n callback(null, data);\n });\n}\n\n/**\n * \u83B7\u53D6\u7B7E\u540D\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Method \u8BF7\u6C42\u65B9\u6CD5\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Expires \u540D\u8D85\u65F6\u65F6\u95F4\uFF0C\u5355\u4F4D\u79D2\uFF0C\u53EF\u9009\n * @return {String} data \u8FD4\u56DE\u7B7E\u540D\u5B57\u7B26\u4E32\n */\nfunction getAuth(params) {\n var self = this;\n return util.getAuth({\n SecretId: params.SecretId || this.options.SecretId || '',\n SecretKey: params.SecretKey || this.options.SecretKey || '',\n Bucket: params.Bucket,\n Region: params.Region,\n Method: params.Method,\n Key: params.Key,\n Query: params.Query,\n Headers: params.Headers,\n Expires: params.Expires,\n UseRawKey: self.options.UseRawKey,\n SystemClockOffset: self.options.SystemClockOffset\n });\n}\n\n/**\n * \u83B7\u53D6\u6587\u4EF6\u4E0B\u8F7D\u94FE\u63A5\n * @param {Object} params \u53C2\u6570\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {String} params.Bucket Bucket\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Region \u5730\u57DF\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Key object\u540D\u79F0\uFF0C\u5FC5\u987B\n * @param {String} params.Method \u8BF7\u6C42\u7684\u65B9\u6CD5\uFF0C\u53EF\u9009\n * @param {String} params.Expires \u7B7E\u540D\u8D85\u65F6\u65F6\u95F4\uFF0C\u5355\u4F4D\u79D2\uFF0C\u53EF\u9009\n * @param {Function} callback \u56DE\u8C03\u51FD\u6570\uFF0C\u5FC5\u987B\n * @return {Object} err \u8BF7\u6C42\u5931\u8D25\u7684\u9519\u8BEF\uFF0C\u5982\u679C\u8BF7\u6C42\u6210\u529F\uFF0C\u5219\u4E3A\u7A7A\u3002https://cloud.tencent.com/document/product/436/7730\n * @return {Object} data \u8FD4\u56DE\u7684\u6570\u636E\n */\nfunction getObjectUrl(params, callback) {\n var self = this;\n var useAccelerate = params.UseAccelerate === undefined ? self.options.UseAccelerate : params.UseAccelerate;\n var url = getUrl({\n ForcePathStyle: self.options.ForcePathStyle,\n protocol: params.Protocol || self.options.Protocol,\n domain: params.Domain || self.options.Domain,\n bucket: params.Bucket,\n region: useAccelerate ? 'accelerate' : params.Region,\n object: params.Key\n });\n var queryParamsStr = '';\n if (params.Query) {\n queryParamsStr += util.obj2str(params.Query);\n }\n if (params.QueryString) {\n queryParamsStr += (queryParamsStr ? '&' : '') + params.QueryString;\n }\n var syncUrl = url;\n if (params.Sign !== undefined && !params.Sign) {\n queryParamsStr && (syncUrl += '?' + queryParamsStr);\n callback(null, {\n Url: syncUrl\n });\n return syncUrl;\n }\n\n // \u7B7E\u540D\u52A0\u4E0A Host\uFF0C\u907F\u514D\u8DE8\u6876\u8BBF\u95EE\n var SignHost = getSignHost.call(this, {\n Bucket: params.Bucket,\n Region: params.Region,\n UseAccelerate: params.UseAccelerate,\n Url: url\n });\n var AuthData = getAuthorizationAsync.call(this, {\n Action: (params.Method || '').toUpperCase() === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject',\n Bucket: params.Bucket || '',\n Region: params.Region || '',\n Method: params.Method || 'get',\n Key: params.Key,\n Expires: params.Expires,\n Headers: params.Headers,\n Query: params.Query,\n SignHost: SignHost,\n ForceSignHost: params.ForceSignHost === false ? false : self.options.ForceSignHost // getObjectUrl\u652F\u6301\u4F20\u53C2ForceSignHost\n }, function (err, AuthData) {\n if (!callback) return;\n if (err) {\n callback(err);\n return;\n }\n\n // \u517C\u5BB9\u4E07\u8C61url qUrlParamList\u9700\u8981\u518Dencode\u4E00\u6B21\n var replaceUrlParamList = function replaceUrlParamList(url) {\n var urlParams = url.match(/q-url-param-list.*?(?=&)/g)[0];\n var encodedParams = 'q-url-param-list=' + encodeURIComponent(urlParams.replace(/q-url-param-list=/, '')).toLowerCase();\n var reg = new RegExp(urlParams, 'g');\n var replacedUrl = url.replace(reg, encodedParams);\n return replacedUrl;\n };\n var signUrl = url;\n signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? replaceUrlParamList(AuthData.Authorization) : 'sign=' + encodeURIComponent(AuthData.Authorization));\n AuthData.SecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.SecurityToken);\n AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP);\n AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA);\n AuthData.Token && (signUrl += '&token=' + AuthData.Token);\n queryParamsStr && (signUrl += '&' + queryParamsStr);\n setTimeout(function () {\n callback(null, {\n Url: signUrl\n });\n });\n });\n if (AuthData) {\n syncUrl += '?' + AuthData.Authorization + (AuthData.SecurityToken ? '&x-cos-security-token=' + AuthData.SecurityToken : '');\n queryParamsStr && (syncUrl += '&' + queryParamsStr);\n } else {\n queryParamsStr && (syncUrl += '?' + queryParamsStr);\n }\n return syncUrl;\n}\n\n/**\n * \u79C1\u6709\u65B9\u6CD5\n */\nfunction decodeAcl(AccessControlPolicy) {\n var result = {\n GrantFullControl: [],\n GrantWrite: [],\n GrantRead: [],\n GrantReadAcp: [],\n GrantWriteAcp: [],\n ACL: ''\n };\n var GrantMap = {\n FULL_CONTROL: 'GrantFullControl',\n WRITE: 'GrantWrite',\n READ: 'GrantRead',\n READ_ACP: 'GrantReadAcp',\n WRITE_ACP: 'GrantWriteAcp'\n };\n var AccessControlList = AccessControlPolicy && AccessControlPolicy.AccessControlList || {};\n var Grant = AccessControlList.Grant;\n if (Grant) {\n Grant = util.isArray(Grant) ? Grant : [Grant];\n }\n var PublicAcl = {\n READ: 0,\n WRITE: 0,\n FULL_CONTROL: 0\n };\n Grant && Grant.length && util.each(Grant, function (item) {\n var uriMatch = item.Grantee.URI && item.Grantee.URI.endsWith('/groups/global/AllUsers');\n if (item.Grantee.ID === 'qcs::cam::anyone:anyone' || uriMatch) {\n PublicAcl[item.Permission] = 1;\n } else if (item.Grantee.ID !== AccessControlPolicy.Owner.ID) {\n result[GrantMap[item.Permission]].push('id=\"' + item.Grantee.ID + '\"');\n }\n });\n if (PublicAcl.FULL_CONTROL || PublicAcl.WRITE && PublicAcl.READ) {\n result.ACL = 'public-read-write';\n } else if (PublicAcl.READ) {\n result.ACL = 'public-read';\n } else {\n result.ACL = 'private';\n }\n util.each(GrantMap, function (item) {\n result[item] = uniqGrant(result[item].join(','));\n });\n return result;\n}\n\n// Grant \u53BB\u91CD\nfunction uniqGrant(str) {\n var arr = str.split(',');\n var exist = {};\n var i, item;\n for (i = 0; i < arr.length;) {\n item = arr[i].trim();\n if (exist[item]) {\n arr.splice(i, 1);\n } else {\n exist[item] = true;\n arr[i] = item;\n i++;\n }\n }\n return arr.join(',');\n}\n\n// \u751F\u6210\u64CD\u4F5C url\nfunction getUrl(params) {\n var region = params.region || '';\n var longBucket = params.bucket || '';\n var shortBucket = longBucket.substr(0, longBucket.lastIndexOf('-'));\n var appId = longBucket.substr(longBucket.lastIndexOf('-') + 1);\n var domain = params.domain;\n var object = params.object;\n if (typeof domain === 'function') {\n domain = domain({\n Bucket: longBucket,\n Region: region\n });\n }\n // \u517C\u5BB9\u4E0D\u5E26\u5192\u53F7\u7684http\u3001https\n if (['http', 'https'].includes(params.protocol)) {\n params.protocol = params.protocol + ':';\n }\n var protocol = params.protocol || (util.isBrowser && (typeof location === \"undefined\" ? \"undefined\" : _typeof(location)) === 'object' && location.protocol === 'http:' ? 'http:' : 'https:');\n if (!domain) {\n if (['cn-south', 'cn-south-2', 'cn-north', 'cn-east', 'cn-southwest', 'sg'].indexOf(region) > -1) {\n domain = '{Region}.myqcloud.com';\n } else {\n domain = 'cos.{Region}.myqcloud.com';\n }\n if (!params.ForcePathStyle) {\n domain = '{Bucket}.' + domain;\n }\n }\n domain = domain.replace(/\\{\\{AppId\\}\\}/gi, appId).replace(/\\{\\{Bucket\\}\\}/gi, shortBucket).replace(/\\{\\{Region\\}\\}/gi, region).replace(/\\{\\{.*?\\}\\}/gi, '');\n domain = domain.replace(/\\{AppId\\}/gi, appId).replace(/\\{BucketName\\}/gi, shortBucket).replace(/\\{Bucket\\}/gi, longBucket).replace(/\\{Region\\}/gi, region).replace(/\\{.*?\\}/gi, '');\n if (!/^[a-zA-Z]+:\\/\\//.test(domain)) {\n domain = protocol + '//' + domain;\n }\n\n // \u53BB\u6389\u57DF\u540D\u6700\u540E\u7684\u659C\u6746\n if (domain.slice(-1) === '/') {\n domain = domain.slice(0, -1);\n }\n var url = domain;\n if (params.ForcePathStyle) {\n url += '/' + longBucket;\n }\n url += '/';\n if (object) {\n url += util.camSafeUrlEncode(object).replace(/%2F/g, '/');\n }\n if (params.isLocation) {\n url = url.replace(/^https?:\\/\\//, '');\n }\n return url;\n}\nvar getSignHost = function getSignHost(opt) {\n if (!opt.Bucket || !opt.Region) return '';\n var useAccelerate = opt.UseAccelerate === undefined ? this.options.UseAccelerate : opt.UseAccelerate;\n var url = opt.Url || getUrl({\n ForcePathStyle: this.options.ForcePathStyle,\n protocol: this.options.Protocol,\n domain: this.options.Domain,\n bucket: opt.Bucket,\n region: useAccelerate ? 'accelerate' : opt.Region\n });\n var urlHost = url.replace(/^https?:\\/\\/([^/]+)(\\/.*)?$/, '$1');\n return urlHost;\n};\n\n// \u5F02\u6B65\u83B7\u53D6\u7B7E\u540D\nfunction getAuthorizationAsync(params, callback) {\n var headers = util.clone(params.Headers);\n var headerHost = '';\n util.each(headers, function (v, k) {\n (v === '' || ['content-type', 'cache-control', 'expires'].indexOf(k.toLowerCase()) > -1) && delete headers[k];\n if (k.toLowerCase() === 'host') headerHost = v;\n });\n // ForceSignHost\u660E\u786E\u4F20\u5165false\u624D\u4E0D\u52A0\u5165host\u7B7E\u540D\n var forceSignHost = params.ForceSignHost === false ? false : true;\n\n // Host \u52A0\u5165\u7B7E\u540D\u8BA1\u7B97\n if (!headerHost && params.SignHost && forceSignHost) headers.Host = params.SignHost;\n\n // \u83B7\u53D6\u51ED\u8BC1\u7684\u56DE\u8C03\uFF0C\u907F\u514D\u7528\u6237 callback \u591A\u6B21\n var cbDone = false;\n var cb = function cb(err, AuthData) {\n if (cbDone) return;\n cbDone = true;\n if (AuthData && AuthData.XCosSecurityToken && !AuthData.SecurityToken) {\n AuthData = util.clone(AuthData);\n AuthData.SecurityToken = AuthData.XCosSecurityToken;\n delete AuthData.XCosSecurityToken;\n }\n callback && callback(err, AuthData);\n };\n var self = this;\n var Bucket = params.Bucket || '';\n var Region = params.Region || '';\n\n // PathName\n var KeyName = params.Key || '';\n if (self.options.ForcePathStyle && Bucket) {\n KeyName = Bucket + '/' + KeyName;\n }\n var Pathname = '/' + KeyName;\n\n // Action\u3001ResourceKey\n var StsData = {};\n var Scope = params.Scope;\n if (!Scope) {\n var Action = params.Action || '';\n var ResourceKey = params.ResourceKey || params.Key || '';\n Scope = params.Scope || [{\n action: Action,\n bucket: Bucket,\n region: Region,\n prefix: ResourceKey\n }];\n }\n var ScopeKey = util.md5(JSON.stringify(Scope));\n\n // STS\n self._StsCache = self._StsCache || [];\n (function () {\n var i, AuthData;\n for (i = self._StsCache.length - 1; i >= 0; i--) {\n AuthData = self._StsCache[i];\n var compareTime = Math.round(util.getSkewTime(self.options.SystemClockOffset) / 1000) + 30;\n if (AuthData.StartTime && compareTime < AuthData.StartTime || compareTime >= AuthData.ExpiredTime) {\n self._StsCache.splice(i, 1);\n continue;\n }\n if (!AuthData.ScopeLimit || AuthData.ScopeLimit && AuthData.ScopeKey === ScopeKey) {\n StsData = AuthData;\n break;\n }\n }\n })();\n var calcAuthByTmpKey = function calcAuthByTmpKey() {\n var KeyTime = '';\n if (StsData.StartTime && params.Expires) KeyTime = StsData.StartTime + ';' + (StsData.StartTime + params.Expires * 1);else if (StsData.StartTime && StsData.ExpiredTime) KeyTime = StsData.StartTime + ';' + StsData.ExpiredTime;\n var Authorization = util.getAuth({\n SecretId: StsData.TmpSecretId,\n SecretKey: StsData.TmpSecretKey,\n Method: params.Method,\n Pathname: Pathname,\n Query: params.Query,\n Headers: headers,\n Expires: params.Expires,\n UseRawKey: self.options.UseRawKey,\n SystemClockOffset: self.options.SystemClockOffset,\n KeyTime: KeyTime,\n ForceSignHost: forceSignHost\n });\n var AuthData = {\n Authorization: Authorization,\n SecurityToken: StsData.SecurityToken || StsData.XCosSecurityToken || '',\n Token: StsData.Token || '',\n ClientIP: StsData.ClientIP || '',\n ClientUA: StsData.ClientUA || '',\n SignFrom: 'client'\n };\n cb(null, AuthData);\n };\n var checkAuthError = function checkAuthError(AuthData) {\n if (AuthData.Authorization) {\n // \u68C0\u67E5\u7B7E\u540D\u683C\u5F0F\n var formatAllow = false;\n var auth = AuthData.Authorization;\n if (auth) {\n if (auth.indexOf(' ') > -1) {\n formatAllow = false;\n } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) {\n formatAllow = true;\n } else {\n try {\n auth = atob(auth);\n if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) {\n formatAllow = true;\n }\n } catch (e) {}\n }\n }\n if (!formatAllow) return util.error(new Error('getAuthorization callback params format error'));\n } else {\n if (!AuthData.TmpSecretId) return util.error(new Error('getAuthorization callback params missing \"TmpSecretId\"'));\n if (!AuthData.TmpSecretKey) return util.error(new Error('getAuthorization callback params missing \"TmpSecretKey\"'));\n if (!AuthData.SecurityToken && !AuthData.XCosSecurityToken) return util.error(new Error('getAuthorization callback params missing \"SecurityToken\"'));\n if (!AuthData.ExpiredTime) return util.error(new Error('getAuthorization callback params missing \"ExpiredTime\"'));\n if (AuthData.ExpiredTime && AuthData.ExpiredTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params \"ExpiredTime\" should be 10 digits'));\n if (AuthData.StartTime && AuthData.StartTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params \"StartTime\" should be 10 StartTime'));\n }\n return false;\n };\n\n // \u5148\u5224\u65AD\u662F\u5426\u6709\u4E34\u65F6\u5BC6\u94A5\n if (StsData.ExpiredTime && StsData.ExpiredTime - util.getSkewTime(self.options.SystemClockOffset) / 1000 > 60) {\n // \u5982\u679C\u7F13\u5B58\u7684\u4E34\u65F6\u5BC6\u94A5\u6709\u6548\uFF0C\u5E76\u8FD8\u6709\u8D85\u8FC760\u79D2\u6709\u6548\u671F\u5C31\u76F4\u63A5\u4F7F\u7528\n calcAuthByTmpKey();\n } else if (self.options.getAuthorization) {\n // \u5916\u90E8\u8BA1\u7B97\u7B7E\u540D\u6216\u83B7\u53D6\u4E34\u65F6\u5BC6\u94A5\n self.options.getAuthorization.call(self, {\n Bucket: Bucket,\n Region: Region,\n Method: params.Method,\n Key: KeyName,\n Pathname: Pathname,\n Query: params.Query,\n Headers: headers,\n Scope: Scope,\n SystemClockOffset: self.options.SystemClockOffset,\n ForceSignHost: forceSignHost\n }, function (AuthData) {\n if (typeof AuthData === 'string') AuthData = {\n Authorization: AuthData\n };\n var AuthError = checkAuthError(AuthData);\n if (AuthError) return cb(AuthError);\n if (AuthData.Authorization) {\n cb(null, AuthData);\n } else {\n StsData = AuthData || {};\n StsData.Scope = Scope;\n StsData.ScopeKey = ScopeKey;\n self._StsCache.push(StsData);\n calcAuthByTmpKey();\n }\n });\n } else if (self.options.getSTS) {\n // \u5916\u90E8\u83B7\u53D6\u4E34\u65F6\u5BC6\u94A5\n self.options.getSTS.call(self, {\n Bucket: Bucket,\n Region: Region\n }, function (data) {\n StsData = data || {};\n StsData.Scope = Scope;\n StsData.ScopeKey = ScopeKey;\n if (!StsData.TmpSecretId) StsData.TmpSecretId = StsData.SecretId;\n if (!StsData.TmpSecretKey) StsData.TmpSecretKey = StsData.SecretKey;\n var AuthError = checkAuthError(StsData);\n if (AuthError) return cb(AuthError);\n self._StsCache.push(StsData);\n calcAuthByTmpKey();\n });\n } else {\n // \u5185\u90E8\u8BA1\u7B97\u83B7\u53D6\u7B7E\u540D\n return function () {\n var KeyTime = '';\n if (self.options.StartTime && params.Expires) {\n if (self.options.StartTime.toString().length !== 10) {\n return cb(util.error(new Error('params \"StartTime\" should be 10 digits')));\n }\n KeyTime = self.options.StartTime + ';' + (self.options.StartTime + params.Expires * 1);\n } else if (self.options.StartTime && self.options.ExpiredTime) {\n if (self.options.StartTime.toString().length !== 10) {\n return cb(util.error(new Error('params \"StartTime\" should be 10 digits')));\n }\n if (self.options.ExpiredTime.toString().length !== 10) {\n return cb(util.error(new Error('params \"ExpiredTime\" should be 10 digits')));\n }\n KeyTime = self.options.StartTime + ';' + self.options.ExpiredTime * 1;\n }\n var Authorization = util.getAuth({\n SecretId: params.SecretId || self.options.SecretId,\n SecretKey: params.SecretKey || self.options.SecretKey,\n Method: params.Method,\n Pathname: Pathname,\n Query: params.Query,\n Headers: headers,\n Expires: params.Expires,\n KeyTime: KeyTime,\n UseRawKey: self.options.UseRawKey,\n SystemClockOffset: self.options.SystemClockOffset,\n ForceSignHost: forceSignHost\n });\n var AuthData = {\n Authorization: Authorization,\n SecurityToken: self.options.SecurityToken || self.options.XCosSecurityToken,\n SignFrom: 'client'\n };\n cb(null, AuthData);\n return AuthData;\n }();\n }\n return '';\n}\n\n// \u5224\u65AD\u5F53\u524D\u8BF7\u6C42\u51FA\u9519\u65F6\u80FD\u5426\u91CD\u8BD5\nfunction allowRetry(err) {\n var self = this;\n var canRetry = false;\n var isTimeError = false;\n var networkError = false;\n var serverDate = err.headers && (err.headers.date || err.headers.Date) || err.error && err.error.ServerTime;\n try {\n var errorCode = err.error.Code;\n var errorMessage = err.error.Message;\n if (errorCode === 'RequestTimeTooSkewed' || errorCode === 'AccessDenied' && errorMessage === 'Request has expired') {\n isTimeError = true;\n }\n } catch (e) {}\n if (err) {\n // \u8C03\u6574\u65F6\u95F4\u504F\u5DEE\n if (isTimeError && serverDate) {\n var serverTime = Date.parse(serverDate);\n if (this.options.CorrectClockSkew && Math.abs(util.getSkewTime(this.options.SystemClockOffset) - serverTime) >= 30000) {\n console.error('error: Local time is too skewed.');\n this.options.SystemClockOffset = serverTime - Date.now();\n canRetry = true;\n }\n } else if (Math.floor(err.statusCode / 100) === 5) {\n canRetry = true;\n } else if (err.message === 'CORS blocked or network error') {\n // \u8DE8\u57DF/\u7F51\u7EDC\u9519\u8BEF\u90FD\u5305\u542B\u5728\u5185\n networkError = true;\n canRetry = self.options.AutoSwitchHost;\n }\n }\n return {\n canRetry: canRetry,\n networkError: networkError\n };\n}\n\n/**\n * requestUrl\uFF1A\u8BF7\u6C42\u7684url\uFF0C\u7528\u4E8E\u5224\u65AD\u662F\u5426cos\u4E3B\u57DF\u540D\uFF0Ctrue\u624D\u5207\n * clientCalcSign\uFF1A\u662F\u5426\u5BA2\u6237\u7AEF\u8BA1\u7B97\u7B7E\u540D\uFF0C\u670D\u52A1\u7AEF\u8FD4\u56DE\u7684\u7B7E\u540D\u4E0D\u80FD\u5207\uFF0Ctrue\u624D\u5207\n * networkError\uFF1A\u662F\u5426\u672A\u77E5\u7F51\u7EDC\u9519\u8BEF\uFF0Ctrue\u624D\u5207\n * */\nfunction canSwitchHost(_ref) {\n var requestUrl = _ref.requestUrl,\n clientCalcSign = _ref.clientCalcSign,\n networkError = _ref.networkError;\n if (!this.options.AutoSwitchHost) return false;\n if (!requestUrl) return false;\n if (!clientCalcSign) return false;\n if (!networkError) return false;\n var commonReg = /^https?:\\/\\/[^\\/]*\\.cos\\.[^\\/]*\\.myqcloud\\.com(\\/.*)?$/;\n var accelerateReg = /^https?:\\/\\/[^\\/]*\\.cos\\.accelerate\\.myqcloud\\.com(\\/.*)?$/;\n // \u5F53\u524D\u57DF\u540D\u662Fcos\u4E3B\u57DF\u540D\u624D\u5207\u6362\n var isCommonCosHost = commonReg.test(requestUrl) && !accelerateReg.test(requestUrl);\n return isCommonCosHost;\n}\n\n// \u83B7\u53D6\u7B7E\u540D\u5E76\u53D1\u8D77\u8BF7\u6C42\nfunction submitRequest(params, callback) {\n var self = this;\n\n // \u5904\u7406 headers\n !params.headers && (params.headers = {});\n\n // \u5904\u7406 query\n !params.qs && (params.qs = {});\n params.VersionId && (params.qs.versionId = params.VersionId);\n params.qs = util.clearKey(params.qs);\n\n // \u6E05\u7406 undefined \u548C null \u5B57\u6BB5\n params.headers && (params.headers = util.clearKey(params.headers));\n params.qs && (params.qs = util.clearKey(params.qs));\n var Query = util.clone(params.qs);\n params.action && (Query[params.action] = '');\n\n /**\n * \u624B\u52A8\u4F20params.SignHost\u7684\u573A\u666F\uFF1Acos.getService\u3001cos.getObjectUrl\n * \u624B\u52A8\u4F20Url\u7684\u573A\u666F\uFF1Acos.request\n */\n var paramsUrl = params.url || params.Url;\n var SignHost = params.SignHost || getSignHost.call(this, {\n Bucket: params.Bucket,\n Region: params.Region,\n Url: paramsUrl\n });\n var tracker = params.tracker;\n var next = function next(tryTimes) {\n var oldClockOffset = self.options.SystemClockOffset;\n tracker && tracker.setParams({\n signStartTime: new Date().getTime(),\n httpRetryTimes: tryTimes - 1\n });\n if (params.SwitchHost) {\n // \u66F4\u6362\u8981\u7B7E\u7684host\n SignHost = SignHost.replace(/myqcloud.com/, 'tencentcos.cn');\n }\n getAuthorizationAsync.call(self, {\n Bucket: params.Bucket || '',\n Region: params.Region || '',\n Method: params.method,\n Key: params.Key,\n Query: Query,\n Headers: params.headers,\n SignHost: SignHost,\n Action: params.Action,\n ResourceKey: params.ResourceKey,\n Scope: params.Scope,\n ForceSignHost: self.options.ForceSignHost,\n SwitchHost: params.SwitchHost\n }, function (err, AuthData) {\n if (err) {\n callback(err);\n return;\n }\n tracker && tracker.setParams({\n signEndTime: new Date().getTime(),\n httpStartTime: new Date().getTime()\n });\n params.AuthData = AuthData;\n _submitRequest.call(self, params, function (err, data) {\n tracker && tracker.setParams({\n httpEndTime: new Date().getTime()\n });\n var canRetry = false;\n var networkError = false;\n if (err) {\n var info = allowRetry.call(self, err);\n canRetry = info.canRetry || oldClockOffset !== self.options.SystemClockOffset;\n networkError = info.networkError;\n }\n if (err && tryTimes < 2 && canRetry) {\n if (params.headers) {\n delete params.headers.Authorization;\n delete params.headers['token'];\n delete params.headers['clientIP'];\n delete params.headers['clientUA'];\n params.headers['x-cos-security-token'] && delete params.headers['x-cos-security-token'];\n params.headers['x-ci-security-token'] && delete params.headers['x-ci-security-token'];\n }\n // \u8FDB\u5165\u91CD\u8BD5\u903B\u8F91\u65F6 \u9700\u5224\u65AD\u662F\u5426\u9700\u8981\u5207\u6362cos\u5907\u7528\u57DF\u540D\n var switchHost = canSwitchHost.call(self, {\n requestUrl: (err === null || err === void 0 ? void 0 : err.url) || '',\n clientCalcSign: AuthData.SignFrom === 'client',\n networkError: networkError\n });\n params.SwitchHost = switchHost;\n params.retry = true;\n next(tryTimes + 1);\n } else {\n callback(err, data);\n }\n });\n });\n };\n next(1);\n}\n\n// \u53D1\u8D77\u8BF7\u6C42\nfunction _submitRequest(params, callback) {\n var self = this;\n var TaskId = params.TaskId;\n if (TaskId && !self._isRunningTask(TaskId)) return;\n var bucket = params.Bucket;\n var region = params.Region;\n var object = params.Key;\n var method = params.method || 'GET';\n var url = params.Url || params.url;\n var body = params.body;\n var rawBody = params.rawBody;\n\n // url\n if (self.options.UseAccelerate) {\n region = 'accelerate';\n }\n url = url || getUrl({\n ForcePathStyle: self.options.ForcePathStyle,\n protocol: self.options.Protocol,\n domain: self.options.Domain,\n bucket: bucket,\n region: region,\n object: object\n });\n if (params.SwitchHost) {\n // \u66F4\u6362\u8BF7\u6C42\u7684url\n url = url.replace(/myqcloud.com/, 'tencentcos.cn');\n }\n var repoterUrl = object ? url : '';\n if (params.action) {\n // \u5DF2\u77E5\u95EE\u9898\uFF0C\u67D0\u4E9B\u7248\u672C\u7684qq\u4F1A\u5BF9url\u81EA\u52A8\u62FC\u63A5\uFF08\u6BD4\u5982/upload\u88AB\u62FC\u63A5\u6210/upload=(null)\uFF09\u5BFC\u81F4\u7B7E\u540D\u9519\u8BEF\uFF0C\u8FD9\u91CC\u505A\u4E0B\u517C\u5BB9\u3002\n url = url + '?' + (util.isIOS_QQ ? \"\".concat(params.action, \"=\") : params.action);\n }\n if (params.qsStr) {\n if (url.indexOf('?') > -1) {\n url = url + '&' + params.qsStr;\n } else {\n url = url + '?' + params.qsStr;\n }\n }\n var opt = {\n method: method,\n url: url,\n headers: params.headers,\n qs: params.qs,\n body: body\n };\n\n // \u517C\u5BB9ci\u63A5\u53E3\n var token = 'x-cos-security-token';\n if (util.isCIHost(url)) {\n token = 'x-ci-security-token';\n }\n\n // \u83B7\u53D6\u7B7E\u540D\n opt.headers.Authorization = params.AuthData.Authorization;\n params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token);\n params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP);\n params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA);\n params.AuthData.SecurityToken && (opt.headers[token] = params.AuthData.SecurityToken);\n params.Action && (opt.action = params.Action);\n opt.key = params.Key || params.ResourceKey;\n\n // \u6E05\u7406 undefined \u548C null \u5B57\u6BB5\n opt.headers && (opt.headers = util.clearKey(opt.headers));\n if (params.retry) {\n opt.headers['x-cos-sdk-retry'] = true;\n }\n opt = util.clearKey(opt);\n\n // progress\n if (params.onProgress && typeof params.onProgress === 'function') {\n var contentLength = body && (body.size || body.length) || 0;\n opt.onProgress = function (e) {\n if (TaskId && !self._isRunningTask(TaskId)) return;\n var loaded = e ? e.loaded : 0;\n params.onProgress({\n loaded: loaded,\n total: contentLength\n });\n };\n }\n if (params.onDownloadProgress) {\n opt.onDownloadProgress = params.onDownloadProgress;\n }\n if (params.DataType) {\n opt.dataType = params.DataType;\n }\n if (this.options.Timeout) {\n opt.timeout = this.options.Timeout;\n }\n self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle);\n self.emit('before-send', opt);\n var useAccelerate = opt.url.includes('accelerate.');\n var queryString = opt.qs ? Object.keys(opt.qs).map(function (key) {\n return \"\".concat(key, \"=\").concat(opt.qs[key]);\n }).join('&') : '';\n var fullUrl = queryString ? opt.url + '?' + queryString : opt.url;\n if (params.tracker) {\n var _opt$body;\n params.tracker.setParams({\n url: fullUrl,\n httpMethod: opt.method,\n accelerate: useAccelerate,\n httpSize: ((_opt$body = opt.body) === null || _opt$body === void 0 ? void 0 : _opt$body.size) || 0\n });\n // \u5206\u5757\u4E0A\u4F20\u65F6\u7ED9\u7236\u7EA7tracker\u8BBE\u7F6Eurl\u4FE1\u606F\n if (params.tracker.parent && !params.tracker.parent.params.url) {\n params.tracker.parent.setParams({\n url: repoterUrl,\n accelerate: useAccelerate\n });\n }\n }\n var sender = (self.options.Request || REQUEST)(opt, function (r) {\n if (r && r.error === 'abort') return;\n var receive = {\n options: opt,\n error: r && r.error,\n statusCode: r && r.statusCode || 0,\n statusMessage: r && r.statusMessage || '',\n headers: r && r.headers || {},\n body: r && r.body\n };\n // \u629B\u51FA\u4E8B\u4EF6\uFF0C\u5141\u8BB8\u4FEE\u6539\u8FD4\u56DE\u503C\u7684 error\u3001statusCode\u3001statusMessage\u3001body\n self.emit('after-receive', receive);\n var err = receive.error;\n var body = receive.body;\n // \u8FD4\u56DE\u5185\u5BB9\u6DFB\u52A0 \u72B6\u6001\u7801 \u548C headers\n var response = {\n statusCode: receive.statusCode,\n statusMessage: receive.statusMessage,\n headers: receive.headers\n };\n var hasReturned;\n var cb = function cb(err, data) {\n TaskId && self.off('inner-kill-task', killTask);\n if (hasReturned) return;\n hasReturned = true;\n var attrs = {};\n response && response.statusCode && (attrs.statusCode = response.statusCode);\n response && response.headers && (attrs.headers = response.headers);\n if (err) {\n opt.url && (attrs.url = opt.url);\n opt.method && (attrs.method = opt.method);\n err = util.extend(err || {}, attrs);\n callback(err, null);\n } else {\n // putObject \u8FD4\u56DE\u56DE\u8C03\u5904\u7406\n if (params.Action === 'name/cos:PutObject') {\n var pHeaders = {};\n for (var i in params.headers) {\n var key = i.toLowerCase();\n pHeaders[key] = params.headers[i];\n }\n if (pHeaders['x-cos-callback']) {\n if (data.Error) {\n data.CallbackError = util.clone(data.Error);\n delete data.Error;\n } else {\n data.CallbackBody = util.clone(data);\n }\n } else if (pHeaders['x-cos-return-body']) {\n if (data.Error) {\n data.ReturnError = util.clone(data.Error);\n delete data.Error;\n } else {\n data.ReturnBody = util.clone(data);\n }\n }\n }\n data = util.extend(data || {}, attrs);\n callback(null, data);\n }\n sender = null;\n };\n\n // \u8BF7\u6C42\u9519\u8BEF\uFF0C\u53D1\u751F\u7F51\u7EDC\u9519\u8BEF\n if (err) return cb(util.error(err));\n\n // \u8BF7\u6C42\u8FD4\u56DE\u7801\u4E0D\u4E3A 200\n var statusCode = response.statusCode;\n var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206\n\n // \u4E0D\u5BF9 body \u8FDB\u884C\u8F6C\u6362\uFF0Cbody \u76F4\u63A5\u6302\u8F7D\u8FD4\u56DE\n if (rawBody) {\n if (statusSuccess) {\n return cb(null, {\n body: body\n });\n } else {\n // \u517C\u5BB9\u62A5\u9519\u65F6\u8FD4\u56DE\u4E86 blob\uFF0C\u9700\u8981\u89E3\u6790\u6210 string\n if (body instanceof Blob) {\n util.readAsBinaryString(body, function (content) {\n var json = util.parseResBody(content);\n var errorBody = json.Error || json;\n return cb(util.error(new Error(errorBody.Message || 'response body error'), {\n code: errorBody.Code,\n error: errorBody\n }));\n });\n return;\n }\n }\n }\n\n // \u89E3\u6790body\uFF0C\u517C\u5BB9 xml\u3001json\uFF0C\u89E3\u6790\u5931\u8D25\u65F6\u5B8C\u6574\u8FD4\u56DE\n var json = util.parseResBody(body);\n\n // \u5904\u7406\u8FD4\u56DE\u503C\n var errorBody = json.Error || json;\n if (statusSuccess) {\n // \u6B63\u786E\u8FD4\u56DE\uFF0C\u72B6\u6001\u7801 2xx \u65F6\uFF0Cbody \u4E0D\u4F1A\u6709 Error\n cb(null, json);\n } else if (errorBody) {\n // \u6B63\u5E38\u8FD4\u56DE\u4E86 xml body\uFF0C\u4E14\u6709 Error \u8282\u70B9\n cb(util.error(new Error(errorBody.Message), {\n code: errorBody.Code,\n error: errorBody\n }));\n } else if (statusCode) {\n // \u6709\u9519\u8BEF\u7684\u72B6\u6001\u7801\n cb(util.error(new Error(response.statusMessage), {\n code: '' + statusCode\n }));\n } else if (statusCode) {\n // \u65E0\u72B6\u6001\u7801\uFF0C\u6216\u8005\u83B7\u53D6\u4E0D\u5230\u72B6\u6001\u7801\n cb(util.error(new Error('statusCode error')));\n }\n });\n\n // kill task\n var killTask = function killTask(data) {\n if (data.TaskId === TaskId) {\n sender && sender.abort && sender.abort();\n self.off('inner-kill-task', killTask);\n }\n };\n TaskId && self.on('inner-kill-task', killTask);\n}\nvar API_MAP = {\n // Bucket \u76F8\u5173\u65B9\u6CD5\n getService: getService,\n // Bucket\n putBucket: putBucket,\n headBucket: headBucket,\n // Bucket\n getBucket: getBucket,\n deleteBucket: deleteBucket,\n putBucketAcl: putBucketAcl,\n // BucketACL\n getBucketAcl: getBucketAcl,\n putBucketCors: putBucketCors,\n // BucketCors\n getBucketCors: getBucketCors,\n deleteBucketCors: deleteBucketCors,\n getBucketLocation: getBucketLocation,\n // BucketLocation\n getBucketPolicy: getBucketPolicy,\n // BucketPolicy\n putBucketPolicy: putBucketPolicy,\n deleteBucketPolicy: deleteBucketPolicy,\n putBucketTagging: putBucketTagging,\n // BucketTagging\n getBucketTagging: getBucketTagging,\n deleteBucketTagging: deleteBucketTagging,\n putBucketLifecycle: putBucketLifecycle,\n // BucketLifecycle\n getBucketLifecycle: getBucketLifecycle,\n deleteBucketLifecycle: deleteBucketLifecycle,\n putBucketVersioning: putBucketVersioning,\n // BucketVersioning\n getBucketVersioning: getBucketVersioning,\n putBucketReplication: putBucketReplication,\n // BucketReplication\n getBucketReplication: getBucketReplication,\n deleteBucketReplication: deleteBucketReplication,\n putBucketWebsite: putBucketWebsite,\n // BucketWebsite\n getBucketWebsite: getBucketWebsite,\n deleteBucketWebsite: deleteBucketWebsite,\n putBucketReferer: putBucketReferer,\n // BucketReferer\n getBucketReferer: getBucketReferer,\n putBucketDomain: putBucketDomain,\n // BucketDomain\n getBucketDomain: getBucketDomain,\n deleteBucketDomain: deleteBucketDomain,\n putBucketOrigin: putBucketOrigin,\n // BucketOrigin\n getBucketOrigin: getBucketOrigin,\n deleteBucketOrigin: deleteBucketOrigin,\n putBucketLogging: putBucketLogging,\n // BucketLogging\n getBucketLogging: getBucketLogging,\n putBucketInventory: putBucketInventory,\n // BucketInventory\n postBucketInventory: postBucketInventory,\n getBucketInventory: getBucketInventory,\n listBucketInventory: listBucketInventory,\n deleteBucketInventory: deleteBucketInventory,\n putBucketAccelerate: putBucketAccelerate,\n getBucketAccelerate: getBucketAccelerate,\n putBucketEncryption: putBucketEncryption,\n getBucketEncryption: getBucketEncryption,\n deleteBucketEncryption: deleteBucketEncryption,\n // Object \u76F8\u5173\u65B9\u6CD5\n getObject: getObject,\n headObject: headObject,\n listObjectVersions: listObjectVersions,\n putObject: putObject,\n deleteObject: deleteObject,\n getObjectAcl: getObjectAcl,\n putObjectAcl: putObjectAcl,\n optionsObject: optionsObject,\n putObjectCopy: putObjectCopy,\n deleteMultipleObject: deleteMultipleObject,\n restoreObject: restoreObject,\n putObjectTagging: putObjectTagging,\n getObjectTagging: getObjectTagging,\n deleteObjectTagging: deleteObjectTagging,\n selectObjectContent: selectObjectContent,\n appendObject: appendObject,\n // \u5206\u5757\u4E0A\u4F20\u76F8\u5173\u65B9\u6CD5\n uploadPartCopy: uploadPartCopy,\n multipartInit: multipartInit,\n multipartUpload: multipartUpload,\n multipartComplete: multipartComplete,\n multipartList: multipartList,\n multipartListPart: multipartListPart,\n multipartAbort: multipartAbort,\n // \u5DE5\u5177\u65B9\u6CD5\n request: request,\n getObjectUrl: getObjectUrl,\n getAuth: getAuth\n};\nfunction warnOldApi(apiName, fn, proto) {\n util.each(['Cors', 'Acl'], function (suffix) {\n if (apiName.slice(-suffix.length) === suffix) {\n var oldName = apiName.slice(0, -suffix.length) + suffix.toUpperCase();\n var apiFn = util.apiWrapper(apiName, fn);\n var warned = false;\n proto[oldName] = function () {\n !warned && console.warn('warning: cos.' + oldName + ' has been deprecated. Please Use cos.' + apiName + ' instead.');\n warned = true;\n apiFn.apply(this, arguments);\n };\n }\n });\n}\nmodule.exports.init = function (COS, task) {\n task.transferToTaskMethod(API_MAP, 'putObject');\n util.each(API_MAP, function (fn, apiName) {\n COS.prototype[apiName] = util.apiWrapper(apiName, fn);\n warnOldApi(apiName, fn, COS.prototype);\n });\n};\n\n/***/ }),\n\n/***/ \"./src/cos.js\":\n/*!********************!*\\\n !*** ./src/cos.js ***!\n \\********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar util = __webpack_require__(/*! ./util */ \"./src/util.js\");\nvar event = __webpack_require__(/*! ./event */ \"./src/event.js\");\nvar task = __webpack_require__(/*! ./task */ \"./src/task.js\");\nvar base = __webpack_require__(/*! ./base */ \"./src/base.js\");\nvar advance = __webpack_require__(/*! ./advance */ \"./src/advance.js\");\nvar pkg = __webpack_require__(/*! ../package.json */ \"./package.json\");\nvar defaultOptions = {\n AppId: '',\n // AppId \u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u62FC\u63A5\u5230 Bucket \u540E\u4F20\u5165\uFF0C\u4F8B\u5982\uFF1Atest-1250000000\n SecretId: '',\n SecretKey: '',\n SecurityToken: '',\n // \u4F7F\u7528\u4E34\u65F6\u5BC6\u94A5\u9700\u8981\u6CE8\u610F\u81EA\u884C\u5237\u65B0 Token\n StartTime: 0,\n // \u4E34\u65F6\u5BC6\u94A5\u8FD4\u56DE\u8D77\u59CB\u65F6\u95F4\n ExpiredTime: 0,\n // \u4E34\u65F6\u5BC6\u94A5\u8FC7\u671F\u65F6\u95F4\n ChunkRetryTimes: 2,\n FileParallelLimit: 3,\n ChunkParallelLimit: 3,\n ChunkSize: 1024 * 1024,\n SliceSize: 1024 * 1024,\n CopyChunkParallelLimit: 20,\n CopyChunkSize: 1024 * 1024 * 10,\n CopySliceSize: 1024 * 1024 * 10,\n MaxPartNumber: 10000,\n ProgressInterval: 1000,\n Domain: '',\n ServiceDomain: '',\n Protocol: '',\n CompatibilityMode: false,\n ForcePathStyle: false,\n UseRawKey: false,\n Timeout: 0,\n // \u5355\u4F4D\u6BEB\u79D2\uFF0C0 \u4EE3\u8868\u4E0D\u8BBE\u7F6E\u8D85\u65F6\u65F6\u95F4\n CorrectClockSkew: true,\n SystemClockOffset: 0,\n // \u5355\u4F4D\u6BEB\u79D2\uFF0Cms\n UploadCheckContentMd5: false,\n UploadQueueSize: 10000,\n UploadAddMetaMd5: false,\n UploadIdCacheLimit: 50,\n UseAccelerate: false,\n ForceSignHost: true,\n // \u9ED8\u8BA4\u5C06host\u52A0\u5165\u7B7E\u540D\u8BA1\u7B97\uFF0C\u5173\u95ED\u540E\u53EF\u80FD\u5BFC\u81F4\u8D8A\u6743\u98CE\u9669\uFF0C\u5EFA\u8BAE\u4FDD\u6301\u4E3Atrue\n AutoSwitchHost: true,\n CopySourceParser: null,\n // \u81EA\u5B9A\u4E49\u62F7\u8D1D\u6E90\u89E3\u6790\u5668\n ObjectKeySimplifyCheck: true,\n // \u5F00\u542F\u5408\u5E76\u6821\u9A8C getObject Key\n /** \u4E0A\u62A5\u76F8\u5173 **/\n DeepTracker: false,\n // \u4E0A\u62A5\u65F6\u662F\u5426\u5BF9\u6BCF\u4E2A\u5206\u5757\u4E0A\u4F20\u505A\u5355\u72EC\u4E0A\u62A5\n TrackerDelay: 5000,\n // \u5468\u671F\u6027\u4E0A\u62A5\uFF0C\u5355\u4F4D\u6BEB\u79D2\u30020\u4EE3\u8868\u5B9E\u65F6\u4E0A\u62A5\n CustomId: '',\n // \u81EA\u5B9A\u4E49\u4E0A\u62A5id\n BeaconReporter: null,\n // \u706F\u5854\u4E0A\u62A5\u7EC4\u4EF6\uFF0C\u5982\u6709\u9700\u8981\u8BF7\u81EA\u884C\u4F20\u5165\uFF0C\u4F20\u5165\u5373\u4EE3\u8868\u5F00\u542F\u4E0A\u62A5\n ClsReporter: null // cls \u4E0A\u62A5\u7EC4\u4EF6\uFF0C\u5982\u6709\u9700\u8981\u8BF7\u81EA\u884C\u4F20\u5165\uFF0C\u4F20\u5165\u5373\u4EE3\u8868\u5F00\u542F\u4E0A\u62A5\n};\n\n// \u5BF9\u5916\u66B4\u9732\u7684\u7C7B\nvar COS = function COS(options) {\n this.options = util.extend(util.clone(defaultOptions), options || {});\n this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit);\n this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit);\n this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes);\n this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize);\n this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit);\n this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize);\n this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize);\n this.options.MaxPartNumber = Math.max(1024, Math.min(10000, this.options.MaxPartNumber));\n this.options.Timeout = Math.max(0, this.options.Timeout);\n this.options.EnableReporter = this.options.BeaconReporter || this.options.ClsReporter;\n if (this.options.AppId) {\n console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: \"test-1250000000\").');\n }\n if (this.options.SecretId && this.options.SecretId.indexOf(' ') > -1) {\n console.error('error: SecretId\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5');\n console.error('error: SecretId format is incorrect. Please check');\n }\n if (this.options.SecretKey && this.options.SecretKey.indexOf(' ') > -1) {\n console.error('error: SecretKey\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5');\n console.error('error: SecretKey format is incorrect. Please check');\n }\n if (util.isNode()) {\n console.log('Tip: Next.js\u3001Nuxt.js \u7B49\u670D\u52A1\u7AEF\u6E32\u67D3\u6280\u672F\u53EF\u6B63\u5E38\u4F7F\u7528JavaScript SDK\uFF0C\u8BF7\u5FFD\u7565\u4E0B\u65B9 nodejs \u73AF\u5883\u8B66\u544A');\n console.warn('warning: cos-js-sdk-v5 \u4E0D\u652F\u6301 nodejs \u73AF\u5883\u4F7F\u7528\uFF0C\u8BF7\u6539\u7528 cos-nodejs-sdk-v5\uFF0C\u53C2\u8003\u6587\u6863\uFF1A https://cloud.tencent.com/document/product/436/8629');\n console.warn('warning: cos-js-sdk-v5 does not support nodejs environment. Please use cos-nodejs-sdk-v5 instead. See: https://cloud.tencent.com/document/product/436/8629');\n }\n if (this.options.ForcePathStyle) {\n console.warn('cos-js-sdk-v5\u4E0D\u518D\u652F\u6301\u4F7F\u7528path-style\uFF0C\u4EC5\u652F\u6301\u4F7F\u7528virtual-hosted-style\uFF0C\u53C2\u8003\u6587\u6863\uFF1Ahttps://cloud.tencent.com/document/product/436/96243');\n throw new Error('ForcePathStyle is not supported');\n }\n event.init(this);\n task.init(this);\n};\nbase.init(COS, task);\nadvance.init(COS, task);\nCOS.util = {\n md5: util.md5,\n xml2json: util.xml2json,\n json2xml: util.json2xml,\n encodeBase64: util.encodeBase64\n};\nCOS.getAuthorization = util.getAuth;\nCOS.version = pkg.version;\nmodule.exports = COS;\n\n/***/ }),\n\n/***/ \"./src/event.js\":\n/*!**********************!*\\\n !*** ./src/event.js ***!\n \\**********************/\n/*! no static exports found */\n/***/ (function(module, exports) {\n\nvar initEvent = function initEvent(cos) {\n var listeners = {};\n var getList = function getList(action) {\n !listeners[action] && (listeners[action] = []);\n return listeners[action];\n };\n cos.on = function (action, callback) {\n if (action === 'task-list-update') {\n console.warn('warning: Event \"' + action + '\" has been deprecated. Please use \"list-update\" instead.');\n }\n getList(action).push(callback);\n };\n cos.off = function (action, callback) {\n var list = getList(action);\n for (var i = list.length - 1; i >= 0; i--) {\n callback === list[i] && list.splice(i, 1);\n }\n };\n cos.emit = function (action, data) {\n var list = getList(action).map(function (cb) {\n return cb;\n });\n for (var i = 0; i < list.length; i++) {\n list[i](data);\n }\n };\n};\nvar EventProxy = function EventProxy() {\n initEvent(this);\n};\nmodule.exports.init = initEvent;\nmodule.exports.EventProxy = EventProxy;\n\n/***/ }),\n\n/***/ \"./src/session.js\":\n/*!************************!*\\\n !*** ./src/session.js ***!\n \\************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar util = __webpack_require__(/*! ./util */ \"./src/util.js\");\n\n// \u6309\u7167\u6587\u4EF6\u7279\u5F81\u503C\uFF0C\u7F13\u5B58 UploadId\nvar cacheKey = 'cos_sdk_upload_cache';\nvar expires = 30 * 24 * 3600;\nvar cache;\nvar timer;\nvar getCache = function getCache() {\n try {\n var val = JSON.parse(localStorage.getItem(cacheKey));\n } catch (e) {}\n if (!val) val = [];\n cache = val;\n};\nvar setCache = function setCache() {\n try {\n if (cache.length) localStorage.setItem(cacheKey, JSON.stringify(cache));else localStorage.removeItem(cacheKey);\n } catch (e) {}\n};\nvar init = function init() {\n if (cache) return;\n getCache.call(this);\n // \u6E05\u7406\u592A\u8001\u65E7\u7684\u6570\u636E\n var changed = false;\n var now = Math.round(Date.now() / 1000);\n for (var i = cache.length - 1; i >= 0; i--) {\n var mtime = cache[i][2];\n if (!mtime || mtime + expires < now) {\n cache.splice(i, 1);\n changed = true;\n }\n }\n changed && setCache();\n};\n\n// \u628A\u7F13\u5B58\u5B58\u5230\u672C\u5730\nvar save = function save() {\n if (timer) return;\n timer = setTimeout(function () {\n setCache();\n timer = null;\n }, 400);\n};\nvar mod = {\n using: {},\n // \u6807\u8BB0 UploadId \u6B63\u5728\u4F7F\u7528\n setUsing: function setUsing(uuid) {\n mod.using[uuid] = true;\n },\n // \u6807\u8BB0 UploadId \u5DF2\u7ECF\u6CA1\u5728\u4F7F\u7528\n removeUsing: function removeUsing(uuid) {\n delete mod.using[uuid];\n },\n // \u7528\u4E0A\u4F20\u53C2\u6570\u751F\u6210\u54C8\u5E0C\u503C\n getFileId: function getFileId(file, ChunkSize, Bucket, Key) {\n if (file.name && file.size && file.lastModifiedDate && ChunkSize) {\n return util.md5([file.name, file.size, file.lastModifiedDate, ChunkSize, Bucket, Key].join('::'));\n } else {\n return null;\n }\n },\n // \u7528\u4E0A\u4F20\u53C2\u6570\u751F\u6210\u54C8\u5E0C\u503C\n getCopyFileId: function getCopyFileId(copySource, sourceHeaders, ChunkSize, Bucket, Key) {\n var size = sourceHeaders['content-length'];\n var etag = sourceHeaders.etag || '';\n var lastModified = sourceHeaders['last-modified'];\n if (copySource && ChunkSize) {\n return util.md5([copySource, size, etag, lastModified, ChunkSize, Bucket, Key].join('::'));\n } else {\n return null;\n }\n },\n // \u83B7\u53D6\u6587\u4EF6\u5BF9\u5E94\u7684 UploadId \u5217\u8868\n getUploadIdList: function getUploadIdList(uuid) {\n if (!uuid) return null;\n init.call(this);\n var list = [];\n for (var i = 0; i < cache.length; i++) {\n if (cache[i][0] === uuid) list.push(cache[i][1]);\n }\n return list.length ? list : null;\n },\n // \u7F13\u5B58 UploadId\n saveUploadId: function saveUploadId(uuid, UploadId, limit) {\n init.call(this);\n if (!uuid) return;\n // \u6E05\u7406\u6CA1\u7528\u7684 UploadId\uFF0Cjs \u6587\u4EF6\u6CA1\u6709 FilePath \uFF0C\u53EA\u6E05\u7406\u76F8\u540C\u8BB0\u5F55\n for (var i = cache.length - 1; i >= 0; i--) {\n var item = cache[i];\n if (item[0] === uuid && item[1] === UploadId) {\n cache.splice(i, 1);\n }\n }\n cache.unshift([uuid, UploadId, Math.round(Date.now() / 1000)]);\n if (cache.length > limit) cache.splice(limit);\n save();\n },\n // UploadId \u5DF2\u7528\u5B8C\uFF0C\u79FB\u9664\u6389\n removeUploadId: function removeUploadId(UploadId) {\n init.call(this);\n delete mod.using[UploadId];\n for (var i = cache.length - 1; i >= 0; i--) {\n if (cache[i][1] === UploadId) cache.splice(i, 1);\n }\n save();\n }\n};\nmodule.exports = mod;\n\n/***/ }),\n\n/***/ \"./src/task.js\":\n/*!*********************!*\\\n !*** ./src/task.js ***!\n \\*********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar session = __webpack_require__(/*! ./session */ \"./src/session.js\");\nvar util = __webpack_require__(/*! ./util */ \"./src/util.js\");\nvar originApiMap = {};\nvar transferToTaskMethod = function transferToTaskMethod(apiMap, apiName) {\n originApiMap[apiName] = apiMap[apiName];\n apiMap[apiName] = function (params, callback) {\n if (params.SkipTask) {\n originApiMap[apiName].call(this, params, callback);\n } else {\n this._addTask(apiName, params, callback);\n }\n };\n};\nvar initTask = function initTask(cos) {\n var queue = [];\n var tasks = {};\n var uploadingFileCount = 0;\n var nextUploadIndex = 0;\n\n // \u63A5\u53E3\u8FD4\u56DE\u7B80\u7565\u7684\u4EFB\u52A1\u4FE1\u606F\n var formatTask = function formatTask(task) {\n var t = {\n id: task.id,\n Bucket: task.Bucket,\n Region: task.Region,\n Key: task.Key,\n FilePath: task.FilePath,\n state: task.state,\n loaded: task.loaded,\n size: task.size,\n speed: task.speed,\n percent: task.percent,\n hashPercent: task.hashPercent,\n error: task.error\n };\n if (task.FilePath) t.FilePath = task.FilePath;\n if (task._custom) t._custom = task._custom; // \u63A7\u5236\u53F0\u4F7F\u7528\n return t;\n };\n var emitListUpdate = function () {\n var timer;\n var emit = function emit() {\n timer = 0;\n cos.emit('task-list-update', {\n list: util.map(queue, formatTask)\n });\n cos.emit('list-update', {\n list: util.map(queue, formatTask)\n });\n };\n return function () {\n if (!timer) timer = setTimeout(emit);\n };\n }();\n var clearQueue = function clearQueue() {\n if (queue.length <= cos.options.UploadQueueSize) return;\n for\n\n // \u5982\u679C\u8FD8\u592A\u591A\uFF0C\u624D\u7EE7\u7EED\u6E05\u7406\n (var i = 0; i < nextUploadIndex &&\n // \u5C0F\u4E8E\u5F53\u524D\u64CD\u4F5C\u7684 index \u624D\u6E05\u7406\n i < queue.length &&\n // \u5927\u4E8E\u961F\u5217\u624D\u6E05\u7406\n queue.length > cos.options.UploadQueueSize;) {\n var isActive = queue[i].state === 'waiting' || queue[i].state === 'checking' || queue[i].state === 'uploading';\n if (!queue[i] || !isActive) {\n tasks[queue[i].id] && delete tasks[queue[i].id];\n queue.splice(i, 1);\n nextUploadIndex--;\n } else {\n i++;\n }\n }\n emitListUpdate();\n };\n var startNextTask = function startNextTask() {\n // \u68C0\u67E5\u662F\u5426\u5141\u8BB8\u589E\u52A0\u6267\u884C\u8FDB\u7A0B\n if (uploadingFileCount >= cos.options.FileParallelLimit) return;\n // \u8DF3\u8FC7\u4E0D\u53EF\u6267\u884C\u7684\u4EFB\u52A1\n while (queue[nextUploadIndex] && queue[nextUploadIndex].state !== 'waiting') nextUploadIndex++;\n // \u68C0\u67E5\u662F\u5426\u5DF2\u904D\u5386\u7ED3\u675F\n if (nextUploadIndex >= queue.length) return;\n // \u4E0A\u4F20\u8BE5\u904D\u5386\u5230\u7684\u4EFB\u52A1\n var task = queue[nextUploadIndex];\n nextUploadIndex++;\n uploadingFileCount++;\n task.state = 'checking';\n task.params.onTaskStart && task.params.onTaskStart(formatTask(task));\n !task.params.UploadData && (task.params.UploadData = {});\n var apiParams = util.formatParams(task.api, task.params);\n originApiMap[task.api].call(cos, apiParams, function (err, data) {\n if (!cos._isRunningTask(task.id)) return;\n if (task.state === 'checking' || task.state === 'uploading') {\n task.state = err ? 'error' : 'success';\n err && (task.error = err);\n uploadingFileCount--;\n emitListUpdate();\n startNextTask();\n task.callback && task.callback(err, data);\n if (task.state === 'success') {\n if (task.params) {\n delete task.params.UploadData;\n delete task.params.Body;\n delete task.params;\n }\n delete task.callback;\n }\n }\n clearQueue();\n });\n emitListUpdate();\n // \u5F02\u6B65\u6267\u884C\u4E0B\u4E00\u4E2A\u4EFB\u52A1\n setTimeout(startNextTask);\n };\n var killTask = function killTask(id, switchToState) {\n var task = tasks[id];\n if (!task) return;\n var waiting = task && task.state === 'waiting';\n var running = task && (task.state === 'checking' || task.state === 'uploading');\n if (switchToState === 'canceled' && task.state !== 'canceled' || switchToState === 'paused' && waiting || switchToState === 'paused' && running) {\n task.state = switchToState;\n cos.emit('inner-kill-task', {\n TaskId: id,\n toState: switchToState\n });\n try {\n var UploadId = task && task.params && task.params.UploadData.UploadId;\n } catch (e) {}\n if (switchToState === 'canceled' && UploadId) session.removeUsing(UploadId);\n emitListUpdate();\n if (running) {\n uploadingFileCount--;\n startNextTask();\n }\n if (switchToState === 'canceled') {\n if (task.params) {\n delete task.params.UploadData;\n delete task.params.Body;\n delete task.params;\n }\n delete task.callback;\n }\n }\n clearQueue();\n };\n cos._addTasks = function (taskList) {\n util.each(taskList, function (task) {\n cos._addTask(task.api, task.params, task.callback, true);\n });\n emitListUpdate();\n };\n var isTaskReadyWarning = true;\n cos._addTask = function (api, params, callback, ignoreAddEvent) {\n // \u590D\u5236\u53C2\u6570\u5BF9\u8C61\n params = util.formatParams(api, params);\n\n // \u751F\u6210 id\n var id = util.uuid();\n params.TaskId = id;\n params.onTaskReady && params.onTaskReady(id);\n if (params.TaskReady) {\n params.TaskReady(id);\n isTaskReadyWarning && console.warn('warning: Param \"TaskReady\" has been deprecated. Please use \"onTaskReady\" instead.');\n isTaskReadyWarning = false;\n }\n var task = {\n // env\n params: params,\n callback: callback,\n api: api,\n index: queue.length,\n // task\n id: id,\n Bucket: params.Bucket,\n Region: params.Region,\n Key: params.Key,\n FilePath: params.FilePath || '',\n state: 'waiting',\n loaded: 0,\n size: 0,\n speed: 0,\n percent: 0,\n hashPercent: 0,\n error: null,\n _custom: params._custom\n };\n var onHashProgress = params.onHashProgress;\n params.onHashProgress = function (info) {\n if (!cos._isRunningTask(task.id)) return;\n task.hashPercent = info.percent;\n onHashProgress && onHashProgress(info);\n emitListUpdate();\n };\n var onProgress = params.onProgress;\n params.onProgress = function (info) {\n if (!cos._isRunningTask(task.id)) return;\n task.state === 'checking' && (task.state = 'uploading');\n task.loaded = info.loaded;\n task.speed = info.speed;\n task.percent = info.percent;\n onProgress && onProgress(info);\n emitListUpdate();\n };\n\n // \u5F02\u6B65\u83B7\u53D6 filesize\n util.getFileSize(api, params, function (err, size) {\n // \u5F00\u59CB\u5904\u7406\u4E0A\u4F20\n if (err) return callback(util.error(err)); // \u5982\u679C\u83B7\u53D6\u5927\u5C0F\u51FA\u9519\uFF0C\u4E0D\u52A0\u5165\u961F\u5217\n // \u83B7\u53D6\u5B8C\u6587\u4EF6\u5927\u5C0F\u518D\u628A\u4EFB\u52A1\u52A0\u5165\u961F\u5217\n tasks[id] = task;\n queue.push(task);\n task.size = size;\n !ignoreAddEvent && emitListUpdate();\n startNextTask();\n clearQueue();\n });\n return id;\n };\n cos._isRunningTask = function (id) {\n var task = tasks[id];\n return !!(task && (task.state === 'checking' || task.state === 'uploading'));\n };\n cos.getTaskList = function () {\n return util.map(queue, formatTask);\n };\n cos.cancelTask = function (id) {\n killTask(id, 'canceled');\n };\n cos.pauseTask = function (id) {\n killTask(id, 'paused');\n };\n cos.restartTask = function (id) {\n var task = tasks[id];\n if (task && (task.state === 'paused' || task.state === 'error')) {\n task.state = 'waiting';\n emitListUpdate();\n nextUploadIndex = Math.min(nextUploadIndex, task.index);\n startNextTask();\n }\n };\n cos.isUploadRunning = function () {\n return uploadingFileCount || nextUploadIndex < queue.length;\n };\n};\nmodule.exports.transferToTaskMethod = transferToTaskMethod;\nmodule.exports.init = initTask;\n\n/***/ }),\n\n/***/ \"./src/tracker.js\":\n/*!************************!*\\\n !*** ./src/tracker.js ***!\n \\************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar _classCallCheck = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ \"./node_modules/@babel/runtime/helpers/classCallCheck.js\");\nvar _createClass = __webpack_require__(/*! @babel/runtime/helpers/createClass */ \"./node_modules/@babel/runtime/helpers/createClass.js\");\nvar _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\nvar pkg = __webpack_require__(/*! ../package.json */ \"./package.json\");\nvar beacon = null;\nvar getBeacon = function getBeacon(Beacon, delay) {\n if (!beacon) {\n // \u751F\u6210 beacon\n if (typeof Beacon !== 'function') {\n throw new Error('Beacon not found');\n }\n beacon = new Beacon({\n appkey: '0WEB05PY6MHRGK0U',\n versionCode: pkg.version,\n channelID: 'js_sdk',\n //\u6E20\u9053,\u9009\u586B\n openid: 'openid',\n // \u7528\u6237id, \u9009\u586B\n unionid: 'unid',\n //\u7528\u6237unionid , \u7C7B\u4F3Cidfv,\u9009\u586B\n strictMode: false,\n //\u4E25\u82DB\u6A21\u5F0F\u5F00\u5173, \u6253\u5F00\u4E25\u82DB\u6A21\u5F0F\u4F1A\u4E3B\u52A8\u629B\u51FA\u5F02\u5E38, \u4E0A\u7EBF\u8BF7\u52A1\u5FC5\u5173\u95ED!!!\n delay: delay,\n // \u666E\u901A\u4E8B\u4EF6\u5EF6\u8FDF\u4E0A\u62A5\u65F6\u95F4(\u5355\u4F4D\u6BEB\u79D2), \u9ED8\u8BA41000(1\u79D2),\u9009\u586B\n sessionDuration: 60 * 1000 // session\u53D8\u66F4\u7684\u65F6\u95F4\u95F4\u9694, \u4E00\u4E2A\u7528\u6237\u6301\u7EED30\u5206\u949F(\u9ED8\u8BA4\u503C)\u6CA1\u6709\u4EFB\u4F55\u4E0A\u62A5\u5219\u7B97\u53E6\u4E00\u6B21 session,\u6BCF\u53D8\u66F4\u4E00\u6B21session\u4E0A\u62A5\u4E00\u6B21\u542F\u52A8\u4E8B\u4EF6(rqd_applaunched),\u4F7F\u7528\u6BEB\u79D2(ms),\u6700\u5C0F\u503C30\u79D2,\u9009\u586B\n });\n }\n return beacon;\n};\n\n// \u6BEB\u79D2\u8F6C\u79D2\nvar ms2s = function ms2s(ms) {\n if (!ms || ms < 0) return 0;\n return (ms / 1000).toFixed(3);\n};\nvar utils = {\n // \u751F\u6210uid \u6BCF\u4E2A\u94FE\u8DEF\u5BF9\u5E94\u552F\u4E00\u4E00\u6761uid\n getUid: function getUid() {\n var S4 = function S4() {\n return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);\n };\n return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();\n },\n // \u83B7\u53D6\u7F51\u7EDC\u7C7B\u578B 4g \uFF5C wifi\n getNetType: function getNetType() {\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) === 'object') {\n var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;\n return (connection === null || connection === void 0 ? void 0 : connection.type) || (connection === null || connection === void 0 ? void 0 : connection.effectiveType) || 'unknown';\n }\n return 'unknown';\n },\n // http | https\n getProtocol: function getProtocol() {\n if ((typeof location === \"undefined\" ? \"undefined\" : _typeof(location)) === 'object') {\n return location.protocol.replace(/:/, '');\n }\n return 'unknown protocol';\n },\n // \u83B7\u53D6pc\u7AEF\u64CD\u4F5C\u7CFB\u7EDF\u7C7B\u578B\n getOsType: function getOsType() {\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) !== 'object') {\n return 'unknown os';\n }\n var agent = navigator.userAgent.toLowerCase();\n var isMac = /macintosh|mac os x/i.test(navigator.userAgent);\n if (agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0) {\n return 'win32';\n }\n if (agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0) {\n return 'win64';\n }\n if (isMac) {\n return 'mac';\n }\n return 'unknown os';\n },\n isMobile: function isMobile() {\n var exp = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) === 'object' && navigator.userAgent.match(exp)) {\n return true; // \u79FB\u52A8\u7AEF\n }\n return false; // PC\u7AEF\n },\n isAndroid: function isAndroid() {\n var exp = /(Android|Adr|Linux)/i;\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) === 'object' && navigator.userAgent.match(exp)) {\n return true;\n }\n return false;\n },\n isIOS: function isIOS() {\n var exp = /(iPhone|iPod|iPad|iOS)/i;\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) === 'object' && navigator.userAgent.match(exp)) {\n return true;\n }\n return false;\n },\n isOtherMobile: function isOtherMobile() {\n return isMobile && !isAndroid && !isIOS;\n },\n getUA: function getUA() {\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) !== 'object') {\n return 'unknown device';\n }\n var explorer = navigator.userAgent;\n return explorer;\n }\n};\nvar isMobile = utils.isMobile();\nvar mobileOsType = utils.isAndroid() ? 'android' : utils.isIOS ? 'ios' : 'other_mobile';\nvar pcOsType = utils.getOsType();\nvar devicePlatform = isMobile ? mobileOsType : pcOsType;\nvar ua = utils.getUA();\nvar protocol = utils.getProtocol();\nvar transApiName = function transApiName(api) {\n if (['putObject', 'sliceUploadFile', 'uploadFile', 'uploadFiles'].includes(api)) {\n return 'UploadTask';\n } else if (api === 'getObject') {\n return 'DownloadTask';\n } else if (['putObjectCopy', 'sliceCopyFile'].includes(api)) {\n return 'CopyTask';\n }\n return api;\n};\n\n// \u4E0A\u62A5\u53C2\u6570\u9A7C\u5CF0\u6539\u4E0B\u5212\u7EBF\nfunction camel2underline(key) {\n return key.replace(/([A-Z])/g, '_$1').toLowerCase();\n}\nfunction formatParams(params) {\n var formattedParams = {};\n var successKeys = ['sdkVersionName', 'sdkVersionCode', 'osName', 'networkType', 'requestName', 'requestResult', 'bucket', 'region', 'appid', 'accelerate', 'url', 'host', 'requestPath', 'userAgent', 'networkProtocol', 'httpMethod', 'httpSize', 'httpSpeed', 'httpTookTime', 'httpMd5', 'httpSign', 'httpFullTime', 'httpDomain', 'partNumber', 'httpRetryTimes', 'customId', 'traceId', 'realApi'];\n var failureKeys = [].concat(successKeys, ['errorNode', 'errorCode', 'errorName', 'errorMessage', 'errorRequestId', 'errorHttpCode', 'errorServiceName', 'errorType', 'fullError']);\n // \u9700\u8981\u4E0A\u62A5\u7684\u53C2\u6570\u5B57\u6BB5\n var reporterKeys = params.requestResult === 'Success' ? successKeys : failureKeys;\n for (var key in params) {\n if (!reporterKeys.includes(key)) continue;\n var formattedKey = camel2underline(key);\n formattedParams[formattedKey] = params[key];\n }\n formattedParams['request_name'] = params.realApi ? transApiName(params.realApi) : params.requestName;\n return formattedParams;\n}\n\n// \u94FE\u8DEF\u8FFD\u8E2A\u5668\nvar Tracker = /*#__PURE__*/function () {\n \"use strict\";\n\n function Tracker(opt) {\n _classCallCheck(this, Tracker);\n var parent = opt.parent,\n traceId = opt.traceId,\n bucket = opt.bucket,\n region = opt.region,\n apiName = opt.apiName,\n realApi = opt.realApi,\n httpMethod = opt.httpMethod,\n fileKey = opt.fileKey,\n fileSize = opt.fileSize,\n accelerate = opt.accelerate,\n customId = opt.customId,\n delay = opt.delay,\n deepTracker = opt.deepTracker,\n Beacon = opt.Beacon,\n clsReporter = opt.clsReporter;\n var appid = bucket && bucket.substr(bucket.lastIndexOf('-') + 1) || '';\n this.parent = parent;\n this.deepTracker = deepTracker;\n this.delay = delay;\n if (clsReporter && !this.clsReporter) {\n this.clsReporter = clsReporter;\n }\n // \u4E0A\u62A5\u7528\u5230\u7684\u5B57\u6BB5\n this.params = {\n // \u901A\u7528\u5B57\u6BB5\n sdkVersionName: 'cos-js-sdk-v5',\n sdkVersionCode: pkg.version,\n osName: devicePlatform,\n networkType: '',\n requestName: apiName || '',\n requestResult: '',\n // sdk api\u8C03\u7528\u7ED3\u679CSuccess\u3001Failure\n realApi: realApi,\n bucket: bucket,\n region: region,\n accelerate: accelerate,\n httpMethod: httpMethod,\n url: '',\n // \u8BF7\u6C42url\n host: '',\n httpDomain: '',\n requestPath: fileKey || '',\n userAgent: ua,\n networkProtocol: protocol,\n errorType: '',\n errorCode: '',\n errorName: '',\n errorMessage: '',\n errorRequestId: '',\n errorHttpCode: 0,\n errorServiceName: '',\n errorNode: '',\n httpTookTime: 0,\n // http\u6574\u4F53\u8017\u65F6\n httpSize: fileSize || 0,\n // \u4E3B\u8981\u662F\u6587\u4EF6\u5927\u5C0F\uFF0C\u5927\u5C0F B\n httpMd5: 0,\n // MD5\u8017\u65F6\n httpSign: 0,\n // \u8BA1\u7B97\u7B7E\u540D\u8017\u65F6\n httpFullTime: 0,\n // \u4EFB\u52A1\u6574\u4F53\u8017\u65F6(\u5305\u62ECmd5\u3001\u7B7E\u540D\u7B49)\n httpSpeed: 0,\n // \u4E3B\u8981\u5173\u6CE8\u4E0A\u4F20\u901F\u5EA6\uFF0CKB/s\n\n md5StartTime: 0,\n // md5\u8BA1\u7B97\u5F00\u59CB\u65F6\u95F4\n md5EndTime: 0,\n // md5\u8BA1\u7B97\u7ED3\u675F\u65F6\u95F4\n signStartTime: 0,\n // \u8BA1\u7B97\u7B7E\u540D\u5F00\u59CB\u65F6\u95F4\n signEndTime: 0,\n // \u8BA1\u7B97\u7B7E\u540D\u7ED3\u675F\u65F6\u95F4\n httpStartTime: 0,\n // \u53D1\u8D77\u7F51\u7EDC\u8BF7\u6C42\u5F00\u59CB\u65F6\u95F4\n httpEndTime: 0,\n // \u7F51\u8DEF\u8BF7\u6C42\u7ED3\u675F\u65F6\u95F4\n startTime: new Date().getTime(),\n // sdk api\u8C03\u7528\u8D77\u59CB\u65F6\u95F4\uFF0C\u4E0D\u662F\u7EAF\u7F51\u7EDC\u8017\u65F6\n endTime: 0,\n // sdk api\u8C03\u7528\u7ED3\u675F\u65F6\u95F4\uFF0C\u4E0D\u662F\u7EAF\u7F51\u7EDC\u8017\u65F6\n\n // js\u8865\u5145\u5B57\u6BB5\n traceId: traceId || utils.getUid(),\n // \u6BCF\u6761\u4E0A\u62A5\u552F\u4E00\u6807\u8BC6\n appid: appid,\n partNumber: 0,\n // \u5206\u5757\u4E0A\u4F20\u7F16\u53F7\n httpRetryTimes: 0,\n // sdk\u5185\u90E8\u53D1\u8D77\u7684\u8BF7\u6C42\u91CD\u8BD5\n customId: customId || '',\n // \u4E1A\u52A1id\n partTime: 0\n };\n if (Beacon) {\n this.beacon = getBeacon(Beacon, delay);\n }\n }\n\n // \u683C\u5F0F\u5316sdk\u56DE\u8C03\n _createClass(Tracker, [{\n key: \"formatResult\",\n value: function formatResult(err, data) {\n var _err$error, _err$error2, _err$error3, _err$error4, _err$error5, _err$error6;\n var now = new Date().getTime();\n var networkType = utils.getNetType();\n var errorCode = err ? (err === null || err === void 0 ? void 0 : err.code) || (err === null || err === void 0 ? void 0 : (_err$error = err.error) === null || _err$error === void 0 ? void 0 : _err$error.code) || (err === null || err === void 0 ? void 0 : (_err$error2 = err.error) === null || _err$error2 === void 0 ? void 0 : _err$error2.Code) : '';\n var errorMessage = err ? (err === null || err === void 0 ? void 0 : err.message) || (err === null || err === void 0 ? void 0 : (_err$error3 = err.error) === null || _err$error3 === void 0 ? void 0 : _err$error3.message) || (err === null || err === void 0 ? void 0 : (_err$error4 = err.error) === null || _err$error4 === void 0 ? void 0 : _err$error4.Message) : '';\n var errorName = errorMessage;\n var errorServiceName = err ? (err === null || err === void 0 ? void 0 : err.resource) || (err === null || err === void 0 ? void 0 : (_err$error5 = err.error) === null || _err$error5 === void 0 ? void 0 : _err$error5.resource) || (err === null || err === void 0 ? void 0 : (_err$error6 = err.error) === null || _err$error6 === void 0 ? void 0 : _err$error6.Resource) : '';\n var errorHttpCode = err ? err === null || err === void 0 ? void 0 : err.statusCode : data.statusCode;\n var requestId = err ? (err === null || err === void 0 ? void 0 : err.headers) && (err === null || err === void 0 ? void 0 : err.headers['x-cos-request-id']) : (data === null || data === void 0 ? void 0 : data.headers) && (data === null || data === void 0 ? void 0 : data.headers['x-cos-request-id']);\n var errorType = err ? requestId ? 'Server' : 'Client' : '';\n if (this.params.requestName === 'getObject') {\n this.params.httpSize = data ? data.headers && data.headers['content-length'] : 0;\n }\n\n // \u4E0A\u62A5 sliceUploadFile || uploadFile || uploadFiles \u547D\u4E2D\u5206\u5757\u4E0A\u4F20\u65F6\n var isSliceUploadFile = this.params.realApi === 'sliceUploadFile';\n var isSliceCopyFile = this.params.realApi === 'sliceCopyFile';\n if (isSliceUploadFile || isSliceCopyFile) {\n var speed = this.params.httpSize / 1024 / this.params.partTime;\n Object.assign(this.params, {\n httpSpeed: speed < 0 ? 0 : speed.toFixed(3)\n });\n } else {\n var httpFullTime = now - this.params.startTime;\n var httpTookTime = this.params.httpEndTime - this.params.httpStartTime;\n var _speed = this.params.httpSize / 1024 / (httpTookTime / 1000);\n var httpMd5 = this.params.md5EndTime - this.params.md5StartTime;\n var httpSign = this.params.signEndTime - this.params.signStartTime;\n if (this.parent) {\n this.parent.addParamValue('httpTookTime', ms2s(httpTookTime));\n this.parent.addParamValue('httpFullTime', ms2s(httpFullTime));\n this.parent.addParamValue('httpMd5', ms2s(httpMd5));\n this.parent.addParamValue('httpSign', ms2s(httpSign));\n if (['multipartUpload', 'uploadPartCopy', 'putObjectCopy'].includes(this.params.requestName)) {\n // \u53EA\u6709\u5C0F\u5206\u5757\u4E0A\u4F20|\u590D\u5236\u624D\u7D2F\u8BA1\u7EAF\u8BF7\u6C42\u8017\u65F6\uFF0C\u8BA1\u7B97\u901F\u5EA6\u65F6\u7528\u5230\n this.parent.addParamValue('partTime', ms2s(httpTookTime));\n }\n }\n Object.assign(this.params, {\n httpFullTime: ms2s(httpFullTime),\n httpMd5: ms2s(httpMd5),\n httpSign: ms2s(httpSign),\n httpTookTime: ms2s(httpTookTime),\n httpSpeed: _speed < 0 ? 0 : _speed.toFixed(3)\n });\n }\n Object.assign(this.params, {\n networkType: networkType,\n requestResult: err ? 'Failure' : 'Success',\n errorType: errorType,\n errorCode: errorCode,\n errorHttpCode: errorHttpCode,\n errorName: errorName,\n errorMessage: errorMessage,\n errorServiceName: errorServiceName,\n errorRequestId: requestId\n });\n if (err && (!errorCode || !errorMessage)) {\n // \u6682\u5B58\u5168\u91CFerr\u4E00\u6BB5\u65F6\u95F4 \u89C2\u5BDF\u662F\u5426\u6240\u6709err\u683C\u5F0F\u90FD\u53EF\u88AB\u89E3\u6790\n this.params.fullError = err ? JSON.stringify(err) : '';\n }\n if (this.params.url) {\n try {\n var execRes = /^http(s)?:\\/\\/(.*?)\\//.exec(this.params.url);\n this.params.host = execRes[2];\n } catch (e) {\n this.params.host = this.params.url;\n }\n this.params.httpDomain = this.params.host;\n }\n }\n\n // \u4E0A\u62A5\n }, {\n key: \"report\",\n value: function report(err, data) {\n if (!this.beacon && !this.clsReporter) return;\n this.formatResult(err, data);\n var formattedParams = formatParams(this.params);\n if (this.beacon) {\n this.sendEventsToBeacon(formattedParams);\n }\n if (this.clsReporter) {\n this.sendEventsToCLS(formattedParams);\n }\n }\n\n // \u8BBE\u7F6E\u5F53\u524D\u94FE\u8DEF\u7684\u53C2\u6570\n }, {\n key: \"setParams\",\n value: function setParams(params) {\n Object.assign(this.params, params);\n }\n }, {\n key: \"addParamValue\",\n value: function addParamValue(key, value) {\n this.params[key] = (+this.params[key] + +value).toFixed(3);\n }\n\n // \u4E0A\u62A5\u706F\u5854\n }, {\n key: \"sendEventsToBeacon\",\n value: function sendEventsToBeacon(formattedParams) {\n // DeepTracker\u6A21\u5F0F\u4E0B\u624D\u4F1A\u4E0A\u62A5\u5206\u5757\u4E0A\u4F20\u5185\u90E8\u7EC6\u8282\n var isSliceUploadFile = this.params.requestName === 'sliceUploadFile' || this.params.realApi === 'sliceUploadFile';\n if (isSliceUploadFile && !this.deepTracker) {\n return;\n }\n var eventCode = 'qcloud_track_cos_sdk';\n if (this.delay === 0) {\n // \u5B9E\u65F6\u4E0A\u62A5\n this.beacon && this.beacon.onDirectUserAction(eventCode, formattedParams);\n } else {\n // \u5468\u671F\u6027\u4E0A\u62A5\n this.beacon && this.beacon.onUserAction(eventCode, formattedParams);\n }\n }\n\n // \u4E0A\u62A5 cls\n }, {\n key: \"sendEventsToCLS\",\n value: function sendEventsToCLS(formattedParams) {\n // \u662F\u5426\u5B9E\u65F6\u4E0A\u62A5\n var immediate = !!(this.delay === 0);\n this.clsReporter.log(formattedParams, immediate);\n }\n\n // \u751F\u6210\u5B50\u5B9E\u4F8B\uFF0C\u4E0E\u7236\u6240\u5C5E\u4E00\u4E2A\u94FE\u8DEF\uFF0C\u53EF\u7528\u4E8E\u5206\u5757\u4E0A\u4F20\u5185\u90E8\u6D41\u7A0B\u4E0A\u62A5\u5355\u4E2A\u5206\u5757\u64CD\u4F5C\n }, {\n key: \"generateSubTracker\",\n value: function generateSubTracker(subParams) {\n Object.assign(subParams, {\n parent: this,\n deepTracker: this.deepTracker,\n traceId: this.params.traceId,\n bucket: this.params.bucket,\n region: this.params.region,\n accelerate: this.params.accelerate,\n fileKey: this.params.requestPath,\n customId: this.params.customId,\n delay: this.delay,\n clsReporter: this.clsReporter\n });\n return new Tracker(subParams);\n }\n }]);\n return Tracker;\n}();\nmodule.exports = Tracker;\n\n/***/ }),\n\n/***/ \"./src/util.js\":\n/*!*********************!*\\\n !*** ./src/util.js ***!\n \\*********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n\nvar _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ \"./node_modules/@babel/runtime/helpers/typeof.js\");\nfunction _createForOfIteratorHelper(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && \"number\" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar md5 = __webpack_require__(/*! ../lib/md5 */ \"./lib/md5.js\");\nvar CryptoJS = __webpack_require__(/*! ../lib/crypto */ \"./lib/crypto.js\");\nvar _require = __webpack_require__(/*! fast-xml-parser */ \"./node_modules/fast-xml-parser/src/fxp.js\"),\n XMLParser = _require.XMLParser,\n XMLBuilder = _require.XMLBuilder;\nvar xmlParser = new XMLParser({\n ignoreDeclaration: true,\n // \u5FFD\u7565 XML \u58F0\u660E\n ignoreAttributes: true,\n // \u5FFD\u7565\u5C5E\u6027\n parseTagValue: false // \u5173\u95ED\u81EA\u52A8\u89E3\u6790\n});\nvar xmlBuilder = new XMLBuilder();\nvar base64 = __webpack_require__(/*! ../lib/base64 */ \"./lib/base64.js\");\nvar Tracker = __webpack_require__(/*! ./tracker */ \"./src/tracker.js\");\n\n// XML \u5BF9\u8C61\u8F6C JSON \u5BF9\u8C61\nvar xml2json = function xml2json(bodyStr) {\n var d = xmlParser.parse(bodyStr);\n return d;\n};\n\n// JSON \u5BF9\u8C61\u8F6C XML \u5BF9\u8C61\nvar json2xml = function json2xml(json) {\n var xml = xmlBuilder.build(json);\n return xml;\n};\nfunction camSafeUrlEncode(str) {\n return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');\n}\nfunction getObjectKeys(obj, forKey) {\n var list = [];\n for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);\n }\n }\n return list.sort(function (a, b) {\n a = a.toLowerCase();\n b = b.toLowerCase();\n return a === b ? 0 : a > b ? 1 : -1;\n });\n}\n\n/**\n * obj\u8F6C\u4E3Astring\n * @param {Object} obj \u9700\u8981\u8F6C\u7684\u5BF9\u8C61\uFF0C\u5FC5\u987B\n * @param {Boolean} lowerCaseKey key\u662F\u5426\u8F6C\u4E3A\u5C0F\u5199\uFF0C\u9ED8\u8BA4false\uFF0C\u975E\u5FC5\u987B\n * @return {String} data \u8FD4\u56DE\u5B57\u7B26\u4E32\n */\nvar obj2str = function obj2str(obj, lowerCaseKey) {\n var i, key, val;\n var list = [];\n var keyList = getObjectKeys(obj);\n for (i = 0; i < keyList.length; i++) {\n key = keyList[i];\n val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];\n key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);\n val = camSafeUrlEncode(val) || '';\n list.push(key + '=' + val);\n }\n return list.join('&');\n};\n\n// \u53EF\u4EE5\u7B7E\u5165\u7B7E\u540D\u7684headers\nvar signHeaders = ['cache-control', 'content-disposition', 'content-encoding', 'content-length', 'content-md5', 'expect', 'expires', 'host', 'if-match', 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'origin', 'range', 'transfer-encoding', 'pic-operations'];\nvar getSignHeaderObj = function getSignHeaderObj(headers) {\n var signHeaderObj = {};\n for (var i in headers) {\n var key = i.toLowerCase();\n if (key.indexOf('x-cos-') > -1 || signHeaders.indexOf(key) > -1) {\n signHeaderObj[i] = headers[i];\n }\n }\n return signHeaderObj;\n};\n\n//\u6D4B\u8BD5\u7528\u7684key\u540E\u9762\u53EF\u4EE5\u53BB\u6389\nvar getAuth = function getAuth(opt) {\n opt = opt || {};\n var SecretId = opt.SecretId;\n var SecretKey = opt.SecretKey;\n var KeyTime = opt.KeyTime;\n var method = (opt.method || opt.Method || 'get').toLowerCase();\n var queryParams = clone(opt.Query || opt.params || {});\n var headers = getSignHeaderObj(clone(opt.Headers || opt.headers || {}));\n var Key = opt.Key || '';\n var pathname;\n if (opt.UseRawKey) {\n pathname = opt.Pathname || opt.pathname || '/' + Key;\n } else {\n pathname = opt.Pathname || opt.pathname || Key;\n pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);\n }\n\n // ForceSignHost\u660E\u786E\u4F20\u5165false\u624D\u4E0D\u52A0\u5165host\u7B7E\u540D\n var forceSignHost = opt.ForceSignHost === false ? false : true;\n\n // \u5982\u679C\u6709\u4F20\u5165\u5B58\u50A8\u6876\u4E14\u9700\u8981\u5F3A\u5236\u7B7E\u540D\uFF0C\u90A3\u4E48\u7B7E\u540D\u9ED8\u8BA4\u52A0 Host \u53C2\u4E0E\u8BA1\u7B97\uFF0C\u907F\u514D\u8DE8\u6876\u8BBF\u95EE\n if (!headers.Host && !headers.host && opt.Bucket && opt.Region && forceSignHost) headers.Host = opt.Bucket + '.cos.' + opt.Region + '.myqcloud.com';\n if (!SecretId) throw new Error('missing param SecretId');\n if (!SecretKey) throw new Error('missing param SecretKey');\n\n // \u7B7E\u540D\u6709\u6548\u8D77\u6B62\u65F6\u95F4\n var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;\n var exp = now;\n var Expires = opt.Expires || opt.expires;\n if (Expires === undefined) {\n exp += 900; // \u7B7E\u540D\u8FC7\u671F\u65F6\u95F4\u4E3A\u5F53\u524D + 900s\n } else {\n exp += Expires * 1 || 0;\n }\n\n // \u8981\u7528\u5230\u7684 Authorization \u53C2\u6570\u5217\u8868\n var qSignAlgorithm = 'sha1';\n var qAk = SecretId;\n var qSignTime = KeyTime || now + ';' + exp;\n var qKeyTime = KeyTime || now + ';' + exp;\n var qHeaderList = getObjectKeys(headers, true).join(';').toLowerCase();\n var qUrlParamList = getObjectKeys(queryParams, true).join(';').toLowerCase();\n\n // \u7B7E\u540D\u7B97\u6CD5\u8BF4\u660E\u6587\u6863\uFF1Ahttps://www.qcloud.com/document/product/436/7778\n // \u6B65\u9AA4\u4E00\uFF1A\u8BA1\u7B97 SignKey\n var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();\n\n // \u6B65\u9AA4\u4E8C\uFF1A\u6784\u6210 FormatString\n var formatString = [method, pathname, util.obj2str(queryParams, true), util.obj2str(headers, true), ''].join('\\n');\n\n // \u6B65\u9AA4\u4E09\uFF1A\u8BA1\u7B97 StringToSign\n var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\\n');\n\n // \u6B65\u9AA4\u56DB\uFF1A\u8BA1\u7B97 Signature\n var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();\n\n // \u6B65\u9AA4\u4E94\uFF1A\u6784\u9020 Authorization\n var authorization = ['q-sign-algorithm=' + qSignAlgorithm, 'q-ak=' + qAk, 'q-sign-time=' + qSignTime, 'q-key-time=' + qKeyTime, 'q-header-list=' + qHeaderList, 'q-url-param-list=' + qUrlParamList, 'q-signature=' + qSignature].join('&');\n return authorization;\n};\nvar readIntBE = function readIntBE(chunk, size, offset) {\n var bytes = size / 8;\n var buf = chunk.slice(offset, offset + bytes);\n new Uint8Array(buf).reverse();\n return new {\n 8: Uint8Array,\n 16: Uint16Array,\n 32: Uint32Array\n }[size](buf)[0];\n};\nvar buf2str = function buf2str(chunk, start, end, isUtf8) {\n var buf = chunk.slice(start, end);\n var str = '';\n new Uint8Array(buf).forEach(function (charCode) {\n str += String.fromCharCode(charCode);\n });\n if (isUtf8) str = decodeURIComponent(escape(str));\n return str;\n};\nvar parseSelectPayload = function parseSelectPayload(chunk) {\n var header = {};\n var body = buf2str(chunk);\n var result = {\n records: []\n };\n while (chunk.byteLength) {\n var totalLength = readIntBE(chunk, 32, 0);\n var headerLength = readIntBE(chunk, 32, 4);\n var payloadRestLength = totalLength - headerLength - 16;\n var offset = 0;\n var content;\n chunk = chunk.slice(12);\n // \u83B7\u53D6 Message \u7684 header \u4FE1\u606F\n while (offset < headerLength) {\n var headerNameLength = readIntBE(chunk, 8, offset);\n var headerName = buf2str(chunk, offset + 1, offset + 1 + headerNameLength);\n var headerValueLength = readIntBE(chunk, 16, offset + headerNameLength + 2);\n var headerValue = buf2str(chunk, offset + headerNameLength + 4, offset + headerNameLength + 4 + headerValueLength);\n header[headerName] = headerValue;\n offset += headerNameLength + 4 + headerValueLength;\n }\n if (header[':event-type'] === 'Records') {\n content = buf2str(chunk, offset, offset + payloadRestLength, true);\n result.records.push(content);\n } else if (header[':event-type'] === 'Stats') {\n content = buf2str(chunk, offset, offset + payloadRestLength, true);\n result.stats = util.xml2json(content).Stats;\n } else if (header[':event-type'] === 'error') {\n var errCode = header[':error-code'];\n var errMessage = header[':error-message'];\n var err = new Error(errMessage);\n err.message = errMessage;\n err.name = err.code = errCode;\n result.error = err;\n } else if (['Progress', 'Continuation', 'End'].includes(header[':event-type'])) {\n // do nothing\n }\n chunk = chunk.slice(offset + payloadRestLength + 4);\n }\n return {\n payload: result.records.join(''),\n body: body\n };\n};\nvar getSourceParams = function getSourceParams(source) {\n var parser = this.options.CopySourceParser;\n if (parser) return parser(source);\n var m = source.match(/^([^.]+-\\d+)\\.cos(v6|-cdc|-cdz|-internal)?\\.([^.]+)\\.((myqcloud\\.com)|(tencentcos\\.cn))\\/(.+)$/);\n if (!m) return null;\n return {\n Bucket: m[1],\n Region: m[3],\n Key: m[7]\n };\n};\nvar noop = function noop() {};\n\n// \u6E05\u9664\u5BF9\u8C61\u91CC\u503C\u4E3A\u7684 undefined \u6216 null \u7684\u5C5E\u6027\nvar clearKey = function clearKey(obj) {\n var retObj = {};\n for (var key in obj) {\n if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {\n retObj[key] = obj[key];\n }\n }\n return retObj;\n};\nvar readAsBinaryString = function readAsBinaryString(blob, callback) {\n var readFun;\n var fr = new FileReader();\n if (FileReader.prototype.readAsBinaryString) {\n readFun = FileReader.prototype.readAsBinaryString;\n fr.onload = function () {\n callback(this.result);\n };\n } else if (FileReader.prototype.readAsArrayBuffer) {\n // \u5728 ie11 \u6DFB\u52A0 readAsBinaryString \u517C\u5BB9\n readFun = function readFun(fileData) {\n var binary = '';\n var pt = this;\n var reader = new FileReader();\n reader.onload = function (e) {\n var bytes = new Uint8Array(reader.result);\n var length = bytes.byteLength;\n for (var i = 0; i < length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n callback(binary);\n };\n reader.readAsArrayBuffer(fileData);\n };\n } else {\n console.error('FileReader not support readAsBinaryString');\n }\n readFun.call(fr, blob);\n};\nvar fileSliceNeedCopy = function () {\n var compareVersion = function compareVersion(a, b) {\n a = a.split('.');\n b = b.split('.');\n for (var i = 0; i < b.length; i++) {\n if (a[i] !== b[i]) {\n return parseInt(a[i]) > parseInt(b[i]) ? 1 : -1;\n }\n }\n return 0;\n };\n var check = function check(ua) {\n if (!ua) return false;\n var ChromeVersion = (ua.match(/Chrome\\/([.\\d]+)/) || [])[1];\n var QBCoreVersion = (ua.match(/QBCore\\/([.\\d]+)/) || [])[1];\n var QQBrowserVersion = (ua.match(/QQBrowser\\/([.\\d]+)/) || [])[1];\n var need = ChromeVersion && compareVersion(ChromeVersion, '53.0.2785.116') < 0 && QBCoreVersion && compareVersion(QBCoreVersion, '3.53.991.400') < 0 && QQBrowserVersion && compareVersion(QQBrowserVersion, '9.0.2524.400') <= 0 || false;\n return need;\n };\n return check(typeof navigator !== 'undefined' && navigator.userAgent);\n}();\n\n// \u83B7\u53D6\u6587\u4EF6\u5206\u7247\nvar fileSlice = function fileSlice(file, start, end, isUseToUpload, callback) {\n var blob;\n if (file.slice) {\n blob = file.slice(start, end);\n } else if (file.mozSlice) {\n blob = file.mozSlice(start, end);\n } else if (file.webkitSlice) {\n blob = file.webkitSlice(start, end);\n }\n if (isUseToUpload && fileSliceNeedCopy) {\n var reader = new FileReader();\n reader.onload = function (e) {\n blob = null;\n callback(new Blob([reader.result]));\n };\n reader.readAsArrayBuffer(blob);\n } else {\n callback(blob);\n }\n};\n\n// \u83B7\u53D6\u6587\u4EF6\u5185\u5BB9\u7684 MD5\nvar getBodyMd5 = function getBodyMd5(UploadCheckContentMd5, Body, callback, onProgress) {\n callback = callback || noop;\n if (UploadCheckContentMd5) {\n if (typeof Body === 'string') {\n callback(util.md5(Body, true));\n } else if (Blob && Body instanceof Blob) {\n util.getFileMd5(Body, function (err, md5) {\n callback(md5);\n }, onProgress);\n } else {\n callback();\n }\n } else {\n callback();\n }\n};\n\n// \u83B7\u53D6\u6587\u4EF6 md5 \u503C\nvar md5ChunkSize = 1024 * 1024;\nvar getFileMd5 = function getFileMd5(blob, callback, onProgress) {\n var size = blob.size;\n var loaded = 0;\n var md5ctx = md5.getCtx();\n var next = function next(start) {\n if (start >= size) {\n var hash = md5ctx.digest('hex');\n callback(null, hash);\n return;\n }\n var end = Math.min(size, start + md5ChunkSize);\n util.fileSlice(blob, start, end, false, function (chunk) {\n readAsBinaryString(chunk, function (content) {\n chunk = null;\n md5ctx = md5ctx.update(content, true);\n loaded += content.length;\n content = null;\n if (onProgress) onProgress({\n loaded: loaded,\n total: size,\n percent: Math.round(loaded / size * 10000) / 10000\n });\n next(start + md5ChunkSize);\n });\n });\n };\n next(0);\n};\nfunction clone(obj) {\n return map(obj, function (v) {\n return _typeof(v) === 'object' && v !== null ? clone(v) : v;\n });\n}\nfunction attr(obj, name, defaultValue) {\n return obj && name in obj ? obj[name] : defaultValue;\n}\nfunction extend(target, source) {\n each(source, function (val, key) {\n target[key] = source[key];\n });\n return target;\n}\nfunction isArray(arr) {\n return arr instanceof Array;\n}\nfunction isInArray(arr, item) {\n var flag = false;\n for (var i = 0; i < arr.length; i++) {\n if (item === arr[i]) {\n flag = true;\n break;\n }\n }\n return flag;\n}\nfunction makeArray(arr) {\n return isArray(arr) ? arr : [arr];\n}\nfunction each(obj, fn) {\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n fn(obj[i], i);\n }\n }\n}\nfunction map(obj, fn) {\n var o = isArray(obj) ? [] : {};\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n o[i] = fn(obj[i], i);\n }\n }\n return o;\n}\nfunction filter(obj, fn) {\n var iaArr = isArray(obj);\n var o = iaArr ? [] : {};\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (fn(obj[i], i)) {\n if (iaArr) {\n o.push(obj[i]);\n } else {\n o[i] = obj[i];\n }\n }\n }\n }\n return o;\n}\nvar b64 = function b64(str) {\n var i,\n len,\n char,\n res = '';\n for (i = 0, len = str.length / 2; i < len; i++) {\n char = parseInt(str[i * 2] + str[i * 2 + 1], 16);\n res += String.fromCharCode(char);\n }\n return btoa(res);\n};\nvar uuid = function uuid() {\n var S4 = function S4() {\n return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);\n };\n return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();\n};\nvar hasMissingParams = function hasMissingParams(apiName, params) {\n var Bucket = params.Bucket;\n var Region = params.Region;\n var Key = params.Key;\n var Domain = this.options.Domain;\n var checkBucket = !Domain || typeof Domain === 'string' && Domain.indexOf('{Bucket}') > -1;\n var checkRegion = !Domain || typeof Domain === 'string' && Domain.indexOf('{Region}') > -1;\n if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {\n if (checkBucket && !Bucket) return 'Bucket';\n if (checkRegion && !Region) return 'Region';\n } else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask' || apiName === 'uploadFile') {\n if (checkBucket && !Bucket) return 'Bucket';\n if (checkRegion && !Region) return 'Region';\n if (!Key) return 'Key';\n }\n return false;\n};\nvar formatParams = function formatParams(apiName, params) {\n // \u590D\u5236\u53C2\u6570\u5BF9\u8C61\n params = extend({}, params);\n\n // \u7EDF\u4E00\u5904\u7406 Headers\n if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {\n var Headers = params.Headers || {};\n if (params && _typeof(params) === 'object') {\n (function () {\n for (var key in params) {\n if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {\n Headers[key] = params[key];\n }\n }\n })();\n var headerMap = {\n // params headers\n 'x-cos-mfa': 'MFA',\n 'Content-MD5': 'ContentMD5',\n 'Content-Length': 'ContentLength',\n 'Content-Type': 'ContentType',\n Expect: 'Expect',\n Expires: 'Expires',\n 'Cache-Control': 'CacheControl',\n 'Content-Disposition': 'ContentDisposition',\n 'Content-Encoding': 'ContentEncoding',\n Range: 'Range',\n 'If-Modified-Since': 'IfModifiedSince',\n 'If-Unmodified-Since': 'IfUnmodifiedSince',\n 'If-Match': 'IfMatch',\n 'If-None-Match': 'IfNoneMatch',\n 'x-cos-copy-source': 'CopySource',\n 'x-cos-copy-source-Range': 'CopySourceRange',\n 'x-cos-metadata-directive': 'MetadataDirective',\n 'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',\n 'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',\n 'x-cos-copy-source-If-Match': 'CopySourceIfMatch',\n 'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',\n 'x-cos-acl': 'ACL',\n 'x-cos-grant-read': 'GrantRead',\n 'x-cos-grant-write': 'GrantWrite',\n 'x-cos-grant-full-control': 'GrantFullControl',\n 'x-cos-grant-read-acp': 'GrantReadAcp',\n 'x-cos-grant-write-acp': 'GrantWriteAcp',\n 'x-cos-storage-class': 'StorageClass',\n 'x-cos-traffic-limit': 'TrafficLimit',\n 'x-cos-mime-limit': 'MimeLimit',\n // SSE-C\n 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',\n 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',\n 'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',\n // SSE-COS\u3001SSE-KMS\n 'x-cos-server-side-encryption': 'ServerSideEncryption',\n 'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',\n 'x-cos-server-side-encryption-context': 'SSEContext',\n // \u4E0A\u4F20\u65F6\u56FE\u7247\u5904\u7406\n 'Pic-Operations': 'PicOperations',\n 'x-cos-callback': 'Callback',\n 'x-cos-callback-var': 'CallbackVar',\n 'x-cos-return-body': 'ReturnBody'\n };\n util.each(headerMap, function (paramKey, headerKey) {\n if (params[paramKey] !== undefined) {\n Headers[headerKey] = params[paramKey];\n }\n });\n params.Headers = clearKey(Headers);\n }\n }\n return params;\n};\nvar apiWrapper = function apiWrapper(apiName, apiFn) {\n return function (params, callback) {\n var self = this;\n\n // \u5904\u7406\u53C2\u6570\n if (typeof params === 'function') {\n callback = params;\n params = {};\n }\n\n // \u6574\u7406\u53C2\u6570\u683C\u5F0F\n params = formatParams(apiName, params);\n\n // tracker\u4F20\u9012\n var tracker;\n if (self.options.EnableReporter) {\n if (params.calledBySdk === 'sliceUploadFile' || params.calledBySdk === 'sliceCopyFile') {\n // \u5206\u5757\u4E0A\u4F20\u5185\u90E8\u65B9\u6CD5\u4F7F\u7528sliceUploadFile\u7684\u5B50\u94FE\u8DEF\n tracker = params.tracker && params.tracker.generateSubTracker({\n apiName: apiName\n });\n } else if (['uploadFile', 'uploadFiles'].includes(apiName)) {\n // uploadFile\u3001uploadFiles\u65B9\u6CD5\u5728\u5185\u90E8\u5904\u7406\uFF0C\u6B64\u5904\u4E0D\u5904\u7406\n tracker = null;\n } else {\n var fileSize = 0;\n if (params.Body) {\n fileSize = typeof params.Body === 'string' ? params.Body.length : params.Body.size || params.Body.byteLength || 0;\n }\n var accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');\n tracker = new Tracker({\n Beacon: self.options.BeaconReporter,\n clsReporter: self.options.ClsReporter,\n bucket: params.Bucket,\n region: params.Region,\n apiName: apiName,\n realApi: apiName,\n accelerate: accelerate,\n fileKey: params.Key,\n fileSize: fileSize,\n deepTracker: self.options.DeepTracker,\n customId: self.options.CustomId,\n delay: self.options.TrackerDelay\n });\n }\n }\n params.tracker = tracker;\n\n // \u4EE3\u7406\u56DE\u8C03\u51FD\u6570\n var formatResult = function formatResult(result) {\n if (result && result.headers) {\n result.headers['x-cos-request-id'] && (result.RequestId = result.headers['x-cos-request-id']);\n result.headers['x-ci-request-id'] && (result.RequestId = result.headers['x-ci-request-id']);\n result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);\n result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);\n }\n return result;\n };\n var _callback = function _callback(err, data) {\n // \u683C\u5F0F\u5316\u4E0A\u62A5\u53C2\u6570\u5E76\u4E0A\u62A5\n tracker && tracker.report(err, data);\n callback && callback(formatResult(err), formatResult(data));\n };\n var checkParams = function checkParams() {\n if (apiName !== 'getService' && apiName !== 'abortUploadTask') {\n // \u5224\u65AD\u53C2\u6570\u662F\u5426\u5B8C\u6574\n var missingResult = hasMissingParams.call(self, apiName, params);\n if (missingResult) {\n return 'missing param ' + missingResult;\n }\n // \u5224\u65AD region \u683C\u5F0F\n if (params.Region) {\n if (self.options.CompatibilityMode) {\n if (!/^([a-z\\d-.]+)$/.test(params.Region)) {\n return 'Region format error.';\n }\n } else {\n if (params.Region.indexOf('cos.') > -1) {\n return 'param Region should not be start with \"cos.\"';\n } else if (!/^([a-z\\d-]+)$/.test(params.Region)) {\n return 'Region format error.';\n }\n }\n // \u5224\u65AD region \u683C\u5F0F\n if (!self.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default' && params.Region !== 'accelerate') {\n console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');\n }\n }\n // \u517C\u5BB9\u4E0D\u5E26 AppId \u7684 Bucket\n if (params.Bucket) {\n if (!/^([a-z\\d-]+)-(\\d+)$/.test(params.Bucket)) {\n if (params.AppId) {\n params.Bucket = params.Bucket + '-' + params.AppId;\n } else if (self.options.AppId) {\n params.Bucket = params.Bucket + '-' + self.options.AppId;\n } else {\n return 'Bucket should format as \"test-1250000000\".';\n }\n }\n if (params.AppId) {\n console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:\"test-1250000000\" ).');\n delete params.AppId;\n }\n }\n // \u5982\u679C Key \u662F / \u5F00\u5934\uFF0C\u5F3A\u5236\u53BB\u6389\u7B2C\u4E00\u4E2A /\n if (!self.options.UseRawKey && params.Key && params.Key.substr(0, 1) === '/') {\n params.Key = params.Key.substr(1);\n }\n }\n };\n var errMsg = checkParams();\n var isSync = ['getAuth', 'getObjectUrl'].includes(apiName);\n if (typeof Promise === 'function' && !isSync && !callback) {\n return new Promise(function (resolve, reject) {\n callback = function callback(err, data) {\n err ? reject(err) : resolve(data);\n };\n if (errMsg) return _callback(util.error(new Error(errMsg)));\n apiFn.call(self, params, _callback);\n });\n } else {\n if (errMsg) return _callback(util.error(new Error(errMsg)));\n var res = apiFn.call(self, params, _callback);\n if (isSync) return res;\n }\n };\n};\nvar throttleOnProgress = function throttleOnProgress(total, onProgress) {\n var self = this;\n var size0 = 0;\n var size1 = 0;\n var time0 = Date.now();\n var time1;\n var timer;\n function update() {\n timer = 0;\n if (onProgress && typeof onProgress === 'function') {\n time1 = Date.now();\n var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100) || 0;\n var percent;\n if (size1 === 0 && total === 0) {\n percent = 1;\n } else {\n percent = Math.floor(size1 / total * 100) / 100 || 0;\n }\n time0 = time1;\n size0 = size1;\n try {\n onProgress({\n loaded: size1,\n total: total,\n speed: speed,\n percent: percent\n });\n } catch (e) {}\n }\n }\n return function (info, immediately) {\n if (info) {\n size1 = info.loaded;\n total = info.total;\n }\n if (immediately) {\n clearTimeout(timer);\n update();\n } else {\n if (timer) return;\n timer = setTimeout(update, self.options.ProgressInterval);\n }\n };\n};\nvar getFileSize = function getFileSize(api, params, callback) {\n var size;\n if (typeof params.Body === 'string') {\n params.Body = new Blob([params.Body], {\n type: 'text/plain'\n });\n } else if (params.Body instanceof ArrayBuffer) {\n params.Body = new Blob([params.Body]);\n }\n if (params.Body && (params.Body instanceof Blob || params.Body.toString() === '[object File]' || params.Body.toString() === '[object Blob]')) {\n size = params.Body.size;\n } else {\n callback(util.error(new Error('params body format error, Only allow File|Blob|String.')));\n return;\n }\n params.ContentLength = size;\n callback(null, size);\n};\n\n// \u83B7\u53D6\u8C03\u6B63\u7684\u65F6\u95F4\u6233\nvar getSkewTime = function getSkewTime(offset) {\n return Date.now() + (offset || 0);\n};\nvar error = function error(err, opt) {\n var sourceErr = err;\n err.message = err.message || null;\n if (typeof opt === 'string') {\n err.error = opt;\n err.message = opt;\n } else if (_typeof(opt) === 'object' && opt !== null) {\n extend(err, opt);\n if (opt.code || opt.name) err.code = opt.code || opt.name;\n if (opt.message) err.message = opt.message;\n if (opt.stack) err.stack = opt.stack;\n }\n if (typeof Object.defineProperty === 'function') {\n Object.defineProperty(err, 'name', {\n writable: true,\n enumerable: false\n });\n Object.defineProperty(err, 'message', {\n enumerable: true\n });\n }\n err.name = opt && opt.name || err.name || err.code || 'Error';\n if (!err.code) err.code = err.name;\n if (!err.error) err.error = clone(sourceErr); // \u517C\u5BB9\u8001\u7684\u9519\u8BEF\u683C\u5F0F\n\n return err;\n};\nvar isWebWorker = function isWebWorker() {\n // \u6709\u9650\u5224\u65AD worker \u73AF\u5883\u7684 constructor name \u5176\u6B21\u7528 worker \u72EC\u6709\u7684 FileReaderSync \u515C\u5E95 \u8BE6\u7EC6\u53C2\u8003 https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers\n return (typeof globalThis === \"undefined\" ? \"undefined\" : _typeof(globalThis)) === 'object' && (globalThis.constructor.name === 'DedicatedWorkerGlobalScope' || globalThis.FileReaderSync);\n};\nvar isNode = function isNode() {\n // \u5F97\u515C\u5E95 web worker \u73AF\u5883\u4E2D webpack \u7528\u4E86 process \u63D2\u4EF6\u4E4B\u7C7B\u7684\u60C5\u51B5\n return (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) !== 'object' && (typeof process === \"undefined\" ? \"undefined\" : _typeof(process)) === 'object' && \"function\" === 'function' && !isWebWorker();\n};\nvar isCIHost = function isCIHost(url) {\n return /^https?:\\/\\/([^/]+\\.)?ci\\.[^/]+/.test(url);\n};\n\n//\u5224\u65AD\u662F\u5426\u662Fios\nvar isIOS = function () {\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) !== 'object') {\n return false;\n }\n var u = navigator.userAgent;\n var isIOS = !!u.match(/\\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios\u7EC8\u7AEF\n return isIOS;\n}();\n\n// \u5224\u65AD\u662Fqq\u5185\u7F6E\u6D4F\u89C8\u5668\nvar isQQ = function () {\n if ((typeof navigator === \"undefined\" ? \"undefined\" : _typeof(navigator)) !== 'object') {\n return false;\n }\n return /\\sQQ/i.test(navigator.userAgent);\n}();\nvar encodeBase64 = function encodeBase64(str, safe) {\n var base64Str = base64.encode(str);\n // \u4E07\u8C61\u4F7F\u7528\u7684\u5B89\u5168base64\u683C\u5F0F\u9700\u8981\u7279\u6B8A\u5904\u7406\n if (safe) {\n base64Str = base64Str.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n }\n return base64Str;\n};\nvar decodeBase64 = function decodeBase64(base64Str) {\n if (!base64Str) return '';\n return base64.decode(base64Str);\n};\nvar simplifyPath = function simplifyPath(path) {\n var names = path.split('/');\n var stack = [];\n var _iterator = _createForOfIteratorHelper(names),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var name = _step.value;\n if (name === '..') {\n if (stack.length) {\n stack.pop();\n }\n } else if (name.length && name !== '.') {\n stack.push(name);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return '/' + stack.join('/');\n};\n\n// \u89E3\u6790\u54CD\u5E94\u4F53\uFF0C\u517C\u5BB9 xml\u3001json\nvar parseResBody = function parseResBody(responseBody) {\n var json;\n if (responseBody && typeof responseBody === 'string') {\n var trimBody = responseBody.trim();\n var isXml = trimBody.indexOf('<') === 0;\n var isJson = trimBody.indexOf('{') === 0;\n if (isXml) {\n // xml \u89E3\u6790\uFF0C\u89E3\u6790\u5931\u8D25\u8FD4\u56DE{}\n json = util.xml2json(responseBody) || {};\n } else if (isJson) {\n // json\u89E3\u6790\uFF0C\u89E3\u6790\u5931\u8D25\u8FD4\u56DE\u539F\u59CB Body\n try {\n // \u66FF\u6362 json \u4E2D\u7684\u6362\u884C\u7B26\u4E3A\u7A7A\u683C\uFF0C\u5426\u5219\u89E3\u6790\u4F1A\u51FA\u9519\n var formatBody = responseBody.replace(/\\n/g, ' ');\n var parsedBody = JSON.parse(formatBody);\n // \u786E\u4FDD\u89E3\u6790\u51FA json \u5BF9\u8C61\n if (Object.prototype.toString.call(parsedBody) === '[object Object]') {\n json = parsedBody;\n } else {\n json = responseBody;\n }\n } catch (e) {\n json = responseBody;\n }\n } else {\n json = responseBody;\n }\n } else {\n json = responseBody || {};\n }\n return json;\n};\nvar util = {\n noop: noop,\n formatParams: formatParams,\n apiWrapper: apiWrapper,\n xml2json: xml2json,\n json2xml: json2xml,\n md5: md5,\n clearKey: clearKey,\n fileSlice: fileSlice,\n getBodyMd5: getBodyMd5,\n getFileMd5: getFileMd5,\n b64: b64,\n extend: extend,\n isArray: isArray,\n isInArray: isInArray,\n makeArray: makeArray,\n each: each,\n map: map,\n filter: filter,\n clone: clone,\n attr: attr,\n uuid: uuid,\n camSafeUrlEncode: camSafeUrlEncode,\n throttleOnProgress: throttleOnProgress,\n getFileSize: getFileSize,\n getSkewTime: getSkewTime,\n error: error,\n obj2str: obj2str,\n getAuth: getAuth,\n parseSelectPayload: parseSelectPayload,\n getSourceParams: getSourceParams,\n isBrowser: true,\n isNode: isNode,\n isCIHost: isCIHost,\n isIOS_QQ: isIOS && isQQ,\n encodeBase64: encodeBase64,\n decodeBase64: decodeBase64,\n simplifyPath: simplifyPath,\n readAsBinaryString: readAsBinaryString,\n parseResBody: parseResBody\n};\nmodule.exports = util;\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/process/browser.js */ \"./node_modules/process/browser.js\")))\n\n/***/ })\n\n/******/ });\n});", "// can-promise has a crash in some versions of react native that dont have\n// standard global objects\n// https://github.com/soldair/node-qrcode/issues/157\n\nmodule.exports = function () {\n return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then\n}\n", "let toSJISFunction\nconst CODEWORDS_COUNT = [\n 0, // Not used\n 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,\n 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,\n 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,\n 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706\n]\n\n/**\n * Returns the QR Code size for the specified version\n *\n * @param {Number} version QR Code version\n * @return {Number} size of QR code\n */\nexports.getSymbolSize = function getSymbolSize (version) {\n if (!version) throw new Error('\"version\" cannot be null or undefined')\n if (version < 1 || version > 40) throw new Error('\"version\" should be in range from 1 to 40')\n return version * 4 + 17\n}\n\n/**\n * Returns the total number of codewords used to store data and EC information.\n *\n * @param {Number} version QR Code version\n * @return {Number} Data length in bits\n */\nexports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {\n return CODEWORDS_COUNT[version]\n}\n\n/**\n * Encode data with Bose-Chaudhuri-Hocquenghem\n *\n * @param {Number} data Value to encode\n * @return {Number} Encoded value\n */\nexports.getBCHDigit = function (data) {\n let digit = 0\n\n while (data !== 0) {\n digit++\n data >>>= 1\n }\n\n return digit\n}\n\nexports.setToSJISFunction = function setToSJISFunction (f) {\n if (typeof f !== 'function') {\n throw new Error('\"toSJISFunc\" is not a valid function.')\n }\n\n toSJISFunction = f\n}\n\nexports.isKanjiModeEnabled = function () {\n return typeof toSJISFunction !== 'undefined'\n}\n\nexports.toSJIS = function toSJIS (kanji) {\n return toSJISFunction(kanji)\n}\n", "exports.L = { bit: 1 }\nexports.M = { bit: 0 }\nexports.Q = { bit: 3 }\nexports.H = { bit: 2 }\n\nfunction fromString (string) {\n if (typeof string !== 'string') {\n throw new Error('Param is not a string')\n }\n\n const lcStr = string.toLowerCase()\n\n switch (lcStr) {\n case 'l':\n case 'low':\n return exports.L\n\n case 'm':\n case 'medium':\n return exports.M\n\n case 'q':\n case 'quartile':\n return exports.Q\n\n case 'h':\n case 'high':\n return exports.H\n\n default:\n throw new Error('Unknown EC Level: ' + string)\n }\n}\n\nexports.isValid = function isValid (level) {\n return level && typeof level.bit !== 'undefined' &&\n level.bit >= 0 && level.bit < 4\n}\n\nexports.from = function from (value, defaultValue) {\n if (exports.isValid(value)) {\n return value\n }\n\n try {\n return fromString(value)\n } catch (e) {\n return defaultValue\n }\n}\n", "function BitBuffer () {\n this.buffer = []\n this.length = 0\n}\n\nBitBuffer.prototype = {\n\n get: function (index) {\n const bufIndex = Math.floor(index / 8)\n return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1\n },\n\n put: function (num, length) {\n for (let i = 0; i < length; i++) {\n this.putBit(((num >>> (length - i - 1)) & 1) === 1)\n }\n },\n\n getLengthInBits: function () {\n return this.length\n },\n\n putBit: function (bit) {\n const bufIndex = Math.floor(this.length / 8)\n if (this.buffer.length <= bufIndex) {\n this.buffer.push(0)\n }\n\n if (bit) {\n this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))\n }\n\n this.length++\n }\n}\n\nmodule.exports = BitBuffer\n", "/**\n * Helper class to handle QR Code symbol modules\n *\n * @param {Number} size Symbol size\n */\nfunction BitMatrix (size) {\n if (!size || size < 1) {\n throw new Error('BitMatrix size must be defined and greater than 0')\n }\n\n this.size = size\n this.data = new Uint8Array(size * size)\n this.reservedBit = new Uint8Array(size * size)\n}\n\n/**\n * Set bit value at specified location\n * If reserved flag is set, this bit will be ignored during masking process\n *\n * @param {Number} row\n * @param {Number} col\n * @param {Boolean} value\n * @param {Boolean} reserved\n */\nBitMatrix.prototype.set = function (row, col, value, reserved) {\n const index = row * this.size + col\n this.data[index] = value\n if (reserved) this.reservedBit[index] = true\n}\n\n/**\n * Returns bit value at specified location\n *\n * @param {Number} row\n * @param {Number} col\n * @return {Boolean}\n */\nBitMatrix.prototype.get = function (row, col) {\n return this.data[row * this.size + col]\n}\n\n/**\n * Applies xor operator at specified location\n * (used during masking process)\n *\n * @param {Number} row\n * @param {Number} col\n * @param {Boolean} value\n */\nBitMatrix.prototype.xor = function (row, col, value) {\n this.data[row * this.size + col] ^= value\n}\n\n/**\n * Check if bit at specified location is reserved\n *\n * @param {Number} row\n * @param {Number} col\n * @return {Boolean}\n */\nBitMatrix.prototype.isReserved = function (row, col) {\n return this.reservedBit[row * this.size + col]\n}\n\nmodule.exports = BitMatrix\n", "/**\n * Alignment pattern are fixed reference pattern in defined positions\n * in a matrix symbology, which enables the decode software to re-synchronise\n * the coordinate mapping of the image modules in the event of moderate amounts\n * of distortion of the image.\n *\n * Alignment patterns are present only in QR Code symbols of version 2 or larger\n * and their number depends on the symbol version.\n */\n\nconst getSymbolSize = require('./utils').getSymbolSize\n\n/**\n * Calculate the row/column coordinates of the center module of each alignment pattern\n * for the specified QR Code version.\n *\n * The alignment patterns are positioned symmetrically on either side of the diagonal\n * running from the top left corner of the symbol to the bottom right corner.\n *\n * Since positions are simmetrical only half of the coordinates are returned.\n * Each item of the array will represent in turn the x and y coordinate.\n * @see {@link getPositions}\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinate\n */\nexports.getRowColCoords = function getRowColCoords (version) {\n if (version === 1) return []\n\n const posCount = Math.floor(version / 7) + 2\n const size = getSymbolSize(version)\n const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2\n const positions = [size - 7] // Last coord is always (size - 7)\n\n for (let i = 1; i < posCount - 1; i++) {\n positions[i] = positions[i - 1] - intervals\n }\n\n positions.push(6) // First coord is always 6\n\n return positions.reverse()\n}\n\n/**\n * Returns an array containing the positions of each alignment pattern.\n * Each array's element represent the center point of the pattern as (x, y) coordinates\n *\n * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}\n * and filtering out the items that overlaps with finder pattern\n *\n * @example\n * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.\n * The alignment patterns, therefore, are to be centered on (row, column)\n * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).\n * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns\n * and are not therefore used for alignment patterns.\n *\n * let pos = getPositions(7)\n * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n const coords = []\n const pos = exports.getRowColCoords(version)\n const posLength = pos.length\n\n for (let i = 0; i < posLength; i++) {\n for (let j = 0; j < posLength; j++) {\n // Skip if position is occupied by finder patterns\n if ((i === 0 && j === 0) || // top-left\n (i === 0 && j === posLength - 1) || // bottom-left\n (i === posLength - 1 && j === 0)) { // top-right\n continue\n }\n\n coords.push([pos[i], pos[j]])\n }\n }\n\n return coords\n}\n", "const getSymbolSize = require('./utils').getSymbolSize\nconst FINDER_PATTERN_SIZE = 7\n\n/**\n * Returns an array containing the positions of each finder pattern.\n * Each array's element represent the top-left point of the pattern as (x, y) coordinates\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n const size = getSymbolSize(version)\n\n return [\n // top-left\n [0, 0],\n // top-right\n [size - FINDER_PATTERN_SIZE, 0],\n // bottom-left\n [0, size - FINDER_PATTERN_SIZE]\n ]\n}\n", "/**\n * Data mask pattern reference\n * @type {Object}\n */\nexports.Patterns = {\n PATTERN000: 0,\n PATTERN001: 1,\n PATTERN010: 2,\n PATTERN011: 3,\n PATTERN100: 4,\n PATTERN101: 5,\n PATTERN110: 6,\n PATTERN111: 7\n}\n\n/**\n * Weighted penalty scores for the undesirable features\n * @type {Object}\n */\nconst PenaltyScores = {\n N1: 3,\n N2: 3,\n N3: 40,\n N4: 10\n}\n\n/**\n * Check if mask pattern value is valid\n *\n * @param {Number} mask Mask pattern\n * @return {Boolean} true if valid, false otherwise\n */\nexports.isValid = function isValid (mask) {\n return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7\n}\n\n/**\n * Returns mask pattern from a value.\n * If value is not valid, returns undefined\n *\n * @param {Number|String} value Mask pattern value\n * @return {Number} Valid mask pattern or undefined\n */\nexports.from = function from (value) {\n return exports.isValid(value) ? parseInt(value, 10) : undefined\n}\n\n/**\n* Find adjacent modules in row/column with the same color\n* and assign a penalty value.\n*\n* Points: N1 + i\n* i is the amount by which the number of adjacent modules of the same color exceeds 5\n*/\nexports.getPenaltyN1 = function getPenaltyN1 (data) {\n const size = data.size\n let points = 0\n let sameCountCol = 0\n let sameCountRow = 0\n let lastCol = null\n let lastRow = null\n\n for (let row = 0; row < size; row++) {\n sameCountCol = sameCountRow = 0\n lastCol = lastRow = null\n\n for (let col = 0; col < size; col++) {\n let module = data.get(row, col)\n if (module === lastCol) {\n sameCountCol++\n } else {\n if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n lastCol = module\n sameCountCol = 1\n }\n\n module = data.get(col, row)\n if (module === lastRow) {\n sameCountRow++\n } else {\n if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n lastRow = module\n sameCountRow = 1\n }\n }\n\n if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n }\n\n return points\n}\n\n/**\n * Find 2x2 blocks with the same color and assign a penalty value\n *\n * Points: N2 * (m - 1) * (n - 1)\n */\nexports.getPenaltyN2 = function getPenaltyN2 (data) {\n const size = data.size\n let points = 0\n\n for (let row = 0; row < size - 1; row++) {\n for (let col = 0; col < size - 1; col++) {\n const last = data.get(row, col) +\n data.get(row, col + 1) +\n data.get(row + 1, col) +\n data.get(row + 1, col + 1)\n\n if (last === 4 || last === 0) points++\n }\n }\n\n return points * PenaltyScores.N2\n}\n\n/**\n * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,\n * preceded or followed by light area 4 modules wide\n *\n * Points: N3 * number of pattern found\n */\nexports.getPenaltyN3 = function getPenaltyN3 (data) {\n const size = data.size\n let points = 0\n let bitsCol = 0\n let bitsRow = 0\n\n for (let row = 0; row < size; row++) {\n bitsCol = bitsRow = 0\n for (let col = 0; col < size; col++) {\n bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)\n if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++\n\n bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)\n if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++\n }\n }\n\n return points * PenaltyScores.N3\n}\n\n/**\n * Calculate proportion of dark modules in entire symbol\n *\n * Points: N4 * k\n *\n * k is the rating of the deviation of the proportion of dark modules\n * in the symbol from 50% in steps of 5%\n */\nexports.getPenaltyN4 = function getPenaltyN4 (data) {\n let darkCount = 0\n const modulesCount = data.data.length\n\n for (let i = 0; i < modulesCount; i++) darkCount += data.data[i]\n\n const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)\n\n return k * PenaltyScores.N4\n}\n\n/**\n * Return mask value at given position\n *\n * @param {Number} maskPattern Pattern reference value\n * @param {Number} i Row\n * @param {Number} j Column\n * @return {Boolean} Mask value\n */\nfunction getMaskAt (maskPattern, i, j) {\n switch (maskPattern) {\n case exports.Patterns.PATTERN000: return (i + j) % 2 === 0\n case exports.Patterns.PATTERN001: return i % 2 === 0\n case exports.Patterns.PATTERN010: return j % 3 === 0\n case exports.Patterns.PATTERN011: return (i + j) % 3 === 0\n case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0\n case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0\n case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0\n case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0\n\n default: throw new Error('bad maskPattern:' + maskPattern)\n }\n}\n\n/**\n * Apply a mask pattern to a BitMatrix\n *\n * @param {Number} pattern Pattern reference number\n * @param {BitMatrix} data BitMatrix data\n */\nexports.applyMask = function applyMask (pattern, data) {\n const size = data.size\n\n for (let col = 0; col < size; col++) {\n for (let row = 0; row < size; row++) {\n if (data.isReserved(row, col)) continue\n data.xor(row, col, getMaskAt(pattern, row, col))\n }\n }\n}\n\n/**\n * Returns the best mask pattern for data\n *\n * @param {BitMatrix} data\n * @return {Number} Mask pattern reference number\n */\nexports.getBestMask = function getBestMask (data, setupFormatFunc) {\n const numPatterns = Object.keys(exports.Patterns).length\n let bestPattern = 0\n let lowerPenalty = Infinity\n\n for (let p = 0; p < numPatterns; p++) {\n setupFormatFunc(p)\n exports.applyMask(p, data)\n\n // Calculate penalty\n const penalty =\n exports.getPenaltyN1(data) +\n exports.getPenaltyN2(data) +\n exports.getPenaltyN3(data) +\n exports.getPenaltyN4(data)\n\n // Undo previously applied mask\n exports.applyMask(p, data)\n\n if (penalty < lowerPenalty) {\n lowerPenalty = penalty\n bestPattern = p\n }\n }\n\n return bestPattern\n}\n", "const ECLevel = require('./error-correction-level')\r\n\r\nconst EC_BLOCKS_TABLE = [\r\n// L M Q H\r\n 1, 1, 1, 1,\r\n 1, 1, 1, 1,\r\n 1, 1, 2, 2,\r\n 1, 2, 2, 4,\r\n 1, 2, 4, 4,\r\n 2, 4, 4, 4,\r\n 2, 4, 6, 5,\r\n 2, 4, 6, 6,\r\n 2, 5, 8, 8,\r\n 4, 5, 8, 8,\r\n 4, 5, 8, 11,\r\n 4, 8, 10, 11,\r\n 4, 9, 12, 16,\r\n 4, 9, 16, 16,\r\n 6, 10, 12, 18,\r\n 6, 10, 17, 16,\r\n 6, 11, 16, 19,\r\n 6, 13, 18, 21,\r\n 7, 14, 21, 25,\r\n 8, 16, 20, 25,\r\n 8, 17, 23, 25,\r\n 9, 17, 23, 34,\r\n 9, 18, 25, 30,\r\n 10, 20, 27, 32,\r\n 12, 21, 29, 35,\r\n 12, 23, 34, 37,\r\n 12, 25, 34, 40,\r\n 13, 26, 35, 42,\r\n 14, 28, 38, 45,\r\n 15, 29, 40, 48,\r\n 16, 31, 43, 51,\r\n 17, 33, 45, 54,\r\n 18, 35, 48, 57,\r\n 19, 37, 51, 60,\r\n 19, 38, 53, 63,\r\n 20, 40, 56, 66,\r\n 21, 43, 59, 70,\r\n 22, 45, 62, 74,\r\n 24, 47, 65, 77,\r\n 25, 49, 68, 81\r\n]\r\n\r\nconst EC_CODEWORDS_TABLE = [\r\n// L M Q H\r\n 7, 10, 13, 17,\r\n 10, 16, 22, 28,\r\n 15, 26, 36, 44,\r\n 20, 36, 52, 64,\r\n 26, 48, 72, 88,\r\n 36, 64, 96, 112,\r\n 40, 72, 108, 130,\r\n 48, 88, 132, 156,\r\n 60, 110, 160, 192,\r\n 72, 130, 192, 224,\r\n 80, 150, 224, 264,\r\n 96, 176, 260, 308,\r\n 104, 198, 288, 352,\r\n 120, 216, 320, 384,\r\n 132, 240, 360, 432,\r\n 144, 280, 408, 480,\r\n 168, 308, 448, 532,\r\n 180, 338, 504, 588,\r\n 196, 364, 546, 650,\r\n 224, 416, 600, 700,\r\n 224, 442, 644, 750,\r\n 252, 476, 690, 816,\r\n 270, 504, 750, 900,\r\n 300, 560, 810, 960,\r\n 312, 588, 870, 1050,\r\n 336, 644, 952, 1110,\r\n 360, 700, 1020, 1200,\r\n 390, 728, 1050, 1260,\r\n 420, 784, 1140, 1350,\r\n 450, 812, 1200, 1440,\r\n 480, 868, 1290, 1530,\r\n 510, 924, 1350, 1620,\r\n 540, 980, 1440, 1710,\r\n 570, 1036, 1530, 1800,\r\n 570, 1064, 1590, 1890,\r\n 600, 1120, 1680, 1980,\r\n 630, 1204, 1770, 2100,\r\n 660, 1260, 1860, 2220,\r\n 720, 1316, 1950, 2310,\r\n 750, 1372, 2040, 2430\r\n]\r\n\r\n/**\r\n * Returns the number of error correction block that the QR Code should contain\r\n * for the specified version and error correction level.\r\n *\r\n * @param {Number} version QR Code version\r\n * @param {Number} errorCorrectionLevel Error correction level\r\n * @return {Number} Number of error correction blocks\r\n */\r\nexports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {\r\n switch (errorCorrectionLevel) {\r\n case ECLevel.L:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]\r\n case ECLevel.M:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]\r\n case ECLevel.Q:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]\r\n case ECLevel.H:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/**\r\n * Returns the number of error correction codewords to use for the specified\r\n * version and error correction level.\r\n *\r\n * @param {Number} version QR Code version\r\n * @param {Number} errorCorrectionLevel Error correction level\r\n * @return {Number} Number of error correction codewords\r\n */\r\nexports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {\r\n switch (errorCorrectionLevel) {\r\n case ECLevel.L:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]\r\n case ECLevel.M:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]\r\n case ECLevel.Q:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]\r\n case ECLevel.H:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]\r\n default:\r\n return undefined\r\n }\r\n}\r\n", "const EXP_TABLE = new Uint8Array(512)\nconst LOG_TABLE = new Uint8Array(256)\n/**\n * Precompute the log and anti-log tables for faster computation later\n *\n * For each possible value in the galois field 2^8, we will pre-compute\n * the logarithm and anti-logarithm (exponential) of this value\n *\n * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}\n */\n;(function initTables () {\n let x = 1\n for (let i = 0; i < 255; i++) {\n EXP_TABLE[i] = x\n LOG_TABLE[x] = i\n\n x <<= 1 // multiply by 2\n\n // The QR code specification says to use byte-wise modulo 100011101 arithmetic.\n // This means that when a number is 256 or larger, it should be XORed with 0x11D.\n if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)\n x ^= 0x11D\n }\n }\n\n // Optimization: double the size of the anti-log table so that we don't need to mod 255 to\n // stay inside the bounds (because we will mainly use this table for the multiplication of\n // two GF numbers, no more).\n // @see {@link mul}\n for (let i = 255; i < 512; i++) {\n EXP_TABLE[i] = EXP_TABLE[i - 255]\n }\n}())\n\n/**\n * Returns log value of n inside Galois Field\n *\n * @param {Number} n\n * @return {Number}\n */\nexports.log = function log (n) {\n if (n < 1) throw new Error('log(' + n + ')')\n return LOG_TABLE[n]\n}\n\n/**\n * Returns anti-log value of n inside Galois Field\n *\n * @param {Number} n\n * @return {Number}\n */\nexports.exp = function exp (n) {\n return EXP_TABLE[n]\n}\n\n/**\n * Multiplies two number inside Galois Field\n *\n * @param {Number} x\n * @param {Number} y\n * @return {Number}\n */\nexports.mul = function mul (x, y) {\n if (x === 0 || y === 0) return 0\n\n // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized\n // @see {@link initTables}\n return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]\n}\n", "const GF = require('./galois-field')\n\n/**\n * Multiplies two polynomials inside Galois Field\n *\n * @param {Uint8Array} p1 Polynomial\n * @param {Uint8Array} p2 Polynomial\n * @return {Uint8Array} Product of p1 and p2\n */\nexports.mul = function mul (p1, p2) {\n const coeff = new Uint8Array(p1.length + p2.length - 1)\n\n for (let i = 0; i < p1.length; i++) {\n for (let j = 0; j < p2.length; j++) {\n coeff[i + j] ^= GF.mul(p1[i], p2[j])\n }\n }\n\n return coeff\n}\n\n/**\n * Calculate the remainder of polynomials division\n *\n * @param {Uint8Array} divident Polynomial\n * @param {Uint8Array} divisor Polynomial\n * @return {Uint8Array} Remainder\n */\nexports.mod = function mod (divident, divisor) {\n let result = new Uint8Array(divident)\n\n while ((result.length - divisor.length) >= 0) {\n const coeff = result[0]\n\n for (let i = 0; i < divisor.length; i++) {\n result[i] ^= GF.mul(divisor[i], coeff)\n }\n\n // remove all zeros from buffer head\n let offset = 0\n while (offset < result.length && result[offset] === 0) offset++\n result = result.slice(offset)\n }\n\n return result\n}\n\n/**\n * Generate an irreducible generator polynomial of specified degree\n * (used by Reed-Solomon encoder)\n *\n * @param {Number} degree Degree of the generator polynomial\n * @return {Uint8Array} Buffer containing polynomial coefficients\n */\nexports.generateECPolynomial = function generateECPolynomial (degree) {\n let poly = new Uint8Array([1])\n for (let i = 0; i < degree; i++) {\n poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))\n }\n\n return poly\n}\n", "const Polynomial = require('./polynomial')\n\nfunction ReedSolomonEncoder (degree) {\n this.genPoly = undefined\n this.degree = degree\n\n if (this.degree) this.initialize(this.degree)\n}\n\n/**\n * Initialize the encoder.\n * The input param should correspond to the number of error correction codewords.\n *\n * @param {Number} degree\n */\nReedSolomonEncoder.prototype.initialize = function initialize (degree) {\n // create an irreducible generator polynomial\n this.degree = degree\n this.genPoly = Polynomial.generateECPolynomial(this.degree)\n}\n\n/**\n * Encodes a chunk of data\n *\n * @param {Uint8Array} data Buffer containing input data\n * @return {Uint8Array} Buffer containing encoded data\n */\nReedSolomonEncoder.prototype.encode = function encode (data) {\n if (!this.genPoly) {\n throw new Error('Encoder not initialized')\n }\n\n // Calculate EC for this data block\n // extends data size to data+genPoly size\n const paddedData = new Uint8Array(data.length + this.degree)\n paddedData.set(data)\n\n // The error correction codewords are the remainder after dividing the data codewords\n // by a generator polynomial\n const remainder = Polynomial.mod(paddedData, this.genPoly)\n\n // return EC data blocks (last n byte, where n is the degree of genPoly)\n // If coefficients number in remainder are less than genPoly degree,\n // pad with 0s to the left to reach the needed number of coefficients\n const start = this.degree - remainder.length\n if (start > 0) {\n const buff = new Uint8Array(this.degree)\n buff.set(remainder, start)\n\n return buff\n }\n\n return remainder\n}\n\nmodule.exports = ReedSolomonEncoder\n", "/**\n * Check if QR Code version is valid\n *\n * @param {Number} version QR Code version\n * @return {Boolean} true if valid version, false otherwise\n */\nexports.isValid = function isValid (version) {\n return !isNaN(version) && version >= 1 && version <= 40\n}\n", "const numeric = '[0-9]+'\nconst alphanumeric = '[A-Z $%*+\\\\-./:]+'\nlet kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +\n '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +\n '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +\n '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'\nkanji = kanji.replace(/u/g, '\\\\u')\n\nconst byte = '(?:(?![A-Z0-9 $%*+\\\\-./:]|' + kanji + ')(?:.|[\\r\\n]))+'\n\nexports.KANJI = new RegExp(kanji, 'g')\nexports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\\\-./:]+', 'g')\nexports.BYTE = new RegExp(byte, 'g')\nexports.NUMERIC = new RegExp(numeric, 'g')\nexports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')\n\nconst TEST_KANJI = new RegExp('^' + kanji + '$')\nconst TEST_NUMERIC = new RegExp('^' + numeric + '$')\nconst TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\\\-./:]+$')\n\nexports.testKanji = function testKanji (str) {\n return TEST_KANJI.test(str)\n}\n\nexports.testNumeric = function testNumeric (str) {\n return TEST_NUMERIC.test(str)\n}\n\nexports.testAlphanumeric = function testAlphanumeric (str) {\n return TEST_ALPHANUMERIC.test(str)\n}\n", "const VersionCheck = require('./version-check')\nconst Regex = require('./regex')\n\n/**\n * Numeric mode encodes data from the decimal digit set (0 - 9)\n * (byte values 30HEX to 39HEX).\n * Normally, 3 data characters are represented by 10 bits.\n *\n * @type {Object}\n */\nexports.NUMERIC = {\n id: 'Numeric',\n bit: 1 << 0,\n ccBits: [10, 12, 14]\n}\n\n/**\n * Alphanumeric mode encodes data from a set of 45 characters,\n * i.e. 10 numeric digits (0 - 9),\n * 26 alphabetic characters (A - Z),\n * and 9 symbols (SP, $, %, *, +, -, ., /, :).\n * Normally, two input characters are represented by 11 bits.\n *\n * @type {Object}\n */\nexports.ALPHANUMERIC = {\n id: 'Alphanumeric',\n bit: 1 << 1,\n ccBits: [9, 11, 13]\n}\n\n/**\n * In byte mode, data is encoded at 8 bits per character.\n *\n * @type {Object}\n */\nexports.BYTE = {\n id: 'Byte',\n bit: 1 << 2,\n ccBits: [8, 16, 16]\n}\n\n/**\n * The Kanji mode efficiently encodes Kanji characters in accordance with\n * the Shift JIS system based on JIS X 0208.\n * The Shift JIS values are shifted from the JIS X 0208 values.\n * JIS X 0208 gives details of the shift coded representation.\n * Each two-byte character value is compacted to a 13-bit binary codeword.\n *\n * @type {Object}\n */\nexports.KANJI = {\n id: 'Kanji',\n bit: 1 << 3,\n ccBits: [8, 10, 12]\n}\n\n/**\n * Mixed mode will contain a sequences of data in a combination of any of\n * the modes described above\n *\n * @type {Object}\n */\nexports.MIXED = {\n bit: -1\n}\n\n/**\n * Returns the number of bits needed to store the data length\n * according to QR Code specifications.\n *\n * @param {Mode} mode Data mode\n * @param {Number} version QR Code version\n * @return {Number} Number of bits\n */\nexports.getCharCountIndicator = function getCharCountIndicator (mode, version) {\n if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)\n\n if (!VersionCheck.isValid(version)) {\n throw new Error('Invalid version: ' + version)\n }\n\n if (version >= 1 && version < 10) return mode.ccBits[0]\n else if (version < 27) return mode.ccBits[1]\n return mode.ccBits[2]\n}\n\n/**\n * Returns the most efficient mode to store the specified data\n *\n * @param {String} dataStr Input data string\n * @return {Mode} Best mode\n */\nexports.getBestModeForData = function getBestModeForData (dataStr) {\n if (Regex.testNumeric(dataStr)) return exports.NUMERIC\n else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC\n else if (Regex.testKanji(dataStr)) return exports.KANJI\n else return exports.BYTE\n}\n\n/**\n * Return mode name as string\n *\n * @param {Mode} mode Mode object\n * @returns {String} Mode name\n */\nexports.toString = function toString (mode) {\n if (mode && mode.id) return mode.id\n throw new Error('Invalid mode')\n}\n\n/**\n * Check if input param is a valid mode object\n *\n * @param {Mode} mode Mode object\n * @returns {Boolean} True if valid mode, false otherwise\n */\nexports.isValid = function isValid (mode) {\n return mode && mode.bit && mode.ccBits\n}\n\n/**\n * Get mode object from its name\n *\n * @param {String} string Mode name\n * @returns {Mode} Mode object\n */\nfunction fromString (string) {\n if (typeof string !== 'string') {\n throw new Error('Param is not a string')\n }\n\n const lcStr = string.toLowerCase()\n\n switch (lcStr) {\n case 'numeric':\n return exports.NUMERIC\n case 'alphanumeric':\n return exports.ALPHANUMERIC\n case 'kanji':\n return exports.KANJI\n case 'byte':\n return exports.BYTE\n default:\n throw new Error('Unknown mode: ' + string)\n }\n}\n\n/**\n * Returns mode from a value.\n * If value is not a valid mode, returns defaultValue\n *\n * @param {Mode|String} value Encoding mode\n * @param {Mode} defaultValue Fallback value\n * @return {Mode} Encoding mode\n */\nexports.from = function from (value, defaultValue) {\n if (exports.isValid(value)) {\n return value\n }\n\n try {\n return fromString(value)\n } catch (e) {\n return defaultValue\n }\n}\n", "const Utils = require('./utils')\nconst ECCode = require('./error-correction-code')\nconst ECLevel = require('./error-correction-level')\nconst Mode = require('./mode')\nconst VersionCheck = require('./version-check')\n\n// Generator polynomial used to encode version information\nconst G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)\nconst G18_BCH = Utils.getBCHDigit(G18)\n\nfunction getBestVersionForDataLength (mode, length, errorCorrectionLevel) {\n for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {\n return currentVersion\n }\n }\n\n return undefined\n}\n\nfunction getReservedBitsCount (mode, version) {\n // Character count indicator + mode indicator bits\n return Mode.getCharCountIndicator(mode, version) + 4\n}\n\nfunction getTotalBitsFromDataArray (segments, version) {\n let totalBits = 0\n\n segments.forEach(function (data) {\n const reservedBits = getReservedBitsCount(data.mode, version)\n totalBits += reservedBits + data.getBitsLength()\n })\n\n return totalBits\n}\n\nfunction getBestVersionForMixedData (segments, errorCorrectionLevel) {\n for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n const length = getTotalBitsFromDataArray(segments, currentVersion)\n if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {\n return currentVersion\n }\n }\n\n return undefined\n}\n\n/**\n * Returns version number from a value.\n * If value is not a valid version, returns defaultValue\n *\n * @param {Number|String} value QR Code version\n * @param {Number} defaultValue Fallback value\n * @return {Number} QR Code version number\n */\nexports.from = function from (value, defaultValue) {\n if (VersionCheck.isValid(value)) {\n return parseInt(value, 10)\n }\n\n return defaultValue\n}\n\n/**\n * Returns how much data can be stored with the specified QR code version\n * and error correction level\n *\n * @param {Number} version QR Code version (1-40)\n * @param {Number} errorCorrectionLevel Error correction level\n * @param {Mode} mode Data mode\n * @return {Number} Quantity of storable data\n */\nexports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {\n if (!VersionCheck.isValid(version)) {\n throw new Error('Invalid QR Code version')\n }\n\n // Use Byte mode as default\n if (typeof mode === 'undefined') mode = Mode.BYTE\n\n // Total codewords for this QR code version (Data + Error correction)\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n // Total number of error correction codewords\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n // Total number of data codewords\n const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n if (mode === Mode.MIXED) return dataTotalCodewordsBits\n\n const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)\n\n // Return max number of storable codewords\n switch (mode) {\n case Mode.NUMERIC:\n return Math.floor((usableBits / 10) * 3)\n\n case Mode.ALPHANUMERIC:\n return Math.floor((usableBits / 11) * 2)\n\n case Mode.KANJI:\n return Math.floor(usableBits / 13)\n\n case Mode.BYTE:\n default:\n return Math.floor(usableBits / 8)\n }\n}\n\n/**\n * Returns the minimum version needed to contain the amount of data\n *\n * @param {Segment} data Segment of data\n * @param {Number} [errorCorrectionLevel=H] Error correction level\n * @param {Mode} mode Data mode\n * @return {Number} QR Code version\n */\nexports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {\n let seg\n\n const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)\n\n if (Array.isArray(data)) {\n if (data.length > 1) {\n return getBestVersionForMixedData(data, ecl)\n }\n\n if (data.length === 0) {\n return 1\n }\n\n seg = data[0]\n } else {\n seg = data\n }\n\n return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)\n}\n\n/**\n * Returns version information with relative error correction bits\n *\n * The version information is included in QR Code symbols of version 7 or larger.\n * It consists of an 18-bit sequence containing 6 data bits,\n * with 12 error correction bits calculated using the (18, 6) Golay code.\n *\n * @param {Number} version QR Code version\n * @return {Number} Encoded version info bits\n */\nexports.getEncodedBits = function getEncodedBits (version) {\n if (!VersionCheck.isValid(version) || version < 7) {\n throw new Error('Invalid QR Code version')\n }\n\n let d = version << 12\n\n while (Utils.getBCHDigit(d) - G18_BCH >= 0) {\n d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))\n }\n\n return (version << 12) | d\n}\n", "const Utils = require('./utils')\n\nconst G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)\nconst G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)\nconst G15_BCH = Utils.getBCHDigit(G15)\n\n/**\n * Returns format information with relative error correction bits\n *\n * The format information is a 15-bit sequence containing 5 data bits,\n * with 10 error correction bits calculated using the (15, 5) BCH code.\n *\n * @param {Number} errorCorrectionLevel Error correction level\n * @param {Number} mask Mask pattern\n * @return {Number} Encoded format information bits\n */\nexports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {\n const data = ((errorCorrectionLevel.bit << 3) | mask)\n let d = data << 10\n\n while (Utils.getBCHDigit(d) - G15_BCH >= 0) {\n d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))\n }\n\n // xor final data with mask pattern in order to ensure that\n // no combination of Error Correction Level and data mask pattern\n // will result in an all-zero data string\n return ((data << 10) | d) ^ G15_MASK\n}\n", "const Mode = require('./mode')\n\nfunction NumericData (data) {\n this.mode = Mode.NUMERIC\n this.data = data.toString()\n}\n\nNumericData.getBitsLength = function getBitsLength (length) {\n return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)\n}\n\nNumericData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nNumericData.prototype.getBitsLength = function getBitsLength () {\n return NumericData.getBitsLength(this.data.length)\n}\n\nNumericData.prototype.write = function write (bitBuffer) {\n let i, group, value\n\n // The input data string is divided into groups of three digits,\n // and each group is converted to its 10-bit binary equivalent.\n for (i = 0; i + 3 <= this.data.length; i += 3) {\n group = this.data.substr(i, 3)\n value = parseInt(group, 10)\n\n bitBuffer.put(value, 10)\n }\n\n // If the number of input digits is not an exact multiple of three,\n // the final one or two digits are converted to 4 or 7 bits respectively.\n const remainingNum = this.data.length - i\n if (remainingNum > 0) {\n group = this.data.substr(i)\n value = parseInt(group, 10)\n\n bitBuffer.put(value, remainingNum * 3 + 1)\n }\n}\n\nmodule.exports = NumericData\n", "const Mode = require('./mode')\n\n/**\n * Array of characters available in alphanumeric mode\n *\n * As per QR Code specification, to each character\n * is assigned a value from 0 to 44 which in this case coincides\n * with the array index\n *\n * @type {Array}\n */\nconst ALPHA_NUM_CHARS = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n ' ', '$', '%', '*', '+', '-', '.', '/', ':'\n]\n\nfunction AlphanumericData (data) {\n this.mode = Mode.ALPHANUMERIC\n this.data = data\n}\n\nAlphanumericData.getBitsLength = function getBitsLength (length) {\n return 11 * Math.floor(length / 2) + 6 * (length % 2)\n}\n\nAlphanumericData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nAlphanumericData.prototype.getBitsLength = function getBitsLength () {\n return AlphanumericData.getBitsLength(this.data.length)\n}\n\nAlphanumericData.prototype.write = function write (bitBuffer) {\n let i\n\n // Input data characters are divided into groups of two characters\n // and encoded as 11-bit binary codes.\n for (i = 0; i + 2 <= this.data.length; i += 2) {\n // The character value of the first character is multiplied by 45\n let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45\n\n // The character value of the second digit is added to the product\n value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])\n\n // The sum is then stored as 11-bit binary number\n bitBuffer.put(value, 11)\n }\n\n // If the number of input data characters is not a multiple of two,\n // the character value of the final character is encoded as a 6-bit binary number.\n if (this.data.length % 2) {\n bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)\n }\n}\n\nmodule.exports = AlphanumericData\n", "'use strict'\n\nmodule.exports = function encodeUtf8 (input) {\n var result = []\n var size = input.length\n\n for (var index = 0; index < size; index++) {\n var point = input.charCodeAt(index)\n\n if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) {\n var second = input.charCodeAt(index + 1)\n\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n index += 1\n }\n }\n\n // US-ASCII\n if (point < 0x80) {\n result.push(point)\n continue\n }\n\n // 2-byte UTF-8\n if (point < 0x800) {\n result.push((point >> 6) | 192)\n result.push((point & 63) | 128)\n continue\n }\n\n // 3-byte UTF-8\n if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) {\n result.push((point >> 12) | 224)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // 4-byte UTF-8\n if (point >= 0x10000 && point <= 0x10FFFF) {\n result.push((point >> 18) | 240)\n result.push(((point >> 12) & 63) | 128)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // Invalid character\n result.push(0xEF, 0xBF, 0xBD)\n }\n\n return new Uint8Array(result).buffer\n}\n", "const encodeUtf8 = require('encode-utf8')\nconst Mode = require('./mode')\n\nfunction ByteData (data) {\n this.mode = Mode.BYTE\n if (typeof (data) === 'string') {\n data = encodeUtf8(data)\n }\n this.data = new Uint8Array(data)\n}\n\nByteData.getBitsLength = function getBitsLength (length) {\n return length * 8\n}\n\nByteData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nByteData.prototype.getBitsLength = function getBitsLength () {\n return ByteData.getBitsLength(this.data.length)\n}\n\nByteData.prototype.write = function (bitBuffer) {\n for (let i = 0, l = this.data.length; i < l; i++) {\n bitBuffer.put(this.data[i], 8)\n }\n}\n\nmodule.exports = ByteData\n", "const Mode = require('./mode')\nconst Utils = require('./utils')\n\nfunction KanjiData (data) {\n this.mode = Mode.KANJI\n this.data = data\n}\n\nKanjiData.getBitsLength = function getBitsLength (length) {\n return length * 13\n}\n\nKanjiData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nKanjiData.prototype.getBitsLength = function getBitsLength () {\n return KanjiData.getBitsLength(this.data.length)\n}\n\nKanjiData.prototype.write = function (bitBuffer) {\n let i\n\n // In the Shift JIS system, Kanji characters are represented by a two byte combination.\n // These byte values are shifted from the JIS X 0208 values.\n // JIS X 0208 gives details of the shift coded representation.\n for (i = 0; i < this.data.length; i++) {\n let value = Utils.toSJIS(this.data[i])\n\n // For characters with Shift JIS values from 0x8140 to 0x9FFC:\n if (value >= 0x8140 && value <= 0x9FFC) {\n // Subtract 0x8140 from Shift JIS value\n value -= 0x8140\n\n // For characters with Shift JIS values from 0xE040 to 0xEBBF\n } else if (value >= 0xE040 && value <= 0xEBBF) {\n // Subtract 0xC140 from Shift JIS value\n value -= 0xC140\n } else {\n throw new Error(\n 'Invalid SJIS character: ' + this.data[i] + '\\n' +\n 'Make sure your charset is UTF-8')\n }\n\n // Multiply most significant byte of result by 0xC0\n // and add least significant byte to product\n value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)\n\n // Convert result to a 13-bit binary string\n bitBuffer.put(value, 13)\n }\n}\n\nmodule.exports = KanjiData\n", "'use strict';\n\n/******************************************************************************\n * Created 2008-08-19.\n *\n * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.\n *\n * Copyright (C) 2008\n * Wyatt Baldwin \n * All rights reserved\n *\n * Licensed under the MIT license.\n *\n * http://www.opensource.org/licenses/mit-license.php\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *****************************************************************************/\nvar dijkstra = {\n single_source_shortest_paths: function(graph, s, d) {\n // Predecessor map for each node that has been encountered.\n // node ID => predecessor node ID\n var predecessors = {};\n\n // Costs of shortest paths from s to all nodes encountered.\n // node ID => cost\n var costs = {};\n costs[s] = 0;\n\n // Costs of shortest paths from s to all nodes encountered; differs from\n // `costs` in that it provides easy access to the node that currently has\n // the known shortest path from s.\n // XXX: Do we actually need both `costs` and `open`?\n var open = dijkstra.PriorityQueue.make();\n open.push(s, 0);\n\n var closest,\n u, v,\n cost_of_s_to_u,\n adjacent_nodes,\n cost_of_e,\n cost_of_s_to_u_plus_cost_of_e,\n cost_of_s_to_v,\n first_visit;\n while (!open.empty()) {\n // In the nodes remaining in graph that have a known cost from s,\n // find the node, u, that currently has the shortest path from s.\n closest = open.pop();\n u = closest.value;\n cost_of_s_to_u = closest.cost;\n\n // Get nodes adjacent to u...\n adjacent_nodes = graph[u] || {};\n\n // ...and explore the edges that connect u to those nodes, updating\n // the cost of the shortest paths to any or all of those nodes as\n // necessary. v is the node across the current edge from u.\n for (v in adjacent_nodes) {\n if (adjacent_nodes.hasOwnProperty(v)) {\n // Get the cost of the edge running from u to v.\n cost_of_e = adjacent_nodes[v];\n\n // Cost of s to u plus the cost of u to v across e--this is *a*\n // cost from s to v that may or may not be less than the current\n // known cost to v.\n cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;\n\n // If we haven't visited v yet OR if the current known cost from s to\n // v is greater than the new cost we just found (cost of s to u plus\n // cost of u to v across e), update v's cost in the cost list and\n // update v's predecessor in the predecessor list (it's now u).\n cost_of_s_to_v = costs[v];\n first_visit = (typeof costs[v] === 'undefined');\n if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {\n costs[v] = cost_of_s_to_u_plus_cost_of_e;\n open.push(v, cost_of_s_to_u_plus_cost_of_e);\n predecessors[v] = u;\n }\n }\n }\n }\n\n if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {\n var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');\n throw new Error(msg);\n }\n\n return predecessors;\n },\n\n extract_shortest_path_from_predecessor_list: function(predecessors, d) {\n var nodes = [];\n var u = d;\n var predecessor;\n while (u) {\n nodes.push(u);\n predecessor = predecessors[u];\n u = predecessors[u];\n }\n nodes.reverse();\n return nodes;\n },\n\n find_path: function(graph, s, d) {\n var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);\n return dijkstra.extract_shortest_path_from_predecessor_list(\n predecessors, d);\n },\n\n /**\n * A very naive priority queue implementation.\n */\n PriorityQueue: {\n make: function (opts) {\n var T = dijkstra.PriorityQueue,\n t = {},\n key;\n opts = opts || {};\n for (key in T) {\n if (T.hasOwnProperty(key)) {\n t[key] = T[key];\n }\n }\n t.queue = [];\n t.sorter = opts.sorter || T.default_sorter;\n return t;\n },\n\n default_sorter: function (a, b) {\n return a.cost - b.cost;\n },\n\n /**\n * Add a new item to the queue and ensure the highest priority element\n * is at the front of the queue.\n */\n push: function (value, cost) {\n var item = {value: value, cost: cost};\n this.queue.push(item);\n this.queue.sort(this.sorter);\n },\n\n /**\n * Return the highest priority element in the queue.\n */\n pop: function () {\n return this.queue.shift();\n },\n\n empty: function () {\n return this.queue.length === 0;\n }\n }\n};\n\n\n// node.js module exports\nif (typeof module !== 'undefined') {\n module.exports = dijkstra;\n}\n", "const Mode = require('./mode')\nconst NumericData = require('./numeric-data')\nconst AlphanumericData = require('./alphanumeric-data')\nconst ByteData = require('./byte-data')\nconst KanjiData = require('./kanji-data')\nconst Regex = require('./regex')\nconst Utils = require('./utils')\nconst dijkstra = require('dijkstrajs')\n\n/**\n * Returns UTF8 byte length\n *\n * @param {String} str Input string\n * @return {Number} Number of byte\n */\nfunction getStringByteLength (str) {\n return unescape(encodeURIComponent(str)).length\n}\n\n/**\n * Get a list of segments of the specified mode\n * from a string\n *\n * @param {Mode} mode Segment mode\n * @param {String} str String to process\n * @return {Array} Array of object with segments data\n */\nfunction getSegments (regex, mode, str) {\n const segments = []\n let result\n\n while ((result = regex.exec(str)) !== null) {\n segments.push({\n data: result[0],\n index: result.index,\n mode: mode,\n length: result[0].length\n })\n }\n\n return segments\n}\n\n/**\n * Extracts a series of segments with the appropriate\n * modes from a string\n *\n * @param {String} dataStr Input string\n * @return {Array} Array of object with segments data\n */\nfunction getSegmentsFromString (dataStr) {\n const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)\n const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)\n let byteSegs\n let kanjiSegs\n\n if (Utils.isKanjiModeEnabled()) {\n byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)\n kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)\n } else {\n byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)\n kanjiSegs = []\n }\n\n const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)\n\n return segs\n .sort(function (s1, s2) {\n return s1.index - s2.index\n })\n .map(function (obj) {\n return {\n data: obj.data,\n mode: obj.mode,\n length: obj.length\n }\n })\n}\n\n/**\n * Returns how many bits are needed to encode a string of\n * specified length with the specified mode\n *\n * @param {Number} length String length\n * @param {Mode} mode Segment mode\n * @return {Number} Bit length\n */\nfunction getSegmentBitsLength (length, mode) {\n switch (mode) {\n case Mode.NUMERIC:\n return NumericData.getBitsLength(length)\n case Mode.ALPHANUMERIC:\n return AlphanumericData.getBitsLength(length)\n case Mode.KANJI:\n return KanjiData.getBitsLength(length)\n case Mode.BYTE:\n return ByteData.getBitsLength(length)\n }\n}\n\n/**\n * Merges adjacent segments which have the same mode\n *\n * @param {Array} segs Array of object with segments data\n * @return {Array} Array of object with segments data\n */\nfunction mergeSegments (segs) {\n return segs.reduce(function (acc, curr) {\n const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null\n if (prevSeg && prevSeg.mode === curr.mode) {\n acc[acc.length - 1].data += curr.data\n return acc\n }\n\n acc.push(curr)\n return acc\n }, [])\n}\n\n/**\n * Generates a list of all possible nodes combination which\n * will be used to build a segments graph.\n *\n * Nodes are divided by groups. Each group will contain a list of all the modes\n * in which is possible to encode the given text.\n *\n * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.\n * The group for '12345' will contain then 3 objects, one for each\n * possible encoding mode.\n *\n * Each node represents a possible segment.\n *\n * @param {Array} segs Array of object with segments data\n * @return {Array} Array of object with segments data\n */\nfunction buildNodes (segs) {\n const nodes = []\n for (let i = 0; i < segs.length; i++) {\n const seg = segs[i]\n\n switch (seg.mode) {\n case Mode.NUMERIC:\n nodes.push([seg,\n { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },\n { data: seg.data, mode: Mode.BYTE, length: seg.length }\n ])\n break\n case Mode.ALPHANUMERIC:\n nodes.push([seg,\n { data: seg.data, mode: Mode.BYTE, length: seg.length }\n ])\n break\n case Mode.KANJI:\n nodes.push([seg,\n { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n ])\n break\n case Mode.BYTE:\n nodes.push([\n { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n ])\n }\n }\n\n return nodes\n}\n\n/**\n * Builds a graph from a list of nodes.\n * All segments in each node group will be connected with all the segments of\n * the next group and so on.\n *\n * At each connection will be assigned a weight depending on the\n * segment's byte length.\n *\n * @param {Array} nodes Array of object with segments data\n * @param {Number} version QR Code version\n * @return {Object} Graph of all possible segments\n */\nfunction buildGraph (nodes, version) {\n const table = {}\n const graph = { start: {} }\n let prevNodeIds = ['start']\n\n for (let i = 0; i < nodes.length; i++) {\n const nodeGroup = nodes[i]\n const currentNodeIds = []\n\n for (let j = 0; j < nodeGroup.length; j++) {\n const node = nodeGroup[j]\n const key = '' + i + j\n\n currentNodeIds.push(key)\n table[key] = { node: node, lastCount: 0 }\n graph[key] = {}\n\n for (let n = 0; n < prevNodeIds.length; n++) {\n const prevNodeId = prevNodeIds[n]\n\n if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {\n graph[prevNodeId][key] =\n getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -\n getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)\n\n table[prevNodeId].lastCount += node.length\n } else {\n if (table[prevNodeId]) table[prevNodeId].lastCount = node.length\n\n graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +\n 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost\n }\n }\n }\n\n prevNodeIds = currentNodeIds\n }\n\n for (let n = 0; n < prevNodeIds.length; n++) {\n graph[prevNodeIds[n]].end = 0\n }\n\n return { map: graph, table: table }\n}\n\n/**\n * Builds a segment from a specified data and mode.\n * If a mode is not specified, the more suitable will be used.\n *\n * @param {String} data Input data\n * @param {Mode | String} modesHint Data mode\n * @return {Segment} Segment\n */\nfunction buildSingleSegment (data, modesHint) {\n let mode\n const bestMode = Mode.getBestModeForData(data)\n\n mode = Mode.from(modesHint, bestMode)\n\n // Make sure data can be encoded\n if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {\n throw new Error('\"' + data + '\"' +\n ' cannot be encoded with mode ' + Mode.toString(mode) +\n '.\\n Suggested mode is: ' + Mode.toString(bestMode))\n }\n\n // Use Mode.BYTE if Kanji support is disabled\n if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {\n mode = Mode.BYTE\n }\n\n switch (mode) {\n case Mode.NUMERIC:\n return new NumericData(data)\n\n case Mode.ALPHANUMERIC:\n return new AlphanumericData(data)\n\n case Mode.KANJI:\n return new KanjiData(data)\n\n case Mode.BYTE:\n return new ByteData(data)\n }\n}\n\n/**\n * Builds a list of segments from an array.\n * Array can contain Strings or Objects with segment's info.\n *\n * For each item which is a string, will be generated a segment with the given\n * string and the more appropriate encoding mode.\n *\n * For each item which is an object, will be generated a segment with the given\n * data and mode.\n * Objects must contain at least the property \"data\".\n * If property \"mode\" is not present, the more suitable mode will be used.\n *\n * @param {Array} array Array of objects with segments data\n * @return {Array} Array of Segments\n */\nexports.fromArray = function fromArray (array) {\n return array.reduce(function (acc, seg) {\n if (typeof seg === 'string') {\n acc.push(buildSingleSegment(seg, null))\n } else if (seg.data) {\n acc.push(buildSingleSegment(seg.data, seg.mode))\n }\n\n return acc\n }, [])\n}\n\n/**\n * Builds an optimized sequence of segments from a string,\n * which will produce the shortest possible bitstream.\n *\n * @param {String} data Input string\n * @param {Number} version QR Code version\n * @return {Array} Array of segments\n */\nexports.fromString = function fromString (data, version) {\n const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n\n const nodes = buildNodes(segs)\n const graph = buildGraph(nodes, version)\n const path = dijkstra.find_path(graph.map, 'start', 'end')\n\n const optimizedSegs = []\n for (let i = 1; i < path.length - 1; i++) {\n optimizedSegs.push(graph.table[path[i]].node)\n }\n\n return exports.fromArray(mergeSegments(optimizedSegs))\n}\n\n/**\n * Splits a string in various segments with the modes which\n * best represent their content.\n * The produced segments are far from being optimized.\n * The output of this function is only used to estimate a QR Code version\n * which may contain the data.\n *\n * @param {string} data Input string\n * @return {Array} Array of segments\n */\nexports.rawSplit = function rawSplit (data) {\n return exports.fromArray(\n getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n )\n}\n", "const Utils = require('./utils')\nconst ECLevel = require('./error-correction-level')\nconst BitBuffer = require('./bit-buffer')\nconst BitMatrix = require('./bit-matrix')\nconst AlignmentPattern = require('./alignment-pattern')\nconst FinderPattern = require('./finder-pattern')\nconst MaskPattern = require('./mask-pattern')\nconst ECCode = require('./error-correction-code')\nconst ReedSolomonEncoder = require('./reed-solomon-encoder')\nconst Version = require('./version')\nconst FormatInfo = require('./format-info')\nconst Mode = require('./mode')\nconst Segments = require('./segments')\n\n/**\n * QRCode for JavaScript\n *\n * modified by Ryan Day for nodejs support\n * Copyright (c) 2011 Ryan Day\n *\n * Licensed under the MIT license:\n * http://www.opensource.org/licenses/mit-license.php\n *\n//---------------------------------------------------------------------\n// QRCode for JavaScript\n//\n// Copyright (c) 2009 Kazuhiko Arase\n//\n// URL: http://www.d-project.com/\n//\n// Licensed under the MIT license:\n// http://www.opensource.org/licenses/mit-license.php\n//\n// The word \"QR Code\" is registered trademark of\n// DENSO WAVE INCORPORATED\n// http://www.denso-wave.com/qrcode/faqpatent-e.html\n//\n//---------------------------------------------------------------------\n*/\n\n/**\n * Add finder patterns bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupFinderPattern (matrix, version) {\n const size = matrix.size\n const pos = FinderPattern.getPositions(version)\n\n for (let i = 0; i < pos.length; i++) {\n const row = pos[i][0]\n const col = pos[i][1]\n\n for (let r = -1; r <= 7; r++) {\n if (row + r <= -1 || size <= row + r) continue\n\n for (let c = -1; c <= 7; c++) {\n if (col + c <= -1 || size <= col + c) continue\n\n if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||\n (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||\n (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {\n matrix.set(row + r, col + c, true, true)\n } else {\n matrix.set(row + r, col + c, false, true)\n }\n }\n }\n }\n}\n\n/**\n * Add timing pattern bits to matrix\n *\n * Note: this function must be called before {@link setupAlignmentPattern}\n *\n * @param {BitMatrix} matrix Modules matrix\n */\nfunction setupTimingPattern (matrix) {\n const size = matrix.size\n\n for (let r = 8; r < size - 8; r++) {\n const value = r % 2 === 0\n matrix.set(r, 6, value, true)\n matrix.set(6, r, value, true)\n }\n}\n\n/**\n * Add alignment patterns bits to matrix\n *\n * Note: this function must be called after {@link setupTimingPattern}\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupAlignmentPattern (matrix, version) {\n const pos = AlignmentPattern.getPositions(version)\n\n for (let i = 0; i < pos.length; i++) {\n const row = pos[i][0]\n const col = pos[i][1]\n\n for (let r = -2; r <= 2; r++) {\n for (let c = -2; c <= 2; c++) {\n if (r === -2 || r === 2 || c === -2 || c === 2 ||\n (r === 0 && c === 0)) {\n matrix.set(row + r, col + c, true, true)\n } else {\n matrix.set(row + r, col + c, false, true)\n }\n }\n }\n }\n}\n\n/**\n * Add version info bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupVersionInfo (matrix, version) {\n const size = matrix.size\n const bits = Version.getEncodedBits(version)\n let row, col, mod\n\n for (let i = 0; i < 18; i++) {\n row = Math.floor(i / 3)\n col = i % 3 + size - 8 - 3\n mod = ((bits >> i) & 1) === 1\n\n matrix.set(row, col, mod, true)\n matrix.set(col, row, mod, true)\n }\n}\n\n/**\n * Add format info bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @param {Number} maskPattern Mask pattern reference value\n */\nfunction setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {\n const size = matrix.size\n const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)\n let i, mod\n\n for (i = 0; i < 15; i++) {\n mod = ((bits >> i) & 1) === 1\n\n // vertical\n if (i < 6) {\n matrix.set(i, 8, mod, true)\n } else if (i < 8) {\n matrix.set(i + 1, 8, mod, true)\n } else {\n matrix.set(size - 15 + i, 8, mod, true)\n }\n\n // horizontal\n if (i < 8) {\n matrix.set(8, size - i - 1, mod, true)\n } else if (i < 9) {\n matrix.set(8, 15 - i - 1 + 1, mod, true)\n } else {\n matrix.set(8, 15 - i - 1, mod, true)\n }\n }\n\n // fixed module\n matrix.set(size - 8, 8, 1, true)\n}\n\n/**\n * Add encoded data bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Uint8Array} data Data codewords\n */\nfunction setupData (matrix, data) {\n const size = matrix.size\n let inc = -1\n let row = size - 1\n let bitIndex = 7\n let byteIndex = 0\n\n for (let col = size - 1; col > 0; col -= 2) {\n if (col === 6) col--\n\n while (true) {\n for (let c = 0; c < 2; c++) {\n if (!matrix.isReserved(row, col - c)) {\n let dark = false\n\n if (byteIndex < data.length) {\n dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)\n }\n\n matrix.set(row, col - c, dark)\n bitIndex--\n\n if (bitIndex === -1) {\n byteIndex++\n bitIndex = 7\n }\n }\n }\n\n row += inc\n\n if (row < 0 || size <= row) {\n row -= inc\n inc = -inc\n break\n }\n }\n }\n}\n\n/**\n * Create encoded codewords from data input\n *\n * @param {Number} version QR Code version\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @param {ByteData} data Data input\n * @return {Uint8Array} Buffer containing encoded codewords\n */\nfunction createData (version, errorCorrectionLevel, segments) {\n // Prepare data buffer\n const buffer = new BitBuffer()\n\n segments.forEach(function (data) {\n // prefix data with mode indicator (4 bits)\n buffer.put(data.mode.bit, 4)\n\n // Prefix data with character count indicator.\n // The character count indicator is a string of bits that represents the\n // number of characters that are being encoded.\n // The character count indicator must be placed after the mode indicator\n // and must be a certain number of bits long, depending on the QR version\n // and data mode\n // @see {@link Mode.getCharCountIndicator}.\n buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))\n\n // add binary data sequence to buffer\n data.write(buffer)\n })\n\n // Calculate required number of bits\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n // Add a terminator.\n // If the bit string is shorter than the total number of required bits,\n // a terminator of up to four 0s must be added to the right side of the string.\n // If the bit string is more than four bits shorter than the required number of bits,\n // add four 0s to the end.\n if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {\n buffer.put(0, 4)\n }\n\n // If the bit string is fewer than four bits shorter, add only the number of 0s that\n // are needed to reach the required number of bits.\n\n // After adding the terminator, if the number of bits in the string is not a multiple of 8,\n // pad the string on the right with 0s to make the string's length a multiple of 8.\n while (buffer.getLengthInBits() % 8 !== 0) {\n buffer.putBit(0)\n }\n\n // Add pad bytes if the string is still shorter than the total number of required bits.\n // Extend the buffer to fill the data capacity of the symbol corresponding to\n // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)\n // and 00010001 (0x11) alternately.\n const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8\n for (let i = 0; i < remainingByte; i++) {\n buffer.put(i % 2 ? 0x11 : 0xEC, 8)\n }\n\n return createCodewords(buffer, version, errorCorrectionLevel)\n}\n\n/**\n * Encode input data with Reed-Solomon and return codewords with\n * relative error correction bits\n *\n * @param {BitBuffer} bitBuffer Data to encode\n * @param {Number} version QR Code version\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @return {Uint8Array} Buffer containing encoded codewords\n */\nfunction createCodewords (bitBuffer, version, errorCorrectionLevel) {\n // Total codewords for this QR code version (Data + Error correction)\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n // Total number of error correction codewords\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n // Total number of data codewords\n const dataTotalCodewords = totalCodewords - ecTotalCodewords\n\n // Total number of blocks\n const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)\n\n // Calculate how many blocks each group should contain\n const blocksInGroup2 = totalCodewords % ecTotalBlocks\n const blocksInGroup1 = ecTotalBlocks - blocksInGroup2\n\n const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)\n\n const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)\n const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1\n\n // Number of EC codewords is the same for both groups\n const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1\n\n // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount\n const rs = new ReedSolomonEncoder(ecCount)\n\n let offset = 0\n const dcData = new Array(ecTotalBlocks)\n const ecData = new Array(ecTotalBlocks)\n let maxDataSize = 0\n const buffer = new Uint8Array(bitBuffer.buffer)\n\n // Divide the buffer into the required number of blocks\n for (let b = 0; b < ecTotalBlocks; b++) {\n const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2\n\n // extract a block of data from buffer\n dcData[b] = buffer.slice(offset, offset + dataSize)\n\n // Calculate EC codewords for this data block\n ecData[b] = rs.encode(dcData[b])\n\n offset += dataSize\n maxDataSize = Math.max(maxDataSize, dataSize)\n }\n\n // Create final data\n // Interleave the data and error correction codewords from each block\n const data = new Uint8Array(totalCodewords)\n let index = 0\n let i, r\n\n // Add data codewords\n for (i = 0; i < maxDataSize; i++) {\n for (r = 0; r < ecTotalBlocks; r++) {\n if (i < dcData[r].length) {\n data[index++] = dcData[r][i]\n }\n }\n }\n\n // Apped EC codewords\n for (i = 0; i < ecCount; i++) {\n for (r = 0; r < ecTotalBlocks; r++) {\n data[index++] = ecData[r][i]\n }\n }\n\n return data\n}\n\n/**\n * Build QR Code symbol\n *\n * @param {String} data Input string\n * @param {Number} version QR Code version\n * @param {ErrorCorretionLevel} errorCorrectionLevel Error level\n * @param {MaskPattern} maskPattern Mask pattern\n * @return {Object} Object containing symbol data\n */\nfunction createSymbol (data, version, errorCorrectionLevel, maskPattern) {\n let segments\n\n if (Array.isArray(data)) {\n segments = Segments.fromArray(data)\n } else if (typeof data === 'string') {\n let estimatedVersion = version\n\n if (!estimatedVersion) {\n const rawSegments = Segments.rawSplit(data)\n\n // Estimate best version that can contain raw splitted segments\n estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel)\n }\n\n // Build optimized segments\n // If estimated version is undefined, try with the highest version\n segments = Segments.fromString(data, estimatedVersion || 40)\n } else {\n throw new Error('Invalid data')\n }\n\n // Get the min version that can contain data\n const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)\n\n // If no version is found, data cannot be stored\n if (!bestVersion) {\n throw new Error('The amount of data is too big to be stored in a QR Code')\n }\n\n // If not specified, use min version as default\n if (!version) {\n version = bestVersion\n\n // Check if the specified version can contain the data\n } else if (version < bestVersion) {\n throw new Error('\\n' +\n 'The chosen QR Code version cannot contain this amount of data.\\n' +\n 'Minimum version required to store current data is: ' + bestVersion + '.\\n'\n )\n }\n\n const dataBits = createData(version, errorCorrectionLevel, segments)\n\n // Allocate matrix buffer\n const moduleCount = Utils.getSymbolSize(version)\n const modules = new BitMatrix(moduleCount)\n\n // Add function modules\n setupFinderPattern(modules, version)\n setupTimingPattern(modules)\n setupAlignmentPattern(modules, version)\n\n // Add temporary dummy bits for format info just to set them as reserved.\n // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}\n // since the masking operation must be performed only on the encoding region.\n // These blocks will be replaced with correct values later in code.\n setupFormatInfo(modules, errorCorrectionLevel, 0)\n\n if (version >= 7) {\n setupVersionInfo(modules, version)\n }\n\n // Add data codewords\n setupData(modules, dataBits)\n\n if (isNaN(maskPattern)) {\n // Find best mask pattern\n maskPattern = MaskPattern.getBestMask(modules,\n setupFormatInfo.bind(null, modules, errorCorrectionLevel))\n }\n\n // Apply mask pattern\n MaskPattern.applyMask(maskPattern, modules)\n\n // Replace format info bits with correct values\n setupFormatInfo(modules, errorCorrectionLevel, maskPattern)\n\n return {\n modules: modules,\n version: version,\n errorCorrectionLevel: errorCorrectionLevel,\n maskPattern: maskPattern,\n segments: segments\n }\n}\n\n/**\n * QR Code\n *\n * @param {String | Array} data Input data\n * @param {Object} options Optional configurations\n * @param {Number} options.version QR Code version\n * @param {String} options.errorCorrectionLevel Error correction level\n * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis\n */\nexports.create = function create (data, options) {\n if (typeof data === 'undefined' || data === '') {\n throw new Error('No input text')\n }\n\n let errorCorrectionLevel = ECLevel.M\n let version\n let mask\n\n if (typeof options !== 'undefined') {\n // Use higher error correction level as default\n errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)\n version = Version.from(options.version)\n mask = MaskPattern.from(options.maskPattern)\n\n if (options.toSJISFunc) {\n Utils.setToSJISFunction(options.toSJISFunc)\n }\n }\n\n return createSymbol(data, version, errorCorrectionLevel, mask)\n}\n", "function hex2rgba (hex) {\n if (typeof hex === 'number') {\n hex = hex.toString()\n }\n\n if (typeof hex !== 'string') {\n throw new Error('Color should be defined as hex string')\n }\n\n let hexCode = hex.slice().replace('#', '').split('')\n if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {\n throw new Error('Invalid hex color: ' + hex)\n }\n\n // Convert from short to long form (fff -> ffffff)\n if (hexCode.length === 3 || hexCode.length === 4) {\n hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {\n return [c, c]\n }))\n }\n\n // Add default alpha value\n if (hexCode.length === 6) hexCode.push('F', 'F')\n\n const hexValue = parseInt(hexCode.join(''), 16)\n\n return {\n r: (hexValue >> 24) & 255,\n g: (hexValue >> 16) & 255,\n b: (hexValue >> 8) & 255,\n a: hexValue & 255,\n hex: '#' + hexCode.slice(0, 6).join('')\n }\n}\n\nexports.getOptions = function getOptions (options) {\n if (!options) options = {}\n if (!options.color) options.color = {}\n\n const margin = typeof options.margin === 'undefined' ||\n options.margin === null ||\n options.margin < 0\n ? 4\n : options.margin\n\n const width = options.width && options.width >= 21 ? options.width : undefined\n const scale = options.scale || 4\n\n return {\n width: width,\n scale: width ? 4 : scale,\n margin: margin,\n color: {\n dark: hex2rgba(options.color.dark || '#000000ff'),\n light: hex2rgba(options.color.light || '#ffffffff')\n },\n type: options.type,\n rendererOpts: options.rendererOpts || {}\n }\n}\n\nexports.getScale = function getScale (qrSize, opts) {\n return opts.width && opts.width >= qrSize + opts.margin * 2\n ? opts.width / (qrSize + opts.margin * 2)\n : opts.scale\n}\n\nexports.getImageWidth = function getImageWidth (qrSize, opts) {\n const scale = exports.getScale(qrSize, opts)\n return Math.floor((qrSize + opts.margin * 2) * scale)\n}\n\nexports.qrToImageData = function qrToImageData (imgData, qr, opts) {\n const size = qr.modules.size\n const data = qr.modules.data\n const scale = exports.getScale(size, opts)\n const symbolSize = Math.floor((size + opts.margin * 2) * scale)\n const scaledMargin = opts.margin * scale\n const palette = [opts.color.light, opts.color.dark]\n\n for (let i = 0; i < symbolSize; i++) {\n for (let j = 0; j < symbolSize; j++) {\n let posDst = (i * symbolSize + j) * 4\n let pxColor = opts.color.light\n\n if (i >= scaledMargin && j >= scaledMargin &&\n i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {\n const iSrc = Math.floor((i - scaledMargin) / scale)\n const jSrc = Math.floor((j - scaledMargin) / scale)\n pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]\n }\n\n imgData[posDst++] = pxColor.r\n imgData[posDst++] = pxColor.g\n imgData[posDst++] = pxColor.b\n imgData[posDst] = pxColor.a\n }\n }\n}\n", "const Utils = require('./utils')\n\nfunction clearCanvas (ctx, canvas, size) {\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n if (!canvas.style) canvas.style = {}\n canvas.height = size\n canvas.width = size\n canvas.style.height = size + 'px'\n canvas.style.width = size + 'px'\n}\n\nfunction getCanvasElement () {\n try {\n return document.createElement('canvas')\n } catch (e) {\n throw new Error('You need to specify a canvas element')\n }\n}\n\nexports.render = function render (qrData, canvas, options) {\n let opts = options\n let canvasEl = canvas\n\n if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n opts = canvas\n canvas = undefined\n }\n\n if (!canvas) {\n canvasEl = getCanvasElement()\n }\n\n opts = Utils.getOptions(opts)\n const size = Utils.getImageWidth(qrData.modules.size, opts)\n\n const ctx = canvasEl.getContext('2d')\n const image = ctx.createImageData(size, size)\n Utils.qrToImageData(image.data, qrData, opts)\n\n clearCanvas(ctx, canvasEl, size)\n ctx.putImageData(image, 0, 0)\n\n return canvasEl\n}\n\nexports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {\n let opts = options\n\n if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n opts = canvas\n canvas = undefined\n }\n\n if (!opts) opts = {}\n\n const canvasEl = exports.render(qrData, canvas, opts)\n\n const type = opts.type || 'image/png'\n const rendererOpts = opts.rendererOpts || {}\n\n return canvasEl.toDataURL(type, rendererOpts.quality)\n}\n", "const Utils = require('./utils')\n\nfunction getColorAttrib (color, attrib) {\n const alpha = color.a / 255\n const str = attrib + '=\"' + color.hex + '\"'\n\n return alpha < 1\n ? str + ' ' + attrib + '-opacity=\"' + alpha.toFixed(2).slice(1) + '\"'\n : str\n}\n\nfunction svgCmd (cmd, x, y) {\n let str = cmd + x\n if (typeof y !== 'undefined') str += ' ' + y\n\n return str\n}\n\nfunction qrToPath (data, size, margin) {\n let path = ''\n let moveBy = 0\n let newRow = false\n let lineLength = 0\n\n for (let i = 0; i < data.length; i++) {\n const col = Math.floor(i % size)\n const row = Math.floor(i / size)\n\n if (!col && !newRow) newRow = true\n\n if (data[i]) {\n lineLength++\n\n if (!(i > 0 && col > 0 && data[i - 1])) {\n path += newRow\n ? svgCmd('M', col + margin, 0.5 + row + margin)\n : svgCmd('m', moveBy, 0)\n\n moveBy = 0\n newRow = false\n }\n\n if (!(col + 1 < size && data[i + 1])) {\n path += svgCmd('h', lineLength)\n lineLength = 0\n }\n } else {\n moveBy++\n }\n }\n\n return path\n}\n\nexports.render = function render (qrData, options, cb) {\n const opts = Utils.getOptions(options)\n const size = qrData.modules.size\n const data = qrData.modules.data\n const qrcodesize = size + opts.margin * 2\n\n const bg = !opts.color.light.a\n ? ''\n : ''\n\n const path =\n ''\n\n const viewBox = 'viewBox=\"' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '\"'\n\n const width = !opts.width ? '' : 'width=\"' + opts.width + '\" height=\"' + opts.width + '\" '\n\n const svgTag = '' + bg + path + '\\n'\n\n if (typeof cb === 'function') {\n cb(null, svgTag)\n }\n\n return svgTag\n}\n", "\nconst canPromise = require('./can-promise')\n\nconst QRCode = require('./core/qrcode')\nconst CanvasRenderer = require('./renderer/canvas')\nconst SvgRenderer = require('./renderer/svg-tag.js')\n\nfunction renderCanvas (renderFunc, canvas, text, opts, cb) {\n const args = [].slice.call(arguments, 1)\n const argsNum = args.length\n const isLastArgCb = typeof args[argsNum - 1] === 'function'\n\n if (!isLastArgCb && !canPromise()) {\n throw new Error('Callback required as last argument')\n }\n\n if (isLastArgCb) {\n if (argsNum < 2) {\n throw new Error('Too few arguments provided')\n }\n\n if (argsNum === 2) {\n cb = text\n text = canvas\n canvas = opts = undefined\n } else if (argsNum === 3) {\n if (canvas.getContext && typeof cb === 'undefined') {\n cb = opts\n opts = undefined\n } else {\n cb = opts\n opts = text\n text = canvas\n canvas = undefined\n }\n }\n } else {\n if (argsNum < 1) {\n throw new Error('Too few arguments provided')\n }\n\n if (argsNum === 1) {\n text = canvas\n canvas = opts = undefined\n } else if (argsNum === 2 && !canvas.getContext) {\n opts = text\n text = canvas\n canvas = undefined\n }\n\n return new Promise(function (resolve, reject) {\n try {\n const data = QRCode.create(text, opts)\n resolve(renderFunc(data, canvas, opts))\n } catch (e) {\n reject(e)\n }\n })\n }\n\n try {\n const data = QRCode.create(text, opts)\n cb(null, renderFunc(data, canvas, opts))\n } catch (e) {\n cb(e)\n }\n}\n\nexports.create = QRCode.create\nexports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)\nexports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)\n\n// only svg for now.\nexports.toString = renderCanvas.bind(null, function (data, _, opts) {\n return SvgRenderer.render(data, opts)\n})\n", "/*!\n * Compressor.js v1.2.1\n * https://fengyuanchen.github.io/compressorjs\n *\n * Copyright 2018-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2023-02-28T14:09:41.732Z\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Compressor = factory());\n})(this, (function () { 'use strict';\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n return keys;\n }\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n }\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);\n }\n }\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n }\n function _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n }\n function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n }\n function _toPrimitive(input, hint) {\n if (typeof input !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (typeof res !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n }\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n }\n\n var canvasToBlob = {exports: {}};\n\n /*\n * JavaScript Canvas to Blob\n * https://github.com/blueimp/JavaScript-Canvas-to-Blob\n *\n * Copyright 2012, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on stackoverflow user Stoive's code snippet:\n * http://stackoverflow.com/q/4998908\n */\n (function (module) {\n if (typeof window === 'undefined') {\n return;\n }\n (function (window) {\n\n var CanvasPrototype = window.HTMLCanvasElement && window.HTMLCanvasElement.prototype;\n var hasBlobConstructor = window.Blob && function () {\n try {\n return Boolean(new Blob());\n } catch (e) {\n return false;\n }\n }();\n var hasArrayBufferViewSupport = hasBlobConstructor && window.Uint8Array && function () {\n try {\n return new Blob([new Uint8Array(100)]).size === 100;\n } catch (e) {\n return false;\n }\n }();\n var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;\n var dataURIPattern = /^data:((.*?)(;charset=.*?)?)(;base64)?,/;\n var dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array && function (dataURI) {\n var matches, mediaType, isBase64, dataString, byteString, arrayBuffer, intArray, i, bb;\n // Parse the dataURI components as per RFC 2397\n matches = dataURI.match(dataURIPattern);\n if (!matches) {\n throw new Error('invalid data URI');\n }\n // Default to text/plain;charset=US-ASCII\n mediaType = matches[2] ? matches[1] : 'text/plain' + (matches[3] || ';charset=US-ASCII');\n isBase64 = !!matches[4];\n dataString = dataURI.slice(matches[0].length);\n if (isBase64) {\n // Convert base64 to raw binary data held in a string:\n byteString = atob(dataString);\n } else {\n // Convert base64/URLEncoded data component to raw binary:\n byteString = decodeURIComponent(dataString);\n }\n // Write the bytes of the string to an ArrayBuffer:\n arrayBuffer = new ArrayBuffer(byteString.length);\n intArray = new Uint8Array(arrayBuffer);\n for (i = 0; i < byteString.length; i += 1) {\n intArray[i] = byteString.charCodeAt(i);\n }\n // Write the ArrayBuffer (or ArrayBufferView) to a blob:\n if (hasBlobConstructor) {\n return new Blob([hasArrayBufferViewSupport ? intArray : arrayBuffer], {\n type: mediaType\n });\n }\n bb = new BlobBuilder();\n bb.append(arrayBuffer);\n return bb.getBlob(mediaType);\n };\n if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {\n if (CanvasPrototype.mozGetAsFile) {\n CanvasPrototype.toBlob = function (callback, type, quality) {\n var self = this;\n setTimeout(function () {\n if (quality && CanvasPrototype.toDataURL && dataURLtoBlob) {\n callback(dataURLtoBlob(self.toDataURL(type, quality)));\n } else {\n callback(self.mozGetAsFile('blob', type));\n }\n });\n };\n } else if (CanvasPrototype.toDataURL && dataURLtoBlob) {\n if (CanvasPrototype.msToBlob) {\n CanvasPrototype.toBlob = function (callback, type, quality) {\n var self = this;\n setTimeout(function () {\n if ((type && type !== 'image/png' || quality) && CanvasPrototype.toDataURL && dataURLtoBlob) {\n callback(dataURLtoBlob(self.toDataURL(type, quality)));\n } else {\n callback(self.msToBlob(type));\n }\n });\n };\n } else {\n CanvasPrototype.toBlob = function (callback, type, quality) {\n var self = this;\n setTimeout(function () {\n callback(dataURLtoBlob(self.toDataURL(type, quality)));\n });\n };\n }\n }\n }\n if (module.exports) {\n module.exports = dataURLtoBlob;\n } else {\n window.dataURLtoBlob = dataURLtoBlob;\n }\n })(window);\n })(canvasToBlob);\n var toBlob = canvasToBlob.exports;\n\n var isBlob = function isBlob(value) {\n if (typeof Blob === 'undefined') {\n return false;\n }\n return value instanceof Blob || Object.prototype.toString.call(value) === '[object Blob]';\n };\n\n var DEFAULTS = {\n /**\n * Indicates if output the original image instead of the compressed one\n * when the size of the compressed image is greater than the original one's\n * @type {boolean}\n */\n strict: true,\n /**\n * Indicates if read the image's Exif Orientation information,\n * and then rotate or flip the image automatically.\n * @type {boolean}\n */\n checkOrientation: true,\n /**\n * Indicates if retain the image's Exif information after compressed.\n * @type {boolean}\n */\n retainExif: false,\n /**\n * The max width of the output image.\n * @type {number}\n */\n maxWidth: Infinity,\n /**\n * The max height of the output image.\n * @type {number}\n */\n maxHeight: Infinity,\n /**\n * The min width of the output image.\n * @type {number}\n */\n minWidth: 0,\n /**\n * The min height of the output image.\n * @type {number}\n */\n minHeight: 0,\n /**\n * The width of the output image.\n * If not specified, the natural width of the source image will be used.\n * @type {number}\n */\n width: undefined,\n /**\n * The height of the output image.\n * If not specified, the natural height of the source image will be used.\n * @type {number}\n */\n height: undefined,\n /**\n * Sets how the size of the image should be resized to the container\n * specified by the `width` and `height` options.\n * @type {string}\n */\n resize: 'none',\n /**\n * The quality of the output image.\n * It must be a number between `0` and `1`,\n * and only available for `image/jpeg` and `image/webp` images.\n * Check out {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob canvas.toBlob}.\n * @type {number}\n */\n quality: 0.8,\n /**\n * The mime type of the output image.\n * By default, the original mime type of the source image file will be used.\n * @type {string}\n */\n mimeType: 'auto',\n /**\n * Files whose file type is included in this list,\n * and whose file size exceeds the `convertSize` value will be converted to JPEGs.\n * @type {string\uFF5CArray}\n */\n convertTypes: ['image/png'],\n /**\n * PNG files over this size (5 MB by default) will be converted to JPEGs.\n * To disable this, just set the value to `Infinity`.\n * @type {number}\n */\n convertSize: 5000000,\n /**\n * The hook function to execute before draw the image into the canvas for compression.\n * @type {Function}\n * @param {CanvasRenderingContext2D} context - The 2d rendering context of the canvas.\n * @param {HTMLCanvasElement} canvas - The canvas for compression.\n * @example\n * function (context, canvas) {\n * context.fillStyle = '#fff';\n * }\n */\n beforeDraw: null,\n /**\n * The hook function to execute after drew the image into the canvas for compression.\n * @type {Function}\n * @param {CanvasRenderingContext2D} context - The 2d rendering context of the canvas.\n * @param {HTMLCanvasElement} canvas - The canvas for compression.\n * @example\n * function (context, canvas) {\n * context.filter = 'grayscale(100%)';\n * }\n */\n drew: null,\n /**\n * The hook function to execute when success to compress the image.\n * @type {Function}\n * @param {File} file - The compressed image File object.\n * @example\n * function (file) {\n * console.log(file);\n * }\n */\n success: null,\n /**\n * The hook function to execute when fail to compress the image.\n * @type {Function}\n * @param {Error} err - An Error object.\n * @example\n * function (err) {\n * console.log(err.message);\n * }\n */\n error: null\n };\n\n var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n var WINDOW = IS_BROWSER ? window : {};\n\n /**\n * Check if the given value is a positive number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.\n */\n var isPositiveNumber = function isPositiveNumber(value) {\n return value > 0 && value < Infinity;\n };\n var slice = Array.prototype.slice;\n\n /**\n * Convert array-like or iterable object to an array.\n * @param {*} value - The value to convert.\n * @returns {Array} Returns a new array.\n */\n function toArray(value) {\n return Array.from ? Array.from(value) : slice.call(value);\n }\n var REGEXP_IMAGE_TYPE = /^image\\/.+$/;\n\n /**\n * Check if the given value is a mime type of image.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given is a mime type of image, else `false`.\n */\n function isImageType(value) {\n return REGEXP_IMAGE_TYPE.test(value);\n }\n\n /**\n * Convert image type to extension.\n * @param {string} value - The image type to convert.\n * @returns {boolean} Returns the image extension.\n */\n function imageTypeToExtension(value) {\n var extension = isImageType(value) ? value.substr(6) : '';\n if (extension === 'jpeg') {\n extension = 'jpg';\n }\n return \".\".concat(extension);\n }\n var fromCharCode = String.fromCharCode;\n\n /**\n * Get string from char code in data view.\n * @param {DataView} dataView - The data view for read.\n * @param {number} start - The start index.\n * @param {number} length - The read length.\n * @returns {string} The read result.\n */\n function getStringFromCharCode(dataView, start, length) {\n var str = '';\n var i;\n length += start;\n for (i = start; i < length; i += 1) {\n str += fromCharCode(dataView.getUint8(i));\n }\n return str;\n }\n var btoa = WINDOW.btoa;\n\n /**\n * Transform array buffer to Data URL.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {string} mimeType - The mime type of the Data URL.\n * @returns {string} The result Data URL.\n */\n function arrayBufferToDataURL(arrayBuffer, mimeType) {\n var chunks = [];\n var chunkSize = 8192;\n var uint8 = new Uint8Array(arrayBuffer);\n while (uint8.length > 0) {\n // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9\n // eslint-disable-next-line prefer-spread\n chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));\n uint8 = uint8.subarray(chunkSize);\n }\n return \"data:\".concat(mimeType, \";base64,\").concat(btoa(chunks.join('')));\n }\n\n /**\n * Get orientation value from given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {number} The read orientation value.\n */\n function resetAndGetOrientation(arrayBuffer) {\n var dataView = new DataView(arrayBuffer);\n var orientation;\n\n // Ignores range error when the image does not have correct Exif information\n try {\n var littleEndian;\n var app1Start;\n var ifdStart;\n\n // Only handle JPEG image (start by 0xFFD8)\n if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {\n var length = dataView.byteLength;\n var offset = 2;\n while (offset + 1 < length) {\n if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {\n app1Start = offset;\n break;\n }\n offset += 1;\n }\n }\n if (app1Start) {\n var exifIDCode = app1Start + 4;\n var tiffOffset = app1Start + 10;\n if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {\n var endianness = dataView.getUint16(tiffOffset);\n littleEndian = endianness === 0x4949;\n if (littleEndian || endianness === 0x4D4D /* bigEndian */) {\n if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {\n var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);\n if (firstIFDOffset >= 0x00000008) {\n ifdStart = tiffOffset + firstIFDOffset;\n }\n }\n }\n }\n }\n if (ifdStart) {\n var _length = dataView.getUint16(ifdStart, littleEndian);\n var _offset;\n var i;\n for (i = 0; i < _length; i += 1) {\n _offset = ifdStart + i * 12 + 2;\n if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {\n // 8 is the offset of the current tag's value\n _offset += 8;\n\n // Get the original orientation value\n orientation = dataView.getUint16(_offset, littleEndian);\n\n // Override the orientation with its default value\n dataView.setUint16(_offset, 1, littleEndian);\n break;\n }\n }\n }\n } catch (e) {\n orientation = 1;\n }\n return orientation;\n }\n\n /**\n * Parse Exif Orientation value.\n * @param {number} orientation - The orientation to parse.\n * @returns {Object} The parsed result.\n */\n function parseOrientation(orientation) {\n var rotate = 0;\n var scaleX = 1;\n var scaleY = 1;\n switch (orientation) {\n // Flip horizontal\n case 2:\n scaleX = -1;\n break;\n\n // Rotate left 180\u00B0\n case 3:\n rotate = -180;\n break;\n\n // Flip vertical\n case 4:\n scaleY = -1;\n break;\n\n // Flip vertical and rotate right 90\u00B0\n case 5:\n rotate = 90;\n scaleY = -1;\n break;\n\n // Rotate right 90\u00B0\n case 6:\n rotate = 90;\n break;\n\n // Flip horizontal and rotate right 90\u00B0\n case 7:\n rotate = 90;\n scaleX = -1;\n break;\n\n // Rotate left 90\u00B0\n case 8:\n rotate = -90;\n break;\n }\n return {\n rotate: rotate,\n scaleX: scaleX,\n scaleY: scaleY\n };\n }\n var REGEXP_DECIMALS = /\\.\\d*(?:0|9){12}\\d*$/;\n\n /**\n * Normalize decimal number.\n * Check out {@link https://0.30000000000000004.com/}\n * @param {number} value - The value to normalize.\n * @param {number} [times=100000000000] - The times for normalizing.\n * @returns {number} Returns the normalized number.\n */\n function normalizeDecimalNumber(value) {\n var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;\n return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;\n }\n\n /**\n * Get the max sizes in a rectangle under the given aspect ratio.\n * @param {Object} data - The original sizes.\n * @param {string} [type='contain'] - The adjust type.\n * @returns {Object} The result sizes.\n */\n function getAdjustedSizes(_ref) {\n var aspectRatio = _ref.aspectRatio,\n height = _ref.height,\n width = _ref.width;\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'none';\n var isValidWidth = isPositiveNumber(width);\n var isValidHeight = isPositiveNumber(height);\n if (isValidWidth && isValidHeight) {\n var adjustedWidth = height * aspectRatio;\n if ((type === 'contain' || type === 'none') && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {\n height = width / aspectRatio;\n } else {\n width = height * aspectRatio;\n }\n } else if (isValidWidth) {\n height = width / aspectRatio;\n } else if (isValidHeight) {\n width = height * aspectRatio;\n }\n return {\n width: width,\n height: height\n };\n }\n\n /**\n * Get Exif information from the given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {Array} The read Exif information.\n */\n function getExif(arrayBuffer) {\n var array = toArray(new Uint8Array(arrayBuffer));\n var length = array.length;\n var segments = [];\n var start = 0;\n while (start + 3 < length) {\n var value = array[start];\n var next = array[start + 1];\n\n // SOS (Start of Scan)\n if (value === 0xFF && next === 0xDA) {\n break;\n }\n\n // SOI (Start of Image)\n if (value === 0xFF && next === 0xD8) {\n start += 2;\n } else {\n var offset = array[start + 2] * 256 + array[start + 3];\n var end = start + offset + 2;\n var segment = array.slice(start, end);\n segments.push(segment);\n start = end;\n }\n }\n return segments.reduce(function (exifArray, current) {\n if (current[0] === 0xFF && current[1] === 0xE1) {\n return exifArray.concat(current);\n }\n return exifArray;\n }, []);\n }\n\n /**\n * Insert Exif information into the given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {Array} exifArray - The Exif information to insert.\n * @returns {ArrayBuffer} The transformed array buffer.\n */\n function insertExif(arrayBuffer, exifArray) {\n var array = toArray(new Uint8Array(arrayBuffer));\n if (array[2] !== 0xFF || array[3] !== 0xE0) {\n return arrayBuffer;\n }\n var app0Length = array[4] * 256 + array[5];\n var newArrayBuffer = [0xFF, 0xD8].concat(exifArray, array.slice(4 + app0Length));\n return new Uint8Array(newArrayBuffer);\n }\n\n var ArrayBuffer$1 = WINDOW.ArrayBuffer,\n FileReader = WINDOW.FileReader;\n var URL = WINDOW.URL || WINDOW.webkitURL;\n var REGEXP_EXTENSION = /\\.\\w+$/;\n var AnotherCompressor = WINDOW.Compressor;\n\n /**\n * Creates a new image compressor.\n * @class\n */\n var Compressor = /*#__PURE__*/function () {\n /**\n * The constructor of Compressor.\n * @param {File|Blob} file - The target image file for compressing.\n * @param {Object} [options] - The options for compressing.\n */\n function Compressor(file, options) {\n _classCallCheck(this, Compressor);\n this.file = file;\n this.exif = [];\n this.image = new Image();\n this.options = _objectSpread2(_objectSpread2({}, DEFAULTS), options);\n this.aborted = false;\n this.result = null;\n this.init();\n }\n _createClass(Compressor, [{\n key: \"init\",\n value: function init() {\n var _this = this;\n var file = this.file,\n options = this.options;\n if (!isBlob(file)) {\n this.fail(new Error('The first argument must be a File or Blob object.'));\n return;\n }\n var mimeType = file.type;\n if (!isImageType(mimeType)) {\n this.fail(new Error('The first argument must be an image File or Blob object.'));\n return;\n }\n if (!URL || !FileReader) {\n this.fail(new Error('The current browser does not support image compression.'));\n return;\n }\n if (!ArrayBuffer$1) {\n options.checkOrientation = false;\n options.retainExif = false;\n }\n var isJPEGImage = mimeType === 'image/jpeg';\n var checkOrientation = isJPEGImage && options.checkOrientation;\n var retainExif = isJPEGImage && options.retainExif;\n if (URL && !checkOrientation && !retainExif) {\n this.load({\n url: URL.createObjectURL(file)\n });\n } else {\n var reader = new FileReader();\n this.reader = reader;\n reader.onload = function (_ref) {\n var target = _ref.target;\n var result = target.result;\n var data = {};\n var orientation = 1;\n if (checkOrientation) {\n // Reset the orientation value to its default value 1\n // as some iOS browsers will render image with its orientation\n orientation = resetAndGetOrientation(result);\n if (orientation > 1) {\n _extends(data, parseOrientation(orientation));\n }\n }\n if (retainExif) {\n _this.exif = getExif(result);\n }\n if (checkOrientation || retainExif) {\n if (!URL\n\n // Generate a new URL with the default orientation value 1.\n || orientation > 1) {\n data.url = arrayBufferToDataURL(result, mimeType);\n } else {\n data.url = URL.createObjectURL(file);\n }\n } else {\n data.url = result;\n }\n _this.load(data);\n };\n reader.onabort = function () {\n _this.fail(new Error('Aborted to read the image with FileReader.'));\n };\n reader.onerror = function () {\n _this.fail(new Error('Failed to read the image with FileReader.'));\n };\n reader.onloadend = function () {\n _this.reader = null;\n };\n if (checkOrientation || retainExif) {\n reader.readAsArrayBuffer(file);\n } else {\n reader.readAsDataURL(file);\n }\n }\n }\n }, {\n key: \"load\",\n value: function load(data) {\n var _this2 = this;\n var file = this.file,\n image = this.image;\n image.onload = function () {\n _this2.draw(_objectSpread2(_objectSpread2({}, data), {}, {\n naturalWidth: image.naturalWidth,\n naturalHeight: image.naturalHeight\n }));\n };\n image.onabort = function () {\n _this2.fail(new Error('Aborted to load the image.'));\n };\n image.onerror = function () {\n _this2.fail(new Error('Failed to load the image.'));\n };\n\n // Match all browsers that use WebKit as the layout engine in iOS devices,\n // such as Safari for iOS, Chrome for iOS, and in-app browsers.\n if (WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent)) {\n // Fix the `The operation is insecure` error (#57)\n image.crossOrigin = 'anonymous';\n }\n image.alt = file.name;\n image.src = data.url;\n }\n }, {\n key: \"draw\",\n value: function draw(_ref2) {\n var _this3 = this;\n var naturalWidth = _ref2.naturalWidth,\n naturalHeight = _ref2.naturalHeight,\n _ref2$rotate = _ref2.rotate,\n rotate = _ref2$rotate === void 0 ? 0 : _ref2$rotate,\n _ref2$scaleX = _ref2.scaleX,\n scaleX = _ref2$scaleX === void 0 ? 1 : _ref2$scaleX,\n _ref2$scaleY = _ref2.scaleY,\n scaleY = _ref2$scaleY === void 0 ? 1 : _ref2$scaleY;\n var file = this.file,\n image = this.image,\n options = this.options;\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n var is90DegreesRotated = Math.abs(rotate) % 180 === 90;\n var resizable = (options.resize === 'contain' || options.resize === 'cover') && isPositiveNumber(options.width) && isPositiveNumber(options.height);\n var maxWidth = Math.max(options.maxWidth, 0) || Infinity;\n var maxHeight = Math.max(options.maxHeight, 0) || Infinity;\n var minWidth = Math.max(options.minWidth, 0) || 0;\n var minHeight = Math.max(options.minHeight, 0) || 0;\n var aspectRatio = naturalWidth / naturalHeight;\n var width = options.width,\n height = options.height;\n if (is90DegreesRotated) {\n var _ref3 = [maxHeight, maxWidth];\n maxWidth = _ref3[0];\n maxHeight = _ref3[1];\n var _ref4 = [minHeight, minWidth];\n minWidth = _ref4[0];\n minHeight = _ref4[1];\n var _ref5 = [height, width];\n width = _ref5[0];\n height = _ref5[1];\n }\n if (resizable) {\n aspectRatio = width / height;\n }\n var _getAdjustedSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: maxWidth,\n height: maxHeight\n }, 'contain');\n maxWidth = _getAdjustedSizes.width;\n maxHeight = _getAdjustedSizes.height;\n var _getAdjustedSizes2 = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: minWidth,\n height: minHeight\n }, 'cover');\n minWidth = _getAdjustedSizes2.width;\n minHeight = _getAdjustedSizes2.height;\n if (resizable) {\n var _getAdjustedSizes3 = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: width,\n height: height\n }, options.resize);\n width = _getAdjustedSizes3.width;\n height = _getAdjustedSizes3.height;\n } else {\n var _getAdjustedSizes4 = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: width,\n height: height\n });\n var _getAdjustedSizes4$wi = _getAdjustedSizes4.width;\n width = _getAdjustedSizes4$wi === void 0 ? naturalWidth : _getAdjustedSizes4$wi;\n var _getAdjustedSizes4$he = _getAdjustedSizes4.height;\n height = _getAdjustedSizes4$he === void 0 ? naturalHeight : _getAdjustedSizes4$he;\n }\n width = Math.floor(normalizeDecimalNumber(Math.min(Math.max(width, minWidth), maxWidth)));\n height = Math.floor(normalizeDecimalNumber(Math.min(Math.max(height, minHeight), maxHeight)));\n var destX = -width / 2;\n var destY = -height / 2;\n var destWidth = width;\n var destHeight = height;\n var params = [];\n if (resizable) {\n var srcX = 0;\n var srcY = 0;\n var srcWidth = naturalWidth;\n var srcHeight = naturalHeight;\n var _getAdjustedSizes5 = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: naturalWidth,\n height: naturalHeight\n }, {\n contain: 'cover',\n cover: 'contain'\n }[options.resize]);\n srcWidth = _getAdjustedSizes5.width;\n srcHeight = _getAdjustedSizes5.height;\n srcX = (naturalWidth - srcWidth) / 2;\n srcY = (naturalHeight - srcHeight) / 2;\n params.push(srcX, srcY, srcWidth, srcHeight);\n }\n params.push(destX, destY, destWidth, destHeight);\n if (is90DegreesRotated) {\n var _ref6 = [height, width];\n width = _ref6[0];\n height = _ref6[1];\n }\n canvas.width = width;\n canvas.height = height;\n if (!isImageType(options.mimeType)) {\n options.mimeType = file.type;\n }\n var fillStyle = 'transparent';\n\n // Converts PNG files over the `convertSize` to JPEGs.\n if (file.size > options.convertSize && options.convertTypes.indexOf(options.mimeType) >= 0) {\n options.mimeType = 'image/jpeg';\n }\n var isJPEGImage = options.mimeType === 'image/jpeg';\n if (isJPEGImage) {\n fillStyle = '#fff';\n }\n\n // Override the default fill color (#000, black)\n context.fillStyle = fillStyle;\n context.fillRect(0, 0, width, height);\n if (options.beforeDraw) {\n options.beforeDraw.call(this, context, canvas);\n }\n if (this.aborted) {\n return;\n }\n context.save();\n context.translate(width / 2, height / 2);\n context.rotate(rotate * Math.PI / 180);\n context.scale(scaleX, scaleY);\n context.drawImage.apply(context, [image].concat(params));\n context.restore();\n if (options.drew) {\n options.drew.call(this, context, canvas);\n }\n if (this.aborted) {\n return;\n }\n var callback = function callback(blob) {\n if (!_this3.aborted) {\n var done = function done(result) {\n return _this3.done({\n naturalWidth: naturalWidth,\n naturalHeight: naturalHeight,\n result: result\n });\n };\n if (blob && isJPEGImage && options.retainExif && _this3.exif && _this3.exif.length > 0) {\n var next = function next(arrayBuffer) {\n return done(toBlob(arrayBufferToDataURL(insertExif(arrayBuffer, _this3.exif), options.mimeType)));\n };\n if (blob.arrayBuffer) {\n blob.arrayBuffer().then(next).catch(function () {\n _this3.fail(new Error('Failed to read the compressed image with Blob.arrayBuffer().'));\n });\n } else {\n var reader = new FileReader();\n _this3.reader = reader;\n reader.onload = function (_ref7) {\n var target = _ref7.target;\n next(target.result);\n };\n reader.onabort = function () {\n _this3.fail(new Error('Aborted to read the compressed image with FileReader.'));\n };\n reader.onerror = function () {\n _this3.fail(new Error('Failed to read the compressed image with FileReader.'));\n };\n reader.onloadend = function () {\n _this3.reader = null;\n };\n reader.readAsArrayBuffer(blob);\n }\n } else {\n done(blob);\n }\n }\n };\n if (canvas.toBlob) {\n canvas.toBlob(callback, options.mimeType, options.quality);\n } else {\n callback(toBlob(canvas.toDataURL(options.mimeType, options.quality)));\n }\n }\n }, {\n key: \"done\",\n value: function done(_ref8) {\n var naturalWidth = _ref8.naturalWidth,\n naturalHeight = _ref8.naturalHeight,\n result = _ref8.result;\n var file = this.file,\n image = this.image,\n options = this.options;\n if (URL && image.src.indexOf('blob:') === 0) {\n URL.revokeObjectURL(image.src);\n }\n if (result) {\n // Returns original file if the result is greater than it and without size related options\n if (options.strict && !options.retainExif && result.size > file.size && options.mimeType === file.type && !(options.width > naturalWidth || options.height > naturalHeight || options.minWidth > naturalWidth || options.minHeight > naturalHeight || options.maxWidth < naturalWidth || options.maxHeight < naturalHeight)) {\n result = file;\n } else {\n var date = new Date();\n result.lastModified = date.getTime();\n result.lastModifiedDate = date;\n result.name = file.name;\n\n // Convert the extension to match its type\n if (result.name && result.type !== file.type) {\n result.name = result.name.replace(REGEXP_EXTENSION, imageTypeToExtension(result.type));\n }\n }\n } else {\n // Returns original file if the result is null in some cases.\n result = file;\n }\n this.result = result;\n if (options.success) {\n options.success.call(this, result);\n }\n }\n }, {\n key: \"fail\",\n value: function fail(err) {\n var options = this.options;\n if (options.error) {\n options.error.call(this, err);\n } else {\n throw err;\n }\n }\n }, {\n key: \"abort\",\n value: function abort() {\n if (!this.aborted) {\n this.aborted = true;\n if (this.reader) {\n this.reader.abort();\n } else if (!this.image.complete) {\n this.image.onload = null;\n this.image.onabort();\n } else {\n this.fail(new Error('The compression process has been aborted.'));\n }\n }\n }\n\n /**\n * Get the no conflict compressor class.\n * @returns {Compressor} The compressor class.\n */\n }], [{\n key: \"noConflict\",\n value: function noConflict() {\n window.Compressor = AnotherCompressor;\n return Compressor;\n }\n\n /**\n * Change the default options.\n * @param {Object} options - The new default options.\n */\n }, {\n key: \"setDefaults\",\n value: function setDefaults(options) {\n _extends(DEFAULTS, options);\n }\n }]);\n return Compressor;\n }();\n\n return Compressor;\n\n}));\n", "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = global || self, global.Alpine = factory());\n}(this, (function () { 'use strict';\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n }\n\n // Thanks @stimulus:\n // https://github.com/stimulusjs/stimulus/blob/master/packages/%40stimulus/core/src/application.ts\n function domReady() {\n return new Promise(resolve => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", resolve);\n } else {\n resolve();\n }\n });\n }\n function arrayUnique(array) {\n return Array.from(new Set(array));\n }\n function isTesting() {\n return navigator.userAgent.includes(\"Node.js\") || navigator.userAgent.includes(\"jsdom\");\n }\n function checkedAttrLooseCompare(valueA, valueB) {\n return valueA == valueB;\n }\n function warnIfMalformedTemplate(el, directive) {\n if (el.tagName.toLowerCase() !== 'template') {\n console.warn(`Alpine: [${directive}] directive should only be added to