/************************************************************************!
*
* ADOBE CONFIDENTIAL
* ___________________
*
* Copyright 2015-2020 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/!function(e){var t={};function i(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,i),o.l=!0,o.exports}i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)i.d(n,o,function(t){return e[t]}.bind(null,o));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=64)}([function(e,t,i){const n=i(19),o=i(29),r=i(7);var s,a={ENVIRONMENT:"production",SETTINGS_FILE:"settings.json",SETTINGS_FILE_VERSION:2,CC_SETTINGS_FILE:"C3Config.xml",CONSOLE_LOGGING:!1,SCOPES:"openid,AdobeID,creative_cloud,creative_sdk,cc_private,sao.cce_private",MAX_WS_PAYLOAD:209715200,MAX_LOG_SIZE:10485760,CORE_SYNC_REQUEST_TIMEOUT:5e3,CORE_SYNC_NUM_RETRIES:3,CORE_SYNC_NOTIFICATION_DEBOUNCE:500,ACCESS_TOKEN_CACHE_DURATION:6e5,SYNC_STATE_BROADCAST_THROTTLE:100,ANALYTICS_PROJECT:"cclib-process",ANALYTICS_INGEST_TYPE:"dunamis",ANALYTICS_DEFAULT_DEBOUNCE:1e4,ANALYTICS_DEBOUNCE:1e4,MAX_QUEUED_ANALYTICS:200,GET_ACTIVE_CLOUD_TIMEOUT:1e4,GET_NOTIFICATION_TIMEOUT:2e3,PROXY_REQUEST_TIMEOUT:2e3,ANALYTICS_STATE_REQUEST_TIMEOUT:2e3,ANALYTICS_STATE_REQUEST_RETRY_INTERVAL:5e3,ANALYTICS_STATE_REQUEST_MAX_RETRIES:2,CONFIGURE_SYNC_TIMEOUT:5e3,THOR_LAUNCH_WAIT:5e3,CORE_SYNC_ANALYTICS_WAIT:3e5,ANALYTICS_ERROR_HISTORY:5,CONNECTION_VALIDATION_INTERVAL:5e3,LAUNCH_APP_POLL_INTERVAL:5e3,LAUNCH_APP_TIMEOUT:3e5,SEND_ACTION_TIMEOUT:5e3,OS_TOAST_NOTIFICATIONS_BACKOFF:1e3,OS_TOAST_NOTIFICATIONS_DELAY:100,LOCAL_THUMBNAILS_SHUTDOWN_DELAY:5e3,VALIDATE_RENDITIONS_SIZE_THRESHOLD:1048576,FONT_WATCH_DEBOUNCE:1e3,FONT_WATCH_ERROR_DEBOUNCE_MIN:1e4,FONT_WATCH_ERROR_DEBOUNCE_MAX:3e5,FONT_WATCH_RESET:50,NGL_INITIALIZE_TIMEOUT:3e3,CDN_CACHE_ROOT:"/v1/",CDN_CACHE_FILE:"contents.json",CDN_REFRESH_INTERVAL:864e5,CDN_RETRY_INTERVAL:18e5,REST_API_VERSION:8,REST_API_MIN_VERSION:2,REST_API_MAX_VERSION:8,PRODUCT_LAUNCHER_SUPPORTED_PRODUCTS:{illustrator:"ILST",photoshop:"PHXS",indesign:"IDSN",premierepro:"PPRO",aftereffects:"AEFT",flash:"FLPR",euclid:"ESHR",creativecloud:"ACCC",adobedesktopservice:"ADCS"},PRODUCT_BRIDGE_ELEMENT_TYPES:["application/vnd.adobe.element.image+dcx","application/vnd.adobe.element.video+dcx","application/vnd.adobe.element.3d+dcx","application/vnd.adobe.element.template+dcx","application/vnd.adobe.element.text+dcx","application/vnd.adobe.element.animation+dcx","application/vnd.adobe.element.component+dcx","application/vnd.adobe.element.audio+dcx"],PRODUCT_BRIDGE_INMEMORY_LIFETIME:6e5,EXTERNAL_LINK_PREFETCH:{"application/vnd.adobe.element.video+dcx":!1},TEAM_REFRESH_INTERVAL:6e4,TEAM_HIDDEN_FOLDERS:["appdata"],PLATFORM_ROOT_DOCUMENT_TTL:2592e6,PLATFORM_ROOT_DOCUMENT_VERSION:1,STARTUP_TIME_FILE:".startup",MAX_STARTUP_TIMES:10,CRASH_DETECT_THRESHOLD:2e4,CRASH_RECOVERY_THRESHOLD:6e5},c={staging:{LABEL:"Staging",CLIENT_ID:"ProjectCentral16",CLIENT_SECRET:"5c597af3-e18a-41bc-8b65-82fd532e5f12",STORAGE_HOST:"cc-api-storage-stage.adobe.io",ACP_CS_HOST:"platform-cs-stage.adobe.io",ACP_CS_HOST_REGEX:/^https:\/\/platform-cs[a-zA-Z0-9\-.]*\.adobe\.io/,ORG_BETA_HOST:"org-beta.ccx-foundation.adobecc.com",CCWEB_HOST:"assets-stage.adobecc.com",CC_IMAGE_HOST:"cc-api-image-stage.adobe.io",CC_IMAGE_X_HOST:"cc-api-image-x-stage.adobe.io",PUBLIC_HOSTS:[{host:"public-stage.adobecc.com"},{host:"drakozoxj1229.cloudfront.net",community_platform:!0},{host:"cdn-stage.cp.adobe.io",community_platform:!0}],TYPEKIT_HOST:"cctypekit-relstage.adobe.io",IMS:"ims-na1-stg1.adobelogin.com",CC_LIBRARY_SERVICE_HOST:"ccx-melville-stage.adobe.io",SHA_CDN_HOST:"cclibraries-defaults-cdn.stage.adobe.com",INVITATIONS_HOST:"invitations-stage.adobe.io"},production:{LABEL:"Production",CLIENT_ID:"ProjectCentral16",CLIENT_SECRET:"1ba6923b-fc3d-4114-a506-f3bc5b34093a",STORAGE_HOST:"cc-api-storage.adobe.io",ACP_CS_HOST:"platform-cs.adobe.io",ACP_CS_HOST_REGEX:/^https:\/\/platform-cs[a-zA-Z0-9\-.]*\.adobe\.io/,ORG_BETA_HOST:"org-beta.ccx-foundation.adobecc.com",CCWEB_HOST:"creative.adobe.com",CC_IMAGE_HOST:"cc-api-image.adobe.io",CC_IMAGE_X_HOST:"cc-api-image-x.adobe.io",PUBLIC_HOSTS:[{host:"public.adobecc.com"},{host:"d35fgcharv2shj.cloudfront.net",community_platform:!0},{host:"cdn.cp.adobe.io",community_platform:!0}],TYPEKIT_HOST:"cctypekit.adobe.io",IMS:"ims-na1.adobelogin.com",CC_LIBRARY_SERVICE_HOST:"libraries.adobe.io",SHA_CDN_HOST:"cclibraries-defaults-cdn.adobe.com",INVITATIONS_HOST:"invitations.adobe.io"}};function l(){var e=!1;try{var t=n.readFileSync(a.CC_DIR+a.CC_SETTINGS_FILE,"utf8");new o.Parser({async:!1}).parseString(t,(function(t,i){t||i.C3Config.config[0].namespace.forEach(t=>{t&&t.$&&t.$.name&&"accc.container"===t.$.name&&t.property.forEach(t=>{t&&t.$&&t.$.name&&"IMS_ENV"===t.$.name&&"STG"===t._&&(e=!0)})})}))}catch(e){}return e}var h={SETTINGS_FILE_VERSION:a.SETTINGS_FILE_VERSION};function d(){var e=JSON.stringify(h,void 0,2);if(e===s)return!1;try{var t=a.SETTINGS_FILE+".TEMP_"+r();n.writeFileSync(a.ROOT_DIR+t,e),n.renameSync(a.ROOT_DIR+t,a.ROOT_DIR+a.SETTINGS_FILE),s=e}catch(e){}return!0}var _={};_._init=function(){if(_.isPlatformWindows()){var e=process.env.USERPROFILE.replace(/\\/g,"/");a.ROOT_DIR=e+"/AppData/Roaming/",a.LOG_DIR=process.env.TEMP.replace(/\\/g,"/")+"/CreativeCloud/Creative Cloud Libraries/",a.FONT_DIRS=[process.env.WINDIR.replace(/\\/g,"/")+"/Fonts",e+"/AppData/Roaming/Adobe/CoreSync/plugins/livetype/r"];const t=process.env.PROGRAMFILES.replace(/\\/g,"/"),i=(process.env["ProgramFiles(x86)"]||process.env.PROGRAMFILES).replace(/\\/g,"/");a.CC_DIR=`${i}/Adobe/Adobe Creative Cloud/`,a.DEFAULT_CONTENT_LOCATIONS=[`${t}/Adobe/Adobe Photoshop 2020/Required/`,`${t}/Adobe/Adobe Photoshop 2021/Required/`],a.FIREFOX_DIR=e+"/AppData/Roaming/Mozilla/Firefox/Profiles"}else a.ROOT_DIR=process.env.HOME+"/Library/Application Support/",a.LOG_DIR=process.env.HOME+"/Library/Logs/CreativeCloud/Creative Cloud Libraries/",a.FONT_DIRS=["/System/Library/Fonts","/Library/Fonts",process.env.HOME+"/Library/Fonts",process.env.HOME+"/Library/Application Support/Adobe/CoreSync/plugins/livetype/.r"],a.CC_DIR="/Applications/Utilities/Adobe Creative Cloud/",a.DEFAULT_CONTENT_LOCATIONS=["/Applications/Adobe Photoshop 2020/Adobe Photoshop 2020.app/Contents/Required/","/Applications/Adobe Photoshop 2021/Adobe Photoshop 2021.app/Contents/Required/"],a.FIREFOX_DIR=process.env.HOME+"/Library/Application Support/Firefox/Profiles";a.ROOT_DIR+="Adobe/Creative Cloud Libraries/LIBS/",function(){try{s=n.readFileSync(a.ROOT_DIR+a.SETTINGS_FILE,"utf8");var e=JSON.parse(s);h.SETTINGS_FILE_VERSION===e.SETTINGS_FILE_VERSION&&(h=e)}catch(e){}}(),l()&&(a.ENVIRONMENT="staging"),process.argv.forEach(e=>{"--debug"===e&&(a.CONSOLE_LOGGING=!0)}),a.CONSOLE_LOGGING||console.log(`Outputting logs to: ${a.LOG_DIR}\nTo view log messages on the console, use the --debug argument`),h.DISABLE_CERTIFICATE_CHECK?(console.warn("Disabling Certificate Check"),process.env.NODE_TLS_REJECT_UNAUTHORIZED=0):delete process.env.NODE_TLS_REJECT_UNAUTHORIZED},_.isPlatformWindows=function(){return 0===process.platform.indexOf("win")},_.isEnvironmentCorrect=function(){return a.ENVIRONMENT===(l()?"staging":"production")},_.getValue=function(e){return void 0!==h[e]?h[e]:a[e]},_.setValue=function(e,t){return h[e]=t,d()},_.getEnvironment=function(){var e=_.getValue("ENVIRONMENT");return c[e]||c[a.ENVIRONMENT]},_._getValidWSSTokens=function(){const e=(new Date).getTime();return(h.WSS_TOKENS||[]).filter(t=>t.expiry>e)},_.addWSSToken=function(e){const t=_._getValidWSSTokens();return t.push({value:e,expiry:(new Date).getTime()+15552e6}),h.WSS_TOKENS=t,d()},_.isWSSTokenValid=function(e){return _._getValidWSSTokens().some(t=>t.value===e)},_.validateAndLogStartupTimes=function(){const e=`${a.ROOT_DIR}/.startup`;let t=[];try{t=JSON.parse(n.readFileSync(e,"utf8"))}catch(e){}t.push(Date.now()),t.length>a.MAX_STARTUP_TIMES&&(t=t.slice(t.length-a.MAX_STARTUP_TIMES));try{n.writeFileSync(e,JSON.stringify(t),"utf8")}catch(e){}if(t.length<a.MAX_STARTUP_TIMES)return!0;return(t[t.length-1]-t[0])/(t.length-1)>=a.CRASH_DETECT_THRESHOLD},_.isInSafeMode=function(){return void 0!==process.send},_._init(),e.exports=_},function(e,t){var i=["INVALID_PARAMETER","READ_ONLY","NOT_IMPLEMENTED","NOT_SUPPORTED","REQUIRES_FILESYSTEM","DELETED_LOCALLY"];function n(e,t,o,r){if(-1!==i.indexOf(e))if(Error.call(this),Error.captureStackTrace)Error.captureStackTrace(this,n);else{var s=new Error;s.name=this.name,this.stack=s.stack}this.code=e,this._message=t,this.message="["+e+"] "+t,this.libraryId=o,this.underlyingError=r}n.prototype=Object.create(Error.prototype),n.prototype.name="AdobeLibraryError",n.INVALID_PARAMETER="INVALID_PARAMETER",n.READ_ONLY="READ_ONLY",n.NOT_IMPLEMENTED="NOT_IMPLEMENTED",n.NOT_SUPPORTED="NOT_SUPPORTED",n.REQUIRES_FILESYSTEM="REQUIRES_FILESYSTEM",n.DELETED_LOCALLY="DELETED_LOCALLY",n.NOT_ALLOWED="NOT_ALLOWED",n.FILE_TOO_LARGE="FILE_TOO_LARGE",n.EXCEEDS_MAX_LIBRARY_SIZE="EXCEEDS_MAX_LIBRARY_SIZE",n.CORRUPTED_LIBRARY="CORRUPTED_LIBRARY",n.THUMBNAIL_NOT_AVAILABLE="THUMBNAIL_NOT_AVAILABLE",n.STALE_THUMBNAIL="STALE_THUMBNAIL",n.RENDITION_NOT_AVAILABLE="RENDITION_NOT_AVAILABLE",n.FS_ERROR="FS_ERROR",n.OUT_OF_SPACE="OUT_OF_SPACE",n.LOGGED_OUT="LOGGED_OUT",n.EXCEEDS_QUOTA="EXCEEDS_QUOTA",n.RETRYABLE_SERVER_ERROR="RETRYABLE_SERVER_ERROR",n.TRANSFER_ERROR="TRANSFER_ERROR",n.TRANSFER_ABORTED="TRANSFER_ABORTED",n.NETWORK_ERROR="NETWORK_ERROR",n.ACCESS_DENIED="ACCESS_DENIED",n.URL_VALIDATION_FAILED="URL_VALIDATION_FAILED",n.NO_COMPATIBLE_APP_FOUND="NO_COMPATIBLE_APP_FOUND",n.APP_LAUNCH_FAILED="APP_LAUNCH_FAILED",n.OPERATION_CANCELLED="OPERATION_CANCELLED",n.INVALID_DATA="INVALID_DATA",n.CLIENT_CONNECTION_ERROR="CLIENT_CONNECTION_ERROR",Object.freeze(n),Object.seal(n.prototype),e.exports=n},function(e,t){function i(e,t,n){if(Error.call(this),Error.captureStackTrace)Error.captureStackTrace(this,i);else{var o=new Error;o.name=this.name,this.stack=o.stack}this.code=e,this.message="["+e+"] "+t,this.underlyingError=n}i.prototype=Object.create(Error.prototype),i.prototype.name="AdobeDCXError",i.INVALID_JSON="INVALID_JSON",i.READ_ONLY="READ_ONLY",i.INVALID_PARAMS="",i.INVALID_DATA="INVALID_DATA",i.DUPLICATE_VALUE="DUPLICATE_VALUE",i.NO_LOCAL_STORAGE="NO_LOCAL_STORAGE",i.INVALID_STATE="INVALID_STATE",i.DELETED_COMPOSITE="DELETED_COMPOSITE",i.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",i.NETWORK_ERROR="NETWORK_ERROR",i.COMPONENT_DOWNLOAD_ERROR="COMPONENT_DOWNLOAD_ERROR",i.COMPONENT_UPLOAD_ERROR="COMPONENT_UPLOAD_ERROR",i.COMPONENT_MODIFIED_ERROR="COMPONENT_MODIFIED_ERROR",i.UPDATE_CONFLICT="UPDATE_CONFLICT",i.NO_COMPOSITE="NO_COMPOSITE",i.ALREADY_EXISTS="ALREADY_EXISTS",i.SERVICE_IS_INACTIVE="SERVICE_IS_INACTIVE",i.EXCEEDS_QUOTA="EXCEEDS_QUOTA",i.NOT_IMPLEMENTED="NOT_IMPLEMENTED",i.RETRYABLE_SERVER_ERROR="RETRYABLE_SERVER_ERROR",i.TIMED_OUT="TIMED_OUT",i.UNEXPECTED="UNEXPECTED",i.TERMINATED_INPUTSTREAM="TERMINATED_INPUTSTREAM",i.WRONG_ENDPOINT="WRONG_ENDPOINT",i.OUT_OF_SPACE="ENOSPC";var n={};n[i.SERVICE_IS_INACTIVE]=1,n[i.NOT_IMPLEMENTED]=1,n[i.EXCEEDS_QUOTA]=1,n[i.RETRYABLE_SERVER_ERROR]=1,n[i.TIMED_OUT]=1,n[i.TERMINATED_INPUTSTREAM]=1,n[i.WRONG_ENDPOINT]=1,n[i.OUT_OF_SPACE]=1,i.wrapError=function(e,t,o,r){if(!o||!n[o.code]){if(r){var s=r.statusCode;s>=500&&s<600&&(501===s?(e=i.NOT_IMPLEMENTED,t="Unimplemented request"):507===s?(e=i.EXCEEDS_QUOTA,t="Quota exceeded"):(e=i.RETRYABLE_SERVER_ERROR,t="Server error"))}o=new i(e,t,o)}return r&&(o.response=r),o},i.networkError=function(e,t,n){return i.wrapError(i.NETWORK_ERROR,e,t,n)},i.unexpectedResponse=function(e,t,n){return i.wrapError(i.UNEXPECTED_RESPONSE,e,t,n)},e.exports=i},function(e,t,i){const n=i(1);e.exports=class{constructor(e,t){this._restrictedTypes=e,this._logCallback=t,this._listeners={}}_log(e){this._logCallback&&this._logCallback(e)}_checkType(e){if(this._restrictedTypes&&!this._restrictedTypes.includes(e)){const t=`${e} is not allowed. Should be one of: [${this._restrictedTypes.join(", ")}]`;throw new n(n.INVALID_PARAMETER,t)}}add(e,t){this._checkType(e),this._listeners[e]=this._listeners[e]||[],this._listeners[e].push(t)}remove(e,t){this._checkType(e);const i=this._listeners[e],n=i?i.indexOf(t):-1;-1!==n&&i.splice(n,1)}removeAll(e){e?(this._checkType(e),delete this._listeners[e]):this._listeners={}}notify(e,t){this._checkType(e);const i=this._listeners[e];i&&i.slice().forEach(e=>{try{e.apply(void 0,t||[])}catch(e){this._log("Error in listener callback: "+(e?e.toString():"")),e&&e.stack&&this._log(e.stack)}})}hasListeners(e){return this._checkType(e),(this._listeners[e]||[]).length>0}forEach(e){const t=this._listeners;Object.keys(t).forEach(i=>{t[i].forEach(t=>e(i,t))})}}},function(e,t,i){var n,o,r=i(43);n=i(7);var s={},a={"application/vnd.adobe.library+dcx":".cclibc"};s._setLogCallback=function(e){o=e},s.merge=function(e){var t,i;for(t=1;t<arguments.length;++t){var n=arguments[t];if("object"==typeof n)for(i in n)n.hasOwnProperty(i)&&(e[i]=n[i])}return e},s.parentDirectory=function(e){var t=e.split("/");return t.pop(),t.join("/")},s.filePathComponents=function(e){var t=e.split("/"),i=t.pop(),n=i.split("."),o=n.length>1?n.pop():null;return{directory:t.join("/"),fileName:i,baseName:n.join("."),extension:o}},s.appendPathElements=function(){var e,t=[],i=arguments.length;for(e=0;e<i;e++){var n=arguments[e];"string"==typeof n&&""!==n&&(0===e&&1!==n.length||"/"===n.charAt(0)&&(n=n.slice(1)),e!==i-1&&"/"===n.charAt(n.length-1)&&(n=n.slice(0,n.length-1)),t.push(n))}return t.join("/")};var c=/^[^\u0000-\u001F\u0022\u002A\u003A\u003C\u003E\u003F\u005C\u007F]*[^\u0000-\u001F\u0022\u002A\u002E\u003A\u003C\u003E\u003F\u005C\u007F]{1}$/;s.isValidPath=function(e,t){try{if(e.length>65535)return!1;var i=(t?e.slice(1):e).split("/");if(!i||0===i.length)return!1;var n,o=i.length;for(n=0;n<o;n++){if(i[n].length>255||!c.test(i[n]))return!1}if(t&&i.length>0){var r=i[0];if("manifest"===r||"mimetype"===r)return!1}return!0}catch(e){return!1}},s.isValidAbsolutePath=function(e){return s.isValidPath(e,!0)};var l=s.noOp=function(){};s.consumeStream=function(e,t,i){e.on("data",i||l),e.on("end",t||l)},s.flatCopy=function(e){var t,i={},n=Object.keys(e),o=n.length;for(t=0;t<o;t++){var r=n[t];i[r]=e[r]}return i},s.deepCopy=function(e){return JSON.parse(JSON.stringify(e))},s.objectsEqual=function(e,t,i){var n,o,r={},a=Object.keys(e),c=a.length;for(o=0;o<c;o++){if(n=a[o],!i||!i[n]){var l=e[n],h=t[n],d=typeof l;if(d!==typeof h)return!1;if("object"===d){if(!s.objectsEqual(l,h,i))return!1}else if(l!==h)return!1}r[n]=!0}for(c=(a=Object.keys(t)).length,o=0;o<c;o++)if(!r[n=a[o]])return!1;return!0};var h=new RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");s.parseURI=function(e){var t=e.match(h);return{scheme:t[2],authority:t[4],path:t[5],query:t[7],fragment:t[9]}},s.endPointOf=function(e){var t,i=s.parseURI(e),n=i.scheme,o=i.authority,r="https"===n?443:"http"===n?80:-1;return n&&o&&(t=(n+"://"+o).toLowerCase(),r>=0&&o.indexOf(":")<0&&(t=t+":"+r)),t},s.ensureRelativeHrefStartsWithSlash=function(e){if(e){var t=s.parseURI(e),i=t.scheme,n=t.authority;i||n||"/"!==e.charAt(0)&&(e="/"+e)}return e};var d=/^([^:]+):(.*)$/,_=/^\s+|\s+$/g;s.parseHeaders=function(e){var t,i,n,o={},r=e.split(/\r?\n/);for(t=0;t<r.length;++t){var s=r[t];if(s.length>0){var a=s.charCodeAt(0);if(!i||9!==a&&32!==a){var c=d.exec(s);c&&c.length>1&&(i=c[1].toLowerCase(),n=(n=c[2]||"").replace(_,""),o[i]?o[i]=o[i]+","+n:o[i]=n)}else o[i]=o[i]+" "+s.replace(_,"")}}return o},s.timeStamp=function(e){var t=(new Date).getTime();return e&&(t-=t%1e3),t},s.generateUuid=n,s.log=function(e){if("function"==typeof o)try{o(e)}catch(e){}},s.validateLinks=function(e){return void 0===e||Object(e)===e&&!Object.keys(e).some(t=>{const i=e[t];return Array.isArray(i)?i.some(({href:e})=>"string"!=typeof e):"string"!=typeof i.href})},s.getTemplateFromLinks=function(e,t){let i=e&&e[t];if(i&&(!Array.isArray(i)||0!==i.length))return Array.isArray(i)&&(i=i[0]),i.href;s.log(`Requested link is not available: ${t}`)},s.getUrlFromLinks=function(e,t,i={}){const n=s.getTemplateFromLinks(e,t);if(!n)return;const o=new r(n);return o&&o.fill(i)},s.getExtension=function(e){return a[e]||""},e.exports=s},function(e,t,i){var n,o=i(16),r=i(0),s=i(3),a=r.getValue("LOG_DIR")+"CC Library Process.log",c=r.getValue("LOG_DIR")+"CC Library Process (prev).log",l=!1,h=new s(["logWrite"]);function d(){o.ensureDir(r.getValue("LOG_DIR"),(function(e){if(e)return n=void 0,void console.error(e);var t;t=function(e){if(e)return n=void 0,void console.error(e);var t=n;n=void 0,l=!0,o.appendFile(a,t,(function(e){e&&console.error(e),l=!1,n&&d(),h.notify("logWrite")}))},o.stat(a,(function(e,i){!e&&i.size>r.getValue("MAX_LOG_SIZE")?o.rename(a,c,t):t(null)}))}))}var _={log:function(){var e=Array.prototype.slice.call(arguments).join(": ");r.getValue("CONSOLE_LOGGING")&&console.log(e);var t=(new Date).toString()+" "+e+"\n";n?n+=t:(n=t,l||d())},addLogWriteListener:function(e){h.add("logWrite",e)},removeLogWriteListener:function(e){h.remove("logWrite",e)}};_._listenerManager=h,e.exports=_},function(e,t,i){var n=i(2),o=i(1),r={getErrorStatusCode:function(e){if(e){var t=e.code===n.UNEXPECTED_RESPONSE&&e.response&&e.response.statusCode;return t||(e.underlyingError?r.getErrorStatusCode(e.underlyingError):void 0)}},getSyncError:function(e,t,i){if(e){if(e.code===o.TRANSFER_ABORTED)return e;var s=r.getErrorStatusCode(e);return e.code===n.SERVICE_IS_INACTIVE?new o(o.LOGGED_OUT,"no access token: call updateAccessToken() and try again",t,e):e.code===n.NETWORK_ERROR?new o(o.NETWORK_ERROR,"error connecting to server",t,e):e.code===n.EXCEEDS_QUOTA?new o(o.EXCEEDS_QUOTA,"push failed due to insufficient remaining quota",t,e):e.code===n.OUT_OF_SPACE?new o(o.OUT_OF_SPACE,"not enough disk space",t,e):e.code===n.NOT_IMPLEMENTED?new o(o.NOT_IMPLEMENTED,"tried to call an API not implemented on the server",t,e):e.code===n.RETRYABLE_SERVER_ERROR?new o(o.RETRYABLE_SERVER_ERROR,"intermittent server failure - can retry later",t,e):e.code===n.INVALID_DATA||e.code===n.INVALID_JSON?new o(o.CORRUPTED_LIBRARY,"unable to read manifest",t,e):s&&i&&i[s]?new o(i[s],"server returned "+s+"response",t,e):new o(o.TRANSFER_ERROR,"something went wrong during a push/pull operation",t,e)}},getCommitError:function(e,t,i){if(e){var r=i?" - "+i:"";return e.code===n.INVALID_DATA||e.code===n.INVALID_JSON?new o(o.CORRUPTED_LIBRARY,"unable to read manifest"+r,t,e):e.code===n.OUT_OF_SPACE?new o(o.OUT_OF_SPACE,"not enough disk space"+r,t,e):new o(o.FS_ERROR,"filesystem error"+r,t,e)}},getFileSystemError:function(e,t,i){if(e)return"ENOSPC"===e.code?new o(o.OUT_OF_SPACE,t,i,e):new o(o.FS_ERROR,t,i,e)},getSnapshotError:function(e,t,i){if(e)return e.code===n.INVALID_DATA||e.code===n.INVALID_PARAMS?new o(o.INVALID_DATA,i,t,e):r.getFileSystemError(e,i,t)},getErrorPriority:function(e){var t=[o.OPERATION_CANCELLED,o.EXCEEDS_MAX_LIBRARY_SIZE,o.THUMBNAIL_NOT_AVAILABLE,o.RENDITION_NOT_AVAILABLE,o.URL_VALIDATION_FAILED,o.CORRUPTED_LIBRARY,o.TRANSFER_ABORTED,o.TRANSFER_ERROR,o.NETWORK_ERROR,o.EXCEEDS_QUOTA,o.RETRYABLE_SERVER_ERROR,o.LOGGED_OUT,o.FILE_TOO_LARGE,o.INVALID_DATA,o.FS_ERROR,o.OUT_OF_SPACE,o.ACCESS_DENIED,o.NOT_ALLOWED,o.DELETED_LOCALLY,o.REQUIRES_FILESYSTEM,o.NOT_SUPPORTED,o.NOT_IMPLEMENTED,o.INVALID_PARAMETER,o.READ_ONLY],i=e&&e.code&&t.indexOf(e.code);return void 0!==i?i:-1},errorToString:function(e){var t="";return e&&(e.message&&(t+=e.message),e.libraryId&&(t+=" library: "+e.libraryId),e.underlyingError?t+="\n<- "+r.errorToString(e.underlyingError):e.response&&e.response.statusCode&&(t+=": "+e.response.statusCode),e.failedComponents&&(t+="\n<- Failed Components:",e.failedComponents.forEach(e=>{var i=e.component&&e.component.id,n=e.error,o=n&&n.message,r=n&&n.response&&n.response.statusCode;t+="\n    ["+i+"] "+o+(r?": "+r:"")}))),t},isErrorCode:function(e){return!!e&&(o.hasOwnProperty(e)&&o[e]===e)}};Object.seal(r),e.exports=r},function(e,t){e.exports=require("uuid/v4")},function(e,t){var i={constructStringFromTemplate:function(e,t){var i=e;return Object.keys(t).forEach(e=>{i=i.replace("{{"+e+"}}",t[e])}),i},parseLocalisationFile:function(e){const t={},i=e.split(/\n/);for(let e=0;e<i.length;e++)if(i[e]=i[e].replace(/^\s\s*/,"").replace(/\s\s*$/,""),i[e].length>0&&"#"!==i[e].match("^#")){const n=i[e].split("="),o=n[0].replace(/^\s\s*/,"").replace(/\s\s*$/,"");let r=1===n.length?"":n[1];for(;r.match(/\\$/)&&"\\"===r.match(/\\$/).toString();)r=r.substring(0,r.length-1),r+=i[++e].replace(/\s\s*$/,"");for(let e=2;e<n.length;e++)r+="="+n[e];r=r.replace(/^\s\s*/,"").replace(/\s\s*$/,""),t[o]=r}return t},compareVersions:function(e,t){if(e=(e||"0").toString().replace(/(\.0)*$/,"").replace(/[^.0-9]+/gim,"."),t=(t||"0").toString().replace(/(\.0)*$/,"").replace(/[^.0-9]+/gim,"."),(isNaN(parseInt(e,10))||parseInt(e,10)>250)&&(e="0"),(isNaN(parseInt(t,10))||parseInt(t,10)>250)&&(t="0"),e===t)return 0;var i,n=e.split("."),o=t.split(".");for(let e=0;e<n.length&&e<o.length;e++){if(i=parseInt(n[e],10)-parseInt(o[e],10),isNaN(i))return isNaN(parseInt(n[e],10))?1:-1;if(i>0)return-1;if(i<0)return 1}return(i=n.length-o.length)>0?-1:i<0?1:0},promisify:e=>(...t)=>new Promise((i,n)=>{e(...t,(e,t)=>e?n(e):i(t))})};Object.seal(i),e.exports=i},function(e,t){e.exports=require("path")},function(e,t,i){var n=i(25),o=i(2),r=i(12),s=i(1);const a=i(8).promisify;var c={},l={};c.isCompatibleType=function(e,t){return e===t||e===l[t]},c.validateLibraryId=function(e,t){if(t){if(e&&e.length>=30&&e.match(/^[0-9A-Z-]+$/i))return!0}else if(e&&e.match(/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i))return!0;return!1},c.validateLibrary=function(e){return(e.current&&e.current.rootNode.getValue(r.VERSION_KEY))===r.VERSION},c.areManifestsEqual=function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;const i=JSON.parse(e),n=JSON.parse(t);delete i["manifest-format-version"],delete n["manifest-format-version"];try{if(JSON.stringify(i)===JSON.stringify(n))return!0}catch(e){}return!1},c.getManifestForComparison=function(e,t){return t&&"\n"===t[1]?e._dcxBranch.prettifiedLocalData:e._dcxBranch.localData},c.getDCXKey=function(e,t){if(!e||!("string"==typeof e||e instanceof String)||""===e)throw new s(s.INVALID_PARAMETER,"Invalid namespace");if(!t||!("string"==typeof t||t instanceof String)||""===t)throw new s(s.INVALID_PARAMETER,"Invalid key");return e+"#"+t},c.getCustomDCXData=function(e){var t=e.getCustomKeys(),i=[];return t.forEach(t=>{var n=t.split("#"),o=n.length>=2;o&&n.forEach(e=>{""===e&&(o=!1)});var s=0===t.indexOf(r.DL_PREFIX);o&&!s&&i.push({namespace:n.shift(),key:n.join("#"),value:e.getValue(t)})}),i},c.copyCustomDCXData=function(e,t){c.getCustomDCXData(e).forEach(e=>{t.setValue(c.getDCXKey(e.namespace,e.key),e.value)}),[r.REPRESENTATION_ORDER_KEY,r.IS_PREFERRED_THUMBNAIL_KEY,r.SHA_KEY].forEach(i=>{var n=e.getValue(i);n&&t.setValue(i,n)})},c.checkDeletedState=function(e,t){if(e.isDeletedLocally){if(t)return t(new s(s.DELETED_LOCALLY,"deleted/orphan object")),!0;throw new s(s.DELETED_LOCALLY,"deleted/orphan object")}return!1},c.checkEncoding=function(e,t,i){if(-1===t.indexOf(e)){var n=t.join(", ");return i(new s(s.INVALID_PARAMETER,"Unsupported encoding. Supported encodings are: "+n)),!1}return!0},c.sortRepresentations=function(e){if(e.length<2)return;let t=!0;for(;t;){t=!1;for(let i=1;i<e.length;i++){const n=e[i-1],o=e[i];o._getOrder()<n._getOrder()&&(e[i-1]=o,e[i]=n,t=!0)}}},c.removeMissingComponents=function(e,t,i){if(t&&i){var n=0,o=0;return i.forEach(i=>{var r=i.component,s=i.error;r&&s&&s.response&&404===s.response.statusCode&&(t.removeComponent(r),n++,e._services.log("Removed missing component: "+r.id+" from library "+t.compositeId)),r&&s&&"[UNEXPECTED_RESPONSE] Incorrect content length"===s.message&&(o++,e._services.log("Skipped length-mismatch component: "+r.id+" from library "+t.compositeId))}),e._services.log("Fixed "+n+" of "+i.length+" components that failed to download"),e._analytics.reportRemoveMissingComponents(t.compositeId,i,n),i.length===n+o?t:void 0}};const h=(e,t)=>{const i=e=>e.representations.find(e=>e.id===t),n=e.elements.find(i)||e.removedElements.find(i);return n&&i(n)},d={"model/vnd.adobe.dn+dcx":"model/vnd.adobe.dn+dcxucf","application/vnd.adobe.element.agc+dcx":"application/vnd.adobe.element.agc+json"};c.fixLocalComponents=function(e,t){if(e&&t){var i=0,n=[];t.forEach(t=>{var r=t.component,s=t.error;if(r&&s&&s.code===o.INVALID_STATE){var a=h(e,r.id);a?n.push(a):e._dcxBranch.removeComponent(r),i++,e._services.log(`Removed missing local component: ${r.id} from library ${e.id}`)}else if(r&&s&&d[r.type]){const t=h(e,r.id),n=d[r.type];t&&(t._getDCXElement().type=n,i++,e._services.log(`Fixed mime type of local component: ${r.id} from library ${e.id} (${n})`))}}),i>0&&(e._beginOperation(),n.forEach(e=>{e.element.removeRepresentation(e)}),e._endOperation()),e._services.log("Fixed "+i+" of "+t.length+" components that failed to upload")}},c.recoverReadOnlyEdits=function(e,t,i){var n=[];e.elements.forEach(e=>{var i=t&&t.getChildWithId(e.id);(i&&i.getValue(r.MODIFIED_KEY))!==e.modified&&n.push(e)});const o=[];if(n.length>0){var s,c=e._localisation.translate("LIBS_RECOVERED_LIBRARY",{name:e.name});e.collection.libraries.some((function(t){if(t.name===c&&t.isWritable&&"incoming"!==t.collaboration&&t.elements.length<e._config.MAX_ELEMENTS)return s=t,!0})),s||(s=e.collection.createLibrary(c));const t=a(e.copyElement.bind(e));n.forEach(e=>o.push(t(e,s))),e._services.log("Recovering "+n.length+" elements from read-only library")}Promise.all(o).then(()=>i(null),e=>i(e))},c.ensureBranchDataValid=function(e){var t=[r.ELEMENTS_NAME,r.REMOVED_ELEMENTS_NAME],i=!1;return e.getChildrenOf().forEach((function(n){if(-1!==t.indexOf(n.name)){var o=n.name===r.REMOVED_ELEMENTS_NAME;e.getChildrenOf(n).forEach(e=>{var t=e.getValue(r.REMOVED_KEY);!o&&t?(e.removeValue(r.REMOVED_KEY),i=!0):o&&!t&&(e.setValue(r.REMOVED_KEY,Date.now()),i=!0)})}})),i},c.collaborationStateToDCX=function(e){return"incoming"===e?n.COLLABORATION.SHARED_WITH_USER:"outgoing"===e?n.COLLABORATION.SHARED_BY_USER:n.COLLABORATION.PRIVATE},c.collaborationStateFromDCX=function(e){return e===n.COLLABORATION.SHARED_WITH_USER?"incoming":e===n.COLLABORATION.SHARED_BY_USER?"outgoing":void 0},c.getCompositeRenditionMap=function(e){var t=e.getComponentsOf(),i={};return t&&t.forEach(e=>{if("rendition"===e.relationship){var t=e.getValue(r.RENDITION_TYPE_KEY);t&&(i[t]=e)}}),i},c.recoverFromElmo=function(e,t,i){const n=e._services.fs,o=e._services.getPathSeparator(),r={},s=t.every(t=>{r[t]=!0;const i=e._getCompositeDir(t)+o+"manifest";try{const e=JSON.parse(n.readFileSync(i,"utf8")).children.find(e=>"elements"===e.name);if(!e.children||0===e.children.length)return!0}catch(e){}}),a=e._syncManager,c=t=>{if(t)return a.links.test(e._getNewCompositeHref(t),i),void e._services.log("Failed to recover from ELMO: "+t);e._services.log("Successfully recovered from ELMO"),i()};if(!s)return c("has_data");const l=()=>{e._services.fileUtils.recursiveDeleteDirectory(e._getBaseDir(),e=>{c(e&&"local_delete")})};a.getServerComposites(e,(t,i)=>{if(t)return c("sg_fetch");i.every(e=>r[e.name])&&i.length>=e._config.ELMO_LOCAL_LIBRARY_LIMIT?a.deleteAllServerComposites(e,e=>{if(e)return c("sg_delete");l()}):i.length<e._config.ELMO_SERVER_RECOVERED_LIMIT?l():c("out_of_sync")})},Object.seal(c),e.exports=c},function(e,t,i){var n,o,r=i(4);o=i(35);const s={};var a={canUseFileSystem:!1,_setFS:function(e){n=e,a.canUseFileSystem=!!e},ensureDirectoryExists:function(e,t){var i=function(e){e&&"EEXIST"===e.code?t():t(e)},o=function(o){if(o)t();else{var s=r.parentDirectory(e);s?a.ensureDirectoryExists(s,(function(o){o?t(o):n.mkdir(e,i)})):n.mkdir(e,i)}};e?n.exists(e,o):o(!0)},getTempFilePathAt:function(e,t){var i=function(){var n=e+r.generateUuid();a.exists(n,(function(e){e?i():t(n)}))};i()},exists:function(e,t){n.exists(e,t)},deleteFile:function(e,t){n.unlink(e,(function(e){e&&"ENOENT"!==e.code?t(e):t()}))},readFile:function(e,t,i){n.readFile(e,t,i)},writeFile:function(e,t,i,o){var s=r.parentDirectory(e);a.ensureDirectoryExists(s,(function(r){r?o(r):n.writeFile(e,t,i,o)}))},writeFileAtomically:function(e,t,i,o){var s=r.parentDirectory(e);a.ensureDirectoryExists(s,(function(r){r?o(r):a.getTempFilePathAt(s+"/",(function(r){n.writeFile(r,t,i,(function(t){t?o(t):n.rename(r,e,o)}))}))}))},createWriteStream:function(e,t){return n.createWriteStream(e,t)},createReadStream:function(e,t){return n.createReadStream(e,t)},move:function(e,t,i,o){var s=r.parentDirectory(t);a.ensureDirectoryExists(s,(function(r){if(r)o(r);else if(i){var s=(new Date).getTime()/1e3;n.utimes(e,s,s,(function(i){i?o(i):n.rename(e,t,o)}))}else n.rename(e,t,o)}))},info:function(e,t){n.stat(e,t)},directoryListing:function(e,t){var i,o,r=[],s=function(s){n.stat(e+"/"+s,(function(e,n){if(!e)try{r.push({name:s,info:n}),i--}catch(t){e=t}e?o||(o=e,t(e)):0===i&&t(void 0,r)}))};n.readdir(e,(function(e,n){if(!e)try{var o,r=n.length;for(i=r,o=0;o<r;o++)s(n[o])}catch(t){e=t}e?t(e):0===i&&t(void 0,[])}))},deleteDirectory:function(e,t){var i,o,r=function(){try{n.rmdir(e,t)}catch(e){t(e)}},s=function(e){e&&!i&&(i=e),--o<1&&(i?t(i):r())},c=function(t){var i=e+"/"+t;n.unlink(i,(function(e){try{e?a.deleteDirectory(i,(function(e){s(e)})):s()}catch(e){s(e)}}))};n.readdir(e,(function(e,i){if(!e)try{var n,s=i.length;if(s<1)r();else for(o=s,n=0;n<s;n++)c(i[n])}catch(t){e=t}e&&t(e)}))}};a.copyFile=function(e,t="default",i=10){return s[t]=s[t]||{operationsInFlight:0,queue:[]},function(...n){const o=n.pop(),r=()=>{s[t].operationsInFlight+=1;e(...n,(...e)=>{s[t].operationsInFlight-=1,s[t].queue.length>0&&s[t].queue.shift()(),o(...e)})};if(s[t].operationsInFlight>=i)return s[t].queue.push(r);r()}}((function(e,t,i){var o=r.parentDirectory(t);a.ensureDirectoryExists(o,(function(o){o?i(o):function(e,t,i){try{var o=t+r.generateUuid(),s=n.createWriteStream(o),a=n.createReadStream(e);a.on("end",()=>{n.rename(o,t,e=>{e?setTimeout(()=>{n.rename(o,t,i)},100):i(null)})}),a.on("error",(function(e){i(e)})),a.pipe(s)}catch(e){i(e)}}(e,t,i)}))})),a.getMD5Hash=function(e,t){const i=o.createHash("md5").setEncoding("base64");try{const o=n.createReadStream(e);o.pipe(i).on("finish",()=>t(null,i.read())),o.on("error",e=>t(e))}catch(e){t(e)}},e.exports=a},function(e,t,i){const n=i(1),o=i(4),r=i(3),s=["ROOT_DIR","POLL_INTERVAL","RENDITION_SIZES","FULL_RENDITION_CONFIG","EXTERNAL_LINK_PREFETCH","LOCALE","STORAGE_API_KEY","USER_AGENT_HEADER","SYNC_POLICY","ELEMENT_TYPE_FILTERS","AUTO_START_POLLING","SHARED_LOCAL_STORAGE","WHITELISTED_DOMAINS","CLIENT_DESCRIPTION","DEVICE_ID","DEVICE_DESCRIPTION","APP_DESCRIPTION","DEFAULT_RENDITION_404_BACKOFF","LOCAL_SETTINGS"],a="library#",c="bookmarks.json",l={VERSION:1,DL_NAMESPACE:"library",DL_PREFIX:a,VERSION_KEY:"library#version",RELATIONSHIP_KEY:"library#rel",WIDTH_KEY:"library#width",HEIGHT_KEY:"library#height",LENGTH_KEY:"library#length",IS_FULL_SIZE_KEY:"library#isFullSize",IS_PREFERRED_THUMBNAIL_KEY:"library#isPreferredThumbnail",MODIFIED_KEY:"library#modified",CREATED_KEY:"library#created",REMOVED_KEY:"library#removed",MODIFIED_DATA_KEY:"library#modifiedData",CREATED_DATA_KEY:"library#createdData",REMOVED_DATA_KEY:"library#removedData",DESCRIPTION_KEY:"library#description",DESCRIPTION_DATA_KEY:"library#descriptionData",GROUPS_KEY:"library#groups",ORDER_KEY:"library#order",CLASSIFIER_KEY:"library#classifier",SOURCE_REF_KEY:"library#sourceRef",LINK_TYPE_KEY:"library#linktype",LINK_URL_KEY:"library#linkurl",LINK_LOCAL_PATH_KEY:"library#linklocalpath",REPRESENTATION_ORDER_KEY:"library#representationOrder",RENDITION_TYPE_KEY:"library#renditiontype",SHA_KEY:"library#sha256",ANIMATION_ELEMENT_TYPE:"application/vnd.adobe.element.animation+dcx",BRUSH_ELEMENT_TYPE:"application/vnd.adobe.element.brush+dcx",COLOR_ELEMENT_TYPE:"application/vnd.adobe.element.color+dcx",IMAGE_ELEMENT_TYPE:"application/vnd.adobe.element.image+dcx",LAYER_STYLE_ELEMENT_TYPE:"application/vnd.adobe.element.layerstyle+dcx",REPRESENTATION_CONTENT_VALUES:{"application/vnd.adobe.color+json":{namespace:"color",key:"data"},"application/vnd.adobe.text+json":{namespace:"text",key:"data",contentFromData:!0}},DEFAULT_GROUP_CLASSIFIER:"$default",COMPOSITE_TYPE:"application/vnd.adobe.library+dcx",LINK_REPRESENTATION_TYPE:"application/vnd.adobe.library.link+dcx",GROUP_TYPE:"application/vnd.adobe.library.group+dcx",ELEMENTS_NAME:"elements",REMOVED_ELEMENTS_NAME:"removed_elements",GROUPS_NAME:"groups",DATA_COLLABORATION_ROLE:"collaborationRole",BOOKMARKS_FILENAME:c,BOOKMARKS_FILE_VERSION:2,BOOKMARKS_PATH:"/bookmarks",BOOKMARKS_MONITOR_PATHS:[c,"collab-bookmarks.json"].map(e=>`/sync/adobe-libraries/${e}`),BOOKMARKS_TYPES:{public:["url"],team:{on_pushed_new:["team_urn","org_id"],default:["urn","team_urn","org_id"]}},STOCK_NAMESPACE:"adobestock",STOCK_DATA_KEY:"trackingdata",STOCK_STATE_PURCHASED:"purchased",TOOLKIT_NAMESPACE:"toolkit",TOOLKIT_ID_KEY:"id",RELATIONSHIP_CHILD:"child",PUBLIC_USER_ID:"public",DEFAULT_CLOUD_ID:"creative_cloud",DEFAULT_CORESYNC_CLOUD_ID:"00000000-0000-0000-0000-000000000000",STORAGE_ASSETS_PATH:"/assets/",LIBRARY_SYNC_GROUP:"adobe-libraries",CP_CLOUD_ID:"community-platform",CP_STORAGE_ASSETS_PATH:"/content/2/",VULCAN_PREFIX:"vulcan.SuiteMessage.",VULCAN_STARTUP_MESSAGE:"cclibraries.service.Initialized",VULCAN_SHUTDOWN_REQUEST:"cclibraries.service.TerminateServiceRequest",VULCAN_QUERY_REQUEST:"cclibraries.service.QueryRequest",VULCAN_QUERY_RESPONSE:"cclibraries.service.QueryResponse",VULCAN_LIBRARY_CHANGED_LOCAL_TYPE:"cclibraries.service.LibraryChangedLocal",VULCAN_LIBRARY_CHANGED_REMOTE_TYPE:"cclibraries.service.LibraryChangedRemote",VULCAN_LIBRARY_DELETED_TYPE:"cclibraries.service.LibraryDeleted",VULCAN_COLLECTIONS_LOADED_TYPE:"cclibraries.service.LibrariesLoaded",VULCAN_COLLECTIONS_UNLOADED_TYPE:"cclibraries.service.LibrariesUnloaded",VULCAN_PROXY_QUERY_REQUEST:"cclibraries.service.QueryProxySettingsRequest",VULCAN_PROXY_QUERY_RESPONSE:"cclibraries.service.QueryProxySettingsResponse",VULCAN_PROXY_CHANGE_MESSAGE:"cclibraries.service.ProxySettingsChanged",VULCAN_APP_READY_MESSAGE:"cclibraries.accessor.AppReady",VULCAN_APP_SEND_ACTION_MESSAGE:"cclibraries.accessor.EditElementRequest",VULCAN_APP_ACTION_ACCEPTED_MESSAGE:"cclibraries.accessor.EditAcceptedMessage"};class h{constructor(){this._listenerManager=new r(["change"]),this.MAX_ELEMENTS=1e4,this.MAX_REMOVED_ELEMENTS=2e3,this.MAX_COMPONENT_SIZE=1073741824,this.VALID_RELATIONS=["rendition","primary","alternate"],this.VALID_LIBRARY_RENDITION_TYPES=["banner","cover"],this.VALID_SYNC_POLICIES=["manifestAndAssets","manifestOnly"],this.ELEMENT_TYPE_FILTERS=[],this.VECTOR_RENDITION_ELEMENT_TYPES=["application/illustrator"],Object.keys(l).forEach(e=>this[e]=l[e]),this.FS_RETRY_INTERVAL=100,this.FS_MAX_RETRIES=10,this.MAX_DCX_CONCURRENT_COPIES=10,this.REMOVE_OPERATION_TIMEOUT=100,this.EXPORT_VERSION=1,this.EXPORT_EXTENSION=".cclibs",this.ANALYTICS_ENABLED=!1,this.ANALYTICS_ELEMENT_UPDATE_THRESHOLD=500,this.STORAGE_API_KEY="",this.USER_AGENT_HEADER=void 0,this.SYNCING_ENABLED=!0,this.VULCAN_QUERY_TIMEOUT=8e3,this.DEFAULT_MAX_SYNC_INTERVAL=1e4,this.RETRY_FAIL_MAX_SYNC_INTERVAL=6e4,this.MAX_SYNC_INTERVAL=this.DEFAULT_MAX_SYNC_INTERVAL,this.POLL_INTERVAL=1,this.TEAM_POLL_INTERVAL=2,this.AUTO_START_POLLING=!1,this.RENDITION_SIZES={},this.FULL_RENDITION_CONFIG={},this.BACKOFF_INTERVALS=[1,1,2,3,5,8,13,21,34,55],this.ERROR_RETRY_INTERVALS=[30,60,120],this.NETWORK_TIMEOUT=6e5,this.IMAGE_SERVICE_NETWORK_TIMEOUT=18e4,this.RETRY_RANDOM_SECONDS=30,this.RENDITION_MAX_RETRIES=2,this.DEFAULT_RENDITION_RETRY_INTERVAL=1e3,this.RENDITION_RETRY_INTERVAL=this.DEFAULT_RENDITION_RETRY_INTERVAL,this.DEFAULT_RENDITION_404_BACKOFF=3e5,this.RENDITION_404_BACKOFF=this.DEFAULT_RENDITION_404_BACKOFF,this.LOCAL_RENDITION_MAX_RETRIES=5,this.LOCAL_RENDITION_RETRY_INTERVAL=200,this.MAX_UPDATE_CONFLICTS=5,this.MAX_REDIRECT_FOLLOW=5,this.MAX_HEAD_REDIRECT_FOLLOW=0,this.MAX_RECOVERED_LIBRARIES=10,this.ELMO_LOCAL_LIBRARY_LIMIT=2e4,this.ELMO_SERVER_RECOVERED_LIMIT=100,this.ADOBE_AUTHENTICATED_DOMAINS=["stock.adobe.com","stock.stage.adobe.com","adobe.io","adobestock.com","fotolia.net"],this.WHITELISTED_DOMAINS=["cclibraries-defaults-cdn.adobe.com","cclibraries-defaults-cdn.stage.adobe.com","stageastockcdn.net","ftcdn.net"],this.DISALLOWED_DOMAINS={"cc-api-storage-stage.adobe.io":["stock.adobe.com"],"cc-api-storage.adobe.io":["stock.stage.adobe.com"]},this.SHA_CACHE={},this.DEFAULT_CONTENT_LOCATIONS=[],this.SYNC_POLICY="manifestAndAssets",this.REMOVED_ELEMENTS_CACHE_TIMEOUT=6e5,this.RENDITION_CACHE_FILE="cache.json",this.RENDITION_CACHE_PLACEHOLDER="<placeholder>",this.SHARED_LOCAL_STORAGE=!0,this.SHARED_LOCAL_STORAGE_VERSION=21,this.SHARED_LOCAL_STORAGE_MIN_CLIENT_VERSION=6,this.SHARED_LOCAL_STORAGE_MAX_CLIENT_VERSION=21,this.LOCAL_SETTINGS={},this.ELEMENT_ACTIONS=["edit","openStock"],this.ELEMENT_ACTION_PRODUCT_MAP={types:{"application/vnd.adobe.element.image+dcx":{"application/illustrator":["ILST_EDIT","ILST_PLACE","IDSN_PLACE"],"image/svg+xml":["ILST_EDIT","ILST_PLACE"],"application/vnd.adobe.indesign-idms":["IDSN_EDIT","IDSN_PLACE"],"image/vnd.adobe.photoshop":["PHXS_EDIT","PHXS_PLACE","IDSN_PLACE"],"application/photoshop":["PHXS_EDIT","PHXS_PLACE","IDSN_PLACE"],"application/photoshop.large":["PHXS_EDIT","PHXS_PLACE","IDSN_PLACE"],"image/png":["PHXS_EDIT","PHXS_PLACE","ILST_PLACE","IDSN_PLACE","PPRO_PLACE","AEFT_PLACE"],"image/jpeg":["PHXS_EDIT","PHXS_PLACE","ILST_PLACE","IDSN_PLACE","PPRO_PLACE","AEFT_PLACE"],"image/jpg":["PHXS_EDIT","PHXS_PLACE","IDSN_PLACE","ILST_PLACE","PPRO_PLACE","AEFT_PLACE"],"image/gif":["PHXS_EDIT","PHXS_PLACE","ILST_PLACE","IDSN_PLACE","PPRO_PLACE","AEFT_PLACE"],"image/bmp":["PHXS_EDIT","PHXS_PLACE","ILST_PLACE","IDSN_PLACE","PPRO_PLACE","AEFT_PLACE"],"image/x-portable-bitmap":["PHXS_EDIT","PHXS_PLACE"],"image/x-pict":["PHXS_EDIT","PHXS_PLACE"],"image/x-pcx":["PHXS_EDIT","PHXS_PLACE"],"image/x-portable-graymap":["PHXS_EDIT","PHXS_PLACE"],"image/x-portable-anymap":["PHXS_EDIT","PHXS_PLACE"],"image/x-portable-pixmap":["PHXS_EDIT","PHXS_PLACE"],"image/x-tga":["PHXS_EDIT","PHXS_PLACE"],"image/tiff":["PHXS_EDIT","PHXS_PLACE"],"image/vnd.wap.wbmp":["PHXS_EDIT","PHXS_PLACE"]},"application/vnd.adobe.element.text+dcx":{"application/illustrator-text":["ILST_EDIT_TEXT"],"application/vnd.adobe.indesign-idms-text":["IDSN_EDIT_TEXT"]},"application/vnd.adobe.element.template+dcx":{"image/vnd.adobe.photoshop.template":["PHXS_PLACE"],"application/illustrator.template":["ILST_PLACE"],"application/vnd.adobe.indesign.template":["IDSN_PLACE"]},"application/vnd.adobe.element.3d+dcx":{"application/vnd.adobe.obj.3d+zip":["ESHR_PLACE"]},"application/vnd.adobe.element.material+dcx":{"application/vnd.adobe.mdl.material+zip":["ESHR_PLACE"]},"application/vnd.adobe.element.light+dcx":{"application/vnd.adobe.ibl.light+zip":["ESHR_PLACE"]},"application/vnd.adobe.element.animation+dcx":{"application/vnd.adobe.animate-xfl+zip":["FLPR_EDIT"],"application/vnd.adobe.animate-sym+zip":["FLPR_EDIT"]}},products:{ILST_EDIT:{minVersion:"19.2",appCode:"ILST",appName:"Illustrator",action:"edit"},ILST_EDIT_TEXT:{minVersion:"22",appCode:"ILST",appName:"Illustrator",action:"edit"},IDSN_EDIT:{minVersion:"11.2",appCode:"IDSN",appName:"InDesign",action:"edit"},IDSN_EDIT_TEXT:{minVersion:"13",appCode:"IDSN",appName:"InDesign",action:"edit"},PHXS_EDIT:{minVersion:"16.1.2",appCode:"PHXS",appName:"Photoshop",action:"edit"},FLPR_EDIT:{minVersion:"16.1",appCode:"FLPR",appName:"Flash",action:"edit"},PHXS_PLACE:{minVersion:"17.0.0",appCode:"PHXS",appName:"Photoshop",action:"openStock"},ILST_PLACE:{minVersion:"20.0.0",appCode:"ILST",appName:"Illustrator",action:"openStock"},IDSN_PLACE:{minVersion:"11.4.0",appCode:"IDSN",appName:"InDesign",action:"openStock"},PPRO_PLACE:{minVersion:"10.3.0",appCode:"PPRO",appName:"Premiere Pro",action:"openStock"},AEFT_PLACE:{minVersion:"13.8.0",appCode:"AEFT",appName:"After Effects",action:"openStock"},ESHR_PLACE:{minVersion:"0.1",appCode:"ESHR",appName:"Project Felix",action:"openStock"}},installedApps:[]},this.TLS_DISCOVERY_PORT_RANGE=[45623,45625],this.TLS_DELAY_ON_DECLINE=500,this.TLS_DELAY_ON_READY=250}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}setLocalSetting(e,t){this.LOCAL_SETTINGS[e]=t,this._listenerManager.notify("change")}setParameter(e,t){if(-1===s.indexOf(e))throw new n(n.INVALID_PARAMETER,"Parameter not configurable");if("SYNC_POLICY"===e&&-1===this.VALID_SYNC_POLICIES.indexOf(t))throw new n(n.INVALID_PARAMETER,"Invalid value for SYNC_POLICY");"POLL_INTERVAL"!==e&&"TEAM_POLL_INTERVAL"!==e||(t=Math.max(1,t)),this[e]=t}getBackoffTicks(e){const t=this.BACKOFF_INTERVALS;return t[Math.max(0,Math.min(e,t.length-1))]-1}getRetryAfterHeader(e){if(e){const t=e["retry-after"]||e["Retry-After"];if(t)try{const e=parseInt(t,10);if(e)return Math.max(0,e);const i=Date.parse(t);if(i){const e=Date.now();return Math.max(0,i-e)/1e3+Math.floor(Math.random()*this.RETRY_RANDOM_SECONDS)}}catch(e){}}return 0}getLocationHeader(e){if(e){const t=e.location||e.Location;if(t)return t}}getContentTypeHeader(e){if(e){let t=e["content-type"]||e["Content-Type"];if(t){const e=t.indexOf(";");return e>0&&(t=t.substring(0,e)),t}}}getContentLengthHeader(e){if(e){const t=e["content-length"]||e["Content-Length"];return Number(t)||void 0}}isUnrecoverableClientError(e,t){return!!e&&(e>=400&&e<500&&(401!==e||!!t)&&407!==e&&408!==e)}isRedirect(e){return 301===e||302===e||303===e||307===e}_checkDomain(e,t){return t.some((function(t){if(e===t)return!0;const i=e.indexOf("."+t);return-1!==i&&i===e.length-t.length-1}))}isAdobeDomain(e){return"string"==typeof e&&this._checkDomain(e,this.ADOBE_AUTHENTICATED_DOMAINS)}validateURL(e,t){if(!e)return new n(n.URL_VALIDATION_FAILED,"URL not specified");const i=o.parseURI(e);if("https"!==i.scheme)return new n(n.URL_VALIDATION_FAILED,"URL must be https://");if(!(this.isAdobeDomain(i.authority)||this._checkDomain(i.authority,this.WHITELISTED_DOMAINS)))return new n(n.URL_VALIDATION_FAILED,"URL domain not in whitelist");const r=t&&t._syncManager._storageHost,s=r&&this.DISALLOWED_DOMAINS[r];return this._checkDomain(i.authority,s||[])?new n(n.URL_VALIDATION_FAILED,"URL domain does not match IMS environment (stage-production mismatch)"):null}formatElementActionMapForClient(e){return e<9?{types:this.ELEMENT_ACTION_PRODUCT_MAP.types["application/vnd.adobe.element.image+dcx"],products:this.ELEMENT_ACTION_PRODUCT_MAP.products,installedApps:this.ELEMENT_ACTION_PRODUCT_MAP.installedApps}:this.ELEMENT_ACTION_PRODUCT_MAP}updateElementActionMap(e,t){if(e<9){const e=t.types;t.types=this.ELEMENT_ACTION_PRODUCT_MAP.types,t.types["application/vnd.adobe.element.image+dcx"]=e}this.ELEMENT_ACTION_PRODUCT_MAP=t}isCollectionSupported(e,t){return!t.isTeam||e>=17}isNewBookmarkFormatSupported(e){return e>=18}shouldPrefetchFullRendition(e){const t=(this.FULL_RENDITION_CONFIG||{})[e.type];if(!t)return!1;let i=!1;return Object.keys(t).forEach(n=>{const o=t[n];if("IF_NO_MATCHING_REPRESENTATION"===o.condition&&o.types){const t=e.representations.every(e=>!o.types.includes(e.type));i=i||t}}),i}shouldPrefetchExternalLink(e){if(!e.isExternalLink)return!1;const t=(this.EXTERNAL_LINK_PREFETCH||{})[e.element.type];return void 0===t||t}addToRenditionSizeConfig(e){const t=this.RENDITION_SIZES,i=JSON.parse(JSON.stringify(t["*"]||[])),n=e["*"]||[];Object.keys(t).forEach(i=>{if(!e[i]){const e=t[i];n.forEach(t=>{-1===e.indexOf(t)&&e.push(t)}),t[i]=e}}),Object.keys(e).forEach(n=>{const o=t[n]||JSON.parse(JSON.stringify(i));e[n].forEach(e=>{-1===o.indexOf(e)&&o.push(e)}),t[n]=o}),this.setParameter("RENDITION_SIZES",t)}addToFullRenditionConfig(e){const t=this.FULL_RENDITION_CONFIG;Object.keys(e).forEach(i=>{const n=t[i]||{};e[i].forEach(e=>{e.id&&(n[e.id]=e)}),t[i]=n}),this.setParameter("FULL_RENDITION_CONFIG",t)}}Object.keys(l).forEach(e=>h[e]=l[e]),e.exports=h},function(e,t,i){var n=i(29),o={parseXML:function(e,t){var i;return new n.Parser({async:!1}).parseString(e,(function(e,n){e?t&&t(e):i=n})),i}};const r={true:!0,false:!1};o.parseQueryString=function(e,t={}){const i={},n=e&&e.split("?");if(n[1]){n[1].split("&").forEach(e=>{const[n,o]=e.split("=");t.parseBooleans&&Object.keys(r).includes(o)?i[n]=r[o]:i[n]=o})}return i},o.stripProtocolPrefix=function(e){return["http://","https://"].forEach(t=>{e&&0===e.indexOf(t)&&(e=e.substring(t.length))}),e},e.exports=o},function(e,t){e.exports={PRIMARY:"http://ns.adobe.com/adobecloud/rel/primary",ID:"http://ns.adobe.com/adobecloud/rel/id",PATH:"http://ns.adobe.com/adobecloud/rel/path",RENDITION:"http://ns.adobe.com/adobecloud/rel/rendition",MANIFEST:"http://ns.adobe.com/adobecloud/rel/manifest",COMPONENT:"http://ns.adobe.com/adobecloud/rel/component",PAGE:"http://ns.adobe.com/adobecloud/rel/page",DISCARD:"http://ns.adobe.com/adobecloud/rel/discard",DIRECTORY:"http://ns.adobe.com/adobecloud/rel/directory",AC_EFFECTIVE:"http://ns.adobe.com/adobecloud/rel/ac/effective",CREATE:"http://ns.adobe.com/adobecloud/rel/create",METADATA:"http://ns.adobe.com/adobecloud/rel/metadata/repository",REPOSITORY:"http://ns.adobe.com/adobecloud/rel/repository",RESOLVE_ID:"http://ns.adobe.com/adobecloud/rel/resolve/id",RESOLVE_PATH:"http://ns.adobe.com/adobecloud/rel/resolve/path",OPS:"http://ns.adobe.com/adobecloud/rel/ops",BLOCK_INITIALIZE:"http://ns.adobe.com/adobecloud/rel/block/init",BLOCK_TRANSFER:"http://ns.adobe.com/adobecloud/rel/block/transfer",BLOCK_FINALIZE:"http://ns.adobe.com/adobecloud/rel/block/finalize"}},function(e,t){e.exports=require("child_process")},function(e,t){e.exports=require("fs-extra")},function(e,t){e.exports=class{constructor(){this._isLocked=!1,this._queue=[]}execute(e){const t=e=>(this.release(),e);return this.obtain().then(e).then(e=>t(e),e=>t(Promise.reject(e)))}_obtain(e){this._isLocked?this._queue.push(e):(this._isLocked=!0,e(null))}obtain(e){return e?this._obtain(e):new Promise((e,t)=>this._obtain(i=>i?t(i):e()))}release(){if(this._queue.length>0){const e=this._queue.shift();setTimeout(()=>e(null))}else this._isLocked=!1}abortPendingOperations(e){const t=this._queue;this._queue=[],t.forEach(t=>t(e))}isLocked(){return this._isLocked}hasPendingRequest(){return this._queue.length>0}}},function(e,t,i){const n=i(9),o=e=>e,r={modified_date:parseInt,size:parseInt,name:o},s={modified_date:e=>e.map(e=>parseInt(e)),owner:o},a=e=>{for(const[t,i]of Object.entries(e))t.includes("#")&&(e.custom_data||(e.custom_data={}),e.custom_data[t]=i,delete e[t])},c=e=>{const t=e.custom_data||{};for(const[i,n]of Object.entries(t))e[i]=n;delete e.custom_data},l=(e,t)=>{if(Array.isArray(e))e.forEach(e=>l(e,t));else if("object"==typeof e&&null!==e)for(const[i,n]of Object.entries(e))"representations"===i&&Array.isArray(n)?n.forEach(t):l(n,t)},h=e=>{const t={id:e.id,type:e.type,children:e.children.map(h),relationship:e.relationship,content_length:e.contentLength,content_hash:e.contentHash,width:e.width,height:e.height,is_external_link:!!e.isExternalLink||void 0,is_full_size:!!e.isFullSize||void 0,url:e.isExternalLink?e.getContentURL():void 0},i=e.getCachedContentPath();i&&(t.path=n.normalize(i));const o=e.getValues();return o&&o.length>0&&(t.custom_data={},o.forEach(e=>t.custom_data[`${e.namespace}#${e.key}`]=e.value)),t},d=e=>e?Array.isArray(e)?e.reduce((e,t)=>e+d(t),0):e.elements?e.elements.reduce((e,t)=>e+d(t),0):e.representations?e.representations.reduce((e,t)=>e+(t.contentLength||0),0):0:0,_=(e,t,i,n)=>{const o={id:e.id,name:e.name,type:e.type,created_date:e.created,modified_date:e.modified,element_ref:e.getReference(),tags:e.tags};if(o.groups=e.getGroups(/.*/).map(t=>({id:t.id,classifier:t.classifierName,order:e.getOrderInGroup(t)})),o.representations=e.representations.map(h),i){const t=e.library;o.library={},o.library.id=t.id,o.library.name=t.name,m(o.library,t)}if(n){const t=e.library._renditionCache.serializeElementCache(e,!0);Object.keys(t).length>0&&(o.thumbnail_cache=t)}t&&(o.size=d(e));const r=e.getValues();return r&&r.length>0&&(o.custom_data={},r.forEach(e=>o.custom_data[`${e.namespace}#${e.key}`]=e.value)),o},p={"application/vnd.adobe.element.color+dcx":e=>{const t=e.representations.map(e=>e.getValue("color","data")).find(e=>e&&"RGB"===e.mode);if(t)return{type:"application/vnd.adobe.element.color+dcx",rendition:{swatches:[[{alpha:t.alpha,mode:t.mode,type:t.type,value:t.value}]]}}},"application/vnd.adobe.element.colortheme+dcx":e=>{const t=e.getPrimaryRepresentation();return t&&{type:"application/vnd.adobe.element.colortheme+dcx",rendition:t.getValue("colortheme","data")}},"application/vnd.adobe.element.gradient+dcx":e=>{const t=e.getPrimaryRepresentation();return t&&{type:"application/vnd.adobe.element.gradient+dcx",rendition:t.getValue("gradient","data")}},default:e=>{const t=e._config.RENDITION_SIZES[e.type]||e._config.RENDITION_SIZES["*"],i=t&&e.getCachedThumbnailPath(Math.max(...t));if(i)return{type:"href",rendition:i}}},u=e=>(p[e.type]||p.default)(e),m=(e,t)=>{if(t.collaboration){const i=t.collaboration.toLowerCase();e.collaboration={state:i},e.collaboration.role="outgoing"===i?"owner":t.isWritable?"editor":"viewer",e.ownership=i}else t.collection.isPublic?e.ownership="public":t.collection.isTeam?e.ownership="team":e.ownership="private"};e.exports={convertIncomingData:e=>{l(e,a)},convertOutgoingData:e=>{l(e,c)},getGroupResponseData:e=>({id:e.id,name:e.name,classifier:e.classifierName,order:e.order,created_date:e.created,modified_date:e.modified}),getElementResponseData:_,getLibraryResponseData:(e,t={})=>{const i={id:e.id,name:e.name,created_date:e.created,modified_date:e.modified,toolkit_id:e.toolkitId,details:{num_elements:e.elements.length,num_archived_elements:e.removedElements.length}};i.groups=e.getGroups(/.*/).map(e=>({id:e.id,name:e.name,classifier:e.classifierName,order:e.order,created_date:e.created,modified_date:e.modified})),e.collection.isPrivate&&e.collection.getDefaultLibrary()===e&&(i.default=!0),m(i,e),t.includeElements&&(i.elements=e.elements.map(_)),t.includeSize&&(i.size=d(e)),t.includeRenditionGrid&&(i.rendition_grid=(e=>{if(0===e.elements.length)return null;const t=e.elements.concat().sort((e,t)=>t.modified-e.modified),i=e.elements.concat().sort((e,t)=>e.created-t.created);let n=i.find(e=>{const t=u(e);return t&&"href"===t.type});const o={};n&&(o.main=u(n));for(let e=0;e<i.length&&!o.main;e++)o.main=u(i[e])||null,n=o.main&&i[e];o.tiles=[];for(let e=0;e<t.length&&o.tiles.length<3;e++){if(t[e]===n)continue;const i=u(t[e]);i&&o.tiles.push(i)}return o})(e));const n=e.getValues();return n&&n.length>0&&(i.custom_data={},n.forEach(e=>i.custom_data[`${e.namespace}#${e.key}`]=e.value)),i},getPagedResponses:(e,t,i,n,o,r)=>{if(e.length<=n)return{pagedResults:e,isLastPage:!0};const s=o?r.findNextIndex(e,t,o,i):0;if(e.length<=s+n)return{pagedResults:e.slice(s),isLastPage:!0};let a=s+n-1;for(;e[a+1]&&e[a][t]===e[a+1][t];)a++;return{pagedResults:e.slice(s,a+1),isLastPage:e.length<=a+1,nextStartValue:e[a][t]}},getSortOrder:(e="")=>{const t=Object.keys(r);let[i,n]=e.split("-").reverse(),o=void 0===n;return t.includes(i)||(i=t[0],o=!1),{orderBy:i,isAscending:o}},updateCustomData:(e,t)=>{t.forEach(({namespace:t,key:i,value:n})=>{null!==n?e.setValue(t,i,n):e.removeValue(t,i)})},parseFilterField:(e,t)=>s[e]&&s[e](t),parseSortField:(e,t)=>r[e]&&r[e](t),parsePlaceholder:e=>{let t=e.match(/\$([0-9]+)\.([A-Za-z][A-Za-z0-9]*)/);if(t){const[,e,i]=t;return{index:parseInt(e),property:i}}}}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("os")},function(e,t,i){const n=i(97),o=i(1),r={};r[o.ACCESS_DENIED]=n.ForbiddenError,r[o.DELETED_LOCALLY]=n.NotFoundError,r[o.FILE_TOO_LARGE]=n.RequestEntityTooLargeError,r[o.INVALID_DATA]=n.BadRequestError,r[o.INVALID_PARAMETER]=n.BadRequestError,r[o.LOGGED_OUT]=n.UnauthorizedError,r[o.NOT_ALLOWED]=n.ForbiddenError,r[o.NOT_IMPLEMENTED]=n.NotImplementedError,r[o.NOT_SUPPORTED]=n.NotAcceptableError,r[o.READ_ONLY]=n.ForbiddenError,r[o.RENDITION_NOT_AVAILABLE]=n.NotFoundError,r[o.OUT_OF_SPACE]=n.InsufficientStorageError,r[o.URL_VALIDATION_FAILED]=n.BadRequestError,r[o.THUMBNAIL_NOT_AVAILABLE]=n.NotFoundError;const s={BadRequest:n.BadRequestError,InternalServer:n.InternalServerError,NotFound:n.NotFoundError,InsufficientStorage:n.InsufficientStorageError,Forbidden:n.ForbiddenError,PreconditionFailed:n.PreconditionFailedError,NotImplemented:n.NotImplementedError,GatewayTimeoutError:n.GatewayTimeoutError};e.exports={COLLECTION_NOT_FOUND:new n.InternalServerError("Cannot find private collection"),LIBRARY_NAME_MISSING:new n.BadRequestError("Library name is missing"),LIBRARY_ID_MISSING:new n.BadRequestError("Library id is missing"),LIBRARY_URL_MISSING:new n.BadRequestError("Library URL is missing"),LIBRARY_NOT_FOUND:new n.NotFoundError("Cannot find library"),LIBRARY_NOT_WRITABLE:new n.ForbiddenError("Library is read-only"),LIBRARY_NOT_ENOUGH_SPACE:new n.InsufficientStorageError("Library does not have enough space for new elements"),ELEMENT_NOT_FOUND:new n.NotFoundError("Cannot find element"),ELEMENT_IDS_MISSING:new n.BadRequestError("Element ids are missing"),ELEMENT_DATA_MISSING:new n.BadRequestError("Element data is missing"),ELEMENT_TYPE_MISSING:new n.BadRequestError("Element type is missing"),ELEMENT_BODY_MISSING:new n.BadRequestError("Element name or representation data or tag data is needed"),ELEMENT_NAME_INVALID:new n.BadRequestError("Element name must be a string"),ELEMENT_TAGS_INVALID:new n.BadRequestError("Element tags must be an array of strings"),RENDITION_PATH_NOT_FOUND:new n.NotFoundError("Cannot find rendition path"),RENDITION_PATH_NOT_CACHED:new n.GatewayTimeoutError("Rendition path not available in cache"),REPRESENTATION_DATA_MISSING:new n.BadRequestError("Representations are missing"),REPRESENTATION_NOT_FOUND:new n.NotFoundError("Cannot find representation"),REPRESENTATION_PATH_NOT_FOUND:new n.NotFoundError("Cannot find representation path"),REPRESENTATION_ID_NOT_RESOLVED:new n.BadRequestError("Representation id cannot be resolved"),REPRESENTATION_TYPE_MISSING:new n.BadRequestError("Representation type is missing"),REPRESENTATION_REL_MISSING:new n.BadRequestError("Representation relationship is missing"),REPRESENTATION_CHILDREN_INVALID:new n.BadRequestError("Representation children is invalid"),REPRESENTATION_REL_INVALID:new n.BadRequestError("Representation relationship is invalid"),REPRESENTATION_REL_PRIMARY_FOUND:new n.BadRequestError("Cannot have multiple primary representations"),REPRESENTATION_WIDTH_INVALID:new n.BadRequestError("Representation width is invalid"),REPRESENTATION_HEIGHT_INVALID:new n.BadRequestError("Representation height is invalid"),REPRESENTATION_CONTENT_LENGTH_INVALID:new n.BadRequestError("Representation content_length is invalid"),REPRESENTATION_CONTENT_LENGTH_UNEXPECTED:new n.BadRequestError("Representation content_length can only be used for an externally-linked representation"),REPRESENTATION_FULL_SIZE_INVALID:new n.BadRequestError("Representation is_full_size is invalid"),REPRESENTATION_SOURCE_MISSING:new n.BadRequestError("Representation source should have a URL or Path"),GROUP_NOT_FOUND:new n.NotFoundError("Cannot find group"),GROUP_NAME_MISSING:new n.BadRequestError("Group name is missing"),GROUP_ORDER_MISSING:new n.BadRequestError("Group order is missing"),GROUP_BODY_MISSING:new n.BadRequestError("Group name or order is needed"),NOTIFICATIONS_DATA_NOT_FOUND:new n.BadRequestError("Notification base data is missing"),EMPTY_SEARCH:new n.BadRequestError("Empty search query"),CONFLICTING_OWNERSHIP:new n.NotFoundError("Filters for ownership and library id conflict"),INVALID_MODIFIED_FILTER:new n.BadRequestError("Modified date filter is incorrectly formatted"),EMPTY_FILTERS:new n.BadRequestError("If a filter object is defined, it must have at least one property"),INCORRECT_LIMIT:new n.BadRequestError("Limit must be a positive integer"),INVALID_CUSTOM_DATA:new n.BadRequestError("Invalid custom data"),INVALID_GROUP_DATA:new n.BadRequestError("Invalid group data"),INVALID_UPDATE_REQUEST:new n.BadRequestError("Invalid Update Request"),INVALID_ETAG:new n.BadRequestError("Invalid eTag syntax. Missing double quotes"),INVALID_RENDITION_SIZE:new n.BadRequestError("Invalid rendition size"),INCORRECT_ETAG:new n.PreconditionFailedError("The if-match eTag does not match the library modified time"),INVALID_TRANSACTION_SYNTAX:new n.BadRequestError("Invalid syntax for batch request. Should be an Array of requests with a method, path, and optional body"),INVALID_TRANSACTION_PLACEHOLDER:new n.BadRequestError("Invalid placeholder in batch request"),INVALID_TRANSACTION_REQUEST:new n.BadRequestError("Request is invalid or not supported by the batch api"),NOT_IMPLEMENTED:new n.NotImplementedError("Not implemented yet"),getResponseError:(e,t)=>{let i="object"==typeof e?e.message:e;if(i=t?`${i}. ${t}`:i,e instanceof o){e=new(r[e.code]||n.InternalServerError)(i)}else if(e.code){if(e.message!==i){e=new(0,s[e.body&&e.body.code||e.code])(i)}}else e=new n.InternalServerError(i||e);return e}}},function(e,t,i){const{convertIncomingData:n,convertOutgoingData:o}=i(18),r=i(21),s=/"([0-9]+)"/;e.exports=class{constructor(e){this._server=e._server,this._ccLibraries=e._ccLibraries,this._routes=[]}_getRequestedModels(e,t,i){let n,o,a,c,l=e.headers["if-match"];if(l){const e=l.match(s);if(!e)return{error:r.INVALID_ETAG};l=parseInt(e[1])}const h=e.params.libraryId||e.body&&e.body.filters&&e.body.filters.library_id;if(h){if(n=this._ccLibraries.getLibraryById(h),!n||n.isDeletedFromServer)return{error:r.LIBRARY_NOT_FOUND};if(l&&l!==n.modified)return{error:r.INCORRECT_ETAG};if(t&&!n.isWritable)return{error:r.LIBRARY_NOT_WRITABLE}}return e.params.elementId&&(o=n.getElementById(e.params.elementId),!o||(i?!o.removed:o.removed))?{error:r.ELEMENT_NOT_FOUND}:e.params.representationId&&(a=o.getRepresentationById(e.params.representationId),!a)?{error:r.REPRESENTATION_NOT_FOUND}:e.params.groupId&&(c=n.getGroupById(e.params.groupId),!c)?{error:r.GROUP_NOT_FOUND}:{library:n,element:o,group:c,representation:a}}_addRoute(e,t,i,s,a){this._routes.push(this._server[e](t,(e,t)=>{const c=this._getRequestedModels(e,s,a),{library:l,element:h,group:d,representation:_,error:p}=c;if(p)return t.send(p);const u=(e.headers["x-client-version"]||1)<=2;u&&n(e.body),e.params.appName=e.headers["user-agent"],e.params.cacheControl=e.headers["cache-control"];try{Promise.resolve(i(e.params,e.body,d||_||h||l)).then(e=>{u&&o(e),t.send(e)}).catch(e=>{t.send(e)})}catch(e){t.send(r.getResponseError(e))}}))}_addPollingRoute(e,t,i){this._routes.push(this._server[e](t,(e,t)=>{if(!e.body)return t.send(r.NOTIFICATIONS_DATA_NOT_FOUND);const n=i(e.body,e=>{t.send(e)});n&&e.on("close",n)}))}_parseCustomData(e){const t=[];return e?Object.keys(e).every(i=>{const[n,o,...r]=i.split("#");return!!(!r.length&&n&&n.length&&o&&o.length&&n!==this._ccLibraries.getOption("DL_NAMESPACE"))&&(t.push({namespace:n,key:o,value:e[i]}),!0)})?t:void 0:t}dispose(){this._routes.forEach(e=>this._server.rm(e))}}},function(e,t){var i={},n={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/hyperstudio":["stk"],"application/illustrator":["ai"],"application/illustrator-text":["ai"],"application/illustrator.template":["ait"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js"],"application/json":["json"],"application/jsonml+json":["jsonml"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/photoshop":["psd"],"application/photoshop.large":["psb"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.ae.graphic+zip":["aegraphic","mogrt"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.animate-xfl+zip":["fla","xfl"],"application/vnd.adobe.animate-oam+zip":["oam"],"application/vnd.adobe.animate-sym+zip":["sym"],"application/vnd.adobe.animate-swf+zip":["swa"],"application/vnd.adobe.characterstyle+json":["style"],"application/vnd.adobe.characterstyle+snippet":["idms"],"application/vnd.adobe.charts+zip":["zip"],"application/vnd.adobe.ch.puppet+zip":["puppet"],"application/vnd.adobe.color+json":["ase"],"application/vnd.adobe.colortheme+json":["ase"],"application/vnd.adobe.cube+txt":["cube"],"application/vnd.adobe.element.agc+json":["agc"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.ibl.light+zip":["zip"],"application/vnd.adobe.illustrator.template":["ait"],"application/vnd.adobe.indesign-idms":["idms"],"application/vnd.adobe.indesign-idms-text":["idms"],"application/vnd.adobe.indesign.template":["indt"],"application/vnd.adobe.layerstyle":["asl"],"application/vnd.adobe.look+xml":["look"],"application/vnd.adobe.graphic+json":["json"],"application/vnd.adobe.mdl.material+zip":["zip"],"application/vnd.adobe.muse-collection":["muse"],"application/vnd.adobe.obj.3d+zip":["zip"],"application/vnd.adobe.paragraphstyle+json":["style"],"application/vnd.adobe.paragraphstyle+snippet":["idms"],"application/vnd.adobe.photoshop.template":["psdt"],"application/vnd.adobe.ppro.graphic+zip":["prgraphic","mogrt"],"application/vnd.adobe.ribbon.brush+zip":["brush"],"application/vnd.adobe.scatter.brush+zip":["brush"],"application/vnd.adobe.vector.brush+zip":["brush"],"application/vnd.adobe.text+json":["text-json"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["dmg"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/font-woff":["woff"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lzh-compressed":["lzh","lha"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdownload":["exe","dll","com","bat","msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","wmz","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-nzb":["nzb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-research-info-systems":["ris"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-wais-source":["src"],"application/x-x509-ca-cert":["der","crt"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/adpcm":["adp"],"audio/aif":["aif"],"audio/basic":["au","snd"],"audio/m4a":["m4a"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp4":["mp4a"],"audio/mpeg":["mpga","mp2","mp2a","m2a"],"audio/mpeg3":["mp3","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-wav":["wav"],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dng":["dng"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heif":["heif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/jpg":["jpg"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.adobe.photoshop.template":["psdt"],"image/vnd.adobe.pattern+png":["png"],"image/vnd.adobe.shape+svg":["shape"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.dvb.subtitle":["sub"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-adobe-dng":["dng"],"image/x-adobe-photoshop-brush":["abr"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-mrsid-image":["sid"],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.adobe.dn+dcx":["dn"],"model/vnd.adobe.dn+dcxucf":["dn"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache"],"text/calendar":["ics","ifb"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/sgml":["sgml","sgm"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-fortran":["f","for","f77","f90"],"text/x-java-source":["java"],"text/x-opml":["opml"],"text/x-pascal":["p","pas"],"text/x-nfo":["nfo"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/3gpp":["3gp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["mov","qt"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx","wmv"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-quicktime":["mov"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]},o={};Object.keys(n).forEach(e=>{n[e].forEach(t=>{o[t]=o[t]||[],o[t].push(e)})}),i.getExtensions=function(e){return e?n[e.toLowerCase()]||(t=e.toLowerCase(),(i=t.match(/application\/x-adobe-libraries-(.+)/))?[i[1]]:[]):[];var t,i},i.getMimeTypes=function(e){return e?o[e.toLowerCase()]||function(e){return["application/x-adobe-libraries-"+e]}(e.toLowerCase()):[]},Object.seal(i),e.exports=i},function(e,t){e.exports=require("https")},function(e,t,i){const n=i(26),o=i(112),r=i(114),s=i(117),a=i(49),c=i(50),l=i(4),h=i(2),d=i(11),_=i(51),p=i(28),u=i(46);function m(e,t){e&&d._setFS(e),this._compositeOptions=l.merge({},t),t&&t.logCallback&&l._setLogCallback(t.logCallback)}m.COLLABORATION={PRIVATE:n.COLLABORATION.PRIVATE,SHARED_BY_USER:n.COLLABORATION.SHARED_BY_USER,SHARED_WITH_USER:n.COLLABORATION.SHARED_WITH_USER},m.AdobeDCXError=h,m.FileContent=p,m.StreamProvider=u,m.prototype.newEmptyComposite=function(e,t,i,o){var r=new n(e,t,null,o,null,this._compositeOptions);return i&&(r.path=i),r},m.prototype.newCompositeFromLocalStorage=function(e,t){try{if("string"!=typeof e)throw new h(h.INVALID_PARAMS,"");var i=new n(null,null,e,null,null,this._compositeOptions);i.loadCurrentFromLocalStorage((function(e){t(e,e?void 0:i)})),i.deleteTempFiles()}catch(e){t(e)}},m.prototype.newCompositeWithHref=function(e,t,i,o,r){var s=new n(i,r,null,o,e,this._compositeOptions);return t&&(s.path=t),s},m.prototype.newCompositeAsCopyOf=function(e,t,i,o,r,s){return n.newCompositeAsCopyOf(e,t,i,o,r,s,this._compositeOptions)},m.prototype.copyCompositeAndAssetsFrom=function(e,t,i,o,r,s,a){n.copyCompositeAndAssetsFrom(e,t,i,o,r,s,this._compositeOptions,a)},m.prototype.createHTTPService=function(e){return new o(e)},m.prototype.createStorageSession=function(e,t,i,n){return new r(e,t,i,n)},m.prototype.createCommunitySession=function(e,t,i){return new s(e,t,i)},m.prototype.createPlatformSession=function(e,t,i,n){return new a(e,t,i,n)},m.prototype.compositeXfer=c,m.prototype.snapshot=_,e.exports=m},function(e,t,i){const n=i(2),o=i(27),r=i(45),s=i(110),a=i(36).STATES,c=i(11),l=i(4),h={PRIVATE:void 0,SHARED_BY_USER:"sharedByUser",SHARED_WITH_USER:"sharedWithUser"};function d(e,t,i,n,r,s){r=l.ensureRelativeHrefStartsWithSlash(r),this._options=s||{},i?this._setPath(i):r?(this._href=r,this._options.links&&(this._links=this._options.links),this._options.assetId&&(this._assetId=this._options.assetId),e&&(this._name=e),t&&(this._type=t),n&&(this._id=n)):t&&(this._current=new o,e&&(this._current._data.name=e),this._current._data.type=t,n&&(this._current.compositeId=n)),this._autoRemoveUnusedLocalFiles=!0,this._options.xhrBaseBranchSupport&&(this._baseBranchData=void 0,this._pushedBranchData=void 0,this._pulledBranchData=void 0),this._collaborationType=h.PRIVATE}d.newCompositeAsCopyOf=function(e,t,i,r,s,a,c){var h=e._core;if(h||e.current&&(h=e.current._core),!h)throw new n(n.INVALID_PARAMS,"compositeBranchOrElement must be a branch, an element or a composite with a current branch.");var _=new d(void 0,void 0,void 0,void 0,void 0,c);return r&&(_.path=r),_._current=o._newBranchAsCopyOfCore(h,this._localStorage),_.id=s||l.generateUuid(),t&&(_.name=t),i&&(_.type=i),a&&(_.href=a),c&&c.links&&(_.links=c.links),c&&c.assetId&&(_.assetId=c.assetId),_},d.copyCompositeAndAssetsFrom=function(e,t,i,r,a,c,_,p){var u=e._core;if(u||e.current&&(u=e.current._core),!u)throw new n(n.INVALID_PARAMS,"compositeBranchOrElement must be a branch, an element or a composite with a current branch.");var m=new d(void 0,void 0,void 0,void 0,void 0,_);r&&(m.path=r),o._newBranchAsCopyOfCoreWithAssets(u,m.path&&new s(m.path,_.preserveFileExtensions),(e,n)=>{if(e)return p(e);m._current=n,m.collaborationType=h.PRIVATE,a!==m.id&&(m.id=a||l.generateUuid()),t&&(m.name=t),i&&(m.type=i),c&&(m.href=c),p(null,m)})},d.COLLABORATION=h,Object.defineProperties(d.prototype,{id:{get(){return this._current?this._current.compositeId:this._id},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");this._current&&(this._current.compositeId=e),this._id=e}},name:{get(){return this._current?this._current.name:this._name},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");this._current&&(this._current.name=e),this._name=e}},type:{get(){return this._current?this._current.type:this._type},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");this._current&&(this._current.type=e),this._type=e}},href:{get(){return this._current?this._current.compositeHref:this._href},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");e=l.ensureRelativeHrefStartsWithSlash(e),this._current&&(this._current.compositeHref=e),this._href=e}},links:{get(){return this._current?this._current.compositeLinks:this._links},set(e){if("object"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting an object.");this._current&&(this._current.compositeLinks=e),this._links=e}},assetId:{get(){return this._current?this._current.compositeAssetId:this._assetId},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");this._current&&(this._current.compositeAssetId=e),this._assetId=e}},collaborationType:{get(){return this._current?this._current._collaborationType:this._collaborationType},set(e){if(e!==h.PRIVATE&&e!==h.SHARED_BY_USER&&e!==h.SHARED_WITH_USER)throw new n(n.INVALID_PARAMS,"Invalid value: ."+e);this._current&&(this._current._collaborationType=e),this._collaborationType=e}},clientDataString:{get(){return this._current?this._current._clientDataString:this._clientDataString},set(e){if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Invalid clientDataString: must be a string or undefined.");var t=this._options.maxClientDataLength||1024;if(e&&e.length>t)throw new n(n.INVALID_PARAMS,"Invalid clientDataString: cannot be greater than 1KB");this._current&&(this._current._clientDataString=e),this._clientDataString=e}},path:{get(){return this._path},set(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");this._setPath(e)}},isBound:{get(){return this._current&&this._current.isBound||!this._current&&this._href},set(){throw new n(n.READ_ONLY,"Cannot set the property isBound. Use resetIdentity or resetBinding instead.")}},hasLocalStorage:{get(){return this._localStorage},set(){throw new n(n.READ_ONLY,"Cannot set the property hasLocalStorage.")}},autoRemoveUnusedLocalFiles:{get(){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");return this._autoRemoveUnusedLocalFiles},set(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");this._autoRemoveUnusedLocalFiles=e}},clientDataStoragePath:{get(){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");return this._localStorage.clientDataPath()},set(){throw new n(n.READ_ONLY,'Property "clientDataStoragePath" is read-only.')}},current:{get(){return this._current},set(){throw new n(n.READ_ONLY,'Property "current" is read-only.')}}}),d.prototype.loadCurrentFromLocalStorage=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");var t=this;this._loadBranch(this._localStorage.currentManifestPath(),!1,(function(i,n){if(!i&&n)try{t._current=n,t._currentBranchCommittedAtDate=l.timeStamp(!0)}catch(e){i=e}e(i,i?void 0:n)}))},d.prototype.commitChanges=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");if(!this._current)return e(new n(n.INVALID_STATE,"Current branch is not in memory."));var t=this;c.writeFileAtomically(this._localStorage.currentManifestPath(),this._current.localData,"utf8",(function(i){if(!i)try{t._currentBranchCommittedAtDate=l.timeStamp(!0),t._current._isDirty=!1}catch(e){i=e}e(i)}))},d.prototype.tempAssetPath=function(){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");return this._localStorage.tempPathForComponent()},d.prototype.deleteTempFiles=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");this._localStorage.deleteTempFiles((function(t){e&&e(t)}))},d.prototype.removeUnusedLocalFiles=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");this._localStorage.removeUnusedLocalFiles(this._currentBranchCommittedAtDate,e)},d.prototype.removeLocalFilesForComponentsWithIDs=function(e,t){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");if(!e)throw new n(n.INVALID_PARAMS,"Param componentIds must not be nil.");var i=this,o=this._current;i._loadBranch(i._localStorage.currentManifestPath(),!0,(function(r,s){r&&"ENOENT"!==r.code?t([r]):i.loadBaseBranch((function(r,l){if(r&&"ENOENT"!==r.code)t([r]);else{var h,d,_=[],p={};for(h=0;h<e.length;++h){var u=e[h],m=o.getComponentWithId(u),g=s?s.getComponentWithId(u):void 0,f=l?l.getComponentWithId(u):void 0;if(!(m&&"/META-INF/metadata.xml"===m.absolutePath||g&&"/META-INF/metadata.xml"===g.absolutePath||f&&"/META-INF/metadata.xml"===f.absolutePath))if(m&&m.state===a.modified||g&&g.state===a.modified){var E=new n(n.COMPONENT_MODIFIED_ERROR,"Cannot remove the file of a modified component.");E.componentId=u,_.push(E)}else m&&(d=o.assetOfComponent(m))&&(void 0===p[d]&&(p[d]=u),i._localStorage.removeComponentAsset(m,o._local()),o._setDirty(!0)),g&&(d=s.assetOfComponent(g))&&void 0===p[d]&&(p[d]=u),f&&(d=l.assetOfComponent(f))&&void 0===p[d]&&(p[d]=u)}var y=Object.keys(p),v=y.length;if(v>0){var A=function(e){c.deleteFile(e,(function(i){i&&(i.componentId=p[e],_.push(i)),0===--v&&t(_.length>0?_:void 0)}))};for(h=0;h<y.length;++h)A(y[h])}else t(_.length>0?_:void 0)}}))}))},d.prototype.removeLocalStorage=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");if(!this._path)return e(new n(n.INVALID_STATE,"No path set."));c.deleteDirectory(this._path,e)},d.prototype.loadBaseBranch=function(e){if(!this._localStorage&&!this._baseBranchData)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");if(this._localStorage)this._loadBranch(this._localStorage.currentBaseManifestPath(),!0,e);else{var t,i;try{i=new o(void 0,!0).parse(this._baseBranchData)}catch(e){t=e}e(t,i)}},d.prototype.loadPulledBranch=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");this._loadBranch(this._localStorage.pulledManifestPath(),!1,e)},d.prototype.loadPushedBranch=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");this._loadBranch(this._localStorage.pushedManifestPath(),!1,e)},d.prototype.resolvePullWithBranch=function(e,t){if(!e)throw new n(n.INVALID_PARAMS,"Need a branch.");if(e===this._current)throw new n(n.INVALID_PARAMS,"Cannot resolve current.");if(this._localStorage&&!t)throw new n(n.INVALID_PARAMS,"Need a callback function.");var i=this,o=function(){e.readOnly=!1,e._collaborationType=i.collaborationType,e._clientDataString=i.clientDataString,i._current=e};if(this._localStorage)i._localStorage.resolvePulledBranch(e,(function(e){if(!e)try{o(),i._autoRemoveUnusedLocalFiles&&i._localStorage.removeUnusedLocalFiles(i._currentBranchCommittedAtDate,(function(){}))}catch(t){e=t}t(e,e?void 0:i._current)}));else{if(this._options.xhrBaseBranchSupport&&(this._baseBranchData=this._pulledBranchData,this._pulledBranchData=void 0),o(),!t)return this._current;t(void 0,this._current)}},d.prototype.acceptPush=function(e){if(this._localStorage&&!e)throw new n(n.INVALID_PARAMS,"Need a callback function.");var t,i,o=this,s=function(n){if(!n)if(t)try{o._localStorage?(t.applyToBranch(i),o._localStorage.acceptPushedBranch(i,(function(i){if(!i)try{t.applyToBranch(o._current,!0),o._autoRemoveUnusedLocalFiles&&o._localStorage.removeUnusedLocalFiles(o._currentBranchCommittedAtDate,(function(){}))}catch(e){i=e}e(i)}))):(t.applyToBranch(o._current,!0),o._options.xhrBaseBranchSupport&&(o._baseBranchData=o._pushedBranchData,o._pushedBranchData=void 0),o._pushJournal=void 0,e&&e())}catch(e){n=e}else e&&e();if(n){if(!e)throw n;e(n)}};if(!this._localStorage)return t=this._pushJournal,s();var a,c=2;r.readJournal(o._localStorage.pushJournalPath(),o,!1,(function(e,i){c--,a?s():(e?"ENOENT"!==e.code&&(a=new n(n.INVALID_STATE,"Failed to load push journal.",e)):t=i,c||s())})),this._loadBranch(this._localStorage.currentManifestPath(),!1,(function(e,t){c--,a?s():(e?a=new n(n.INVALID_STATE,"Failed to load current manifest.",e):i=t,c||s())}))},d.prototype.discardPulledBranch=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");var t=this;this._localStorage.discardPulledBranch((function(i){if(!i){try{t._autoRemoveUnusedLocalFiles&&t._localStorage.removeUnusedLocalFiles(t._currentBranchCommittedAtDate,(function(){}))}catch(e){i=e}e(i)}i&&e(i)}))},d.prototype.discardPushedBranch=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");var t=this;this._localStorage.discardPushedBranch((function(i){if(!i){try{t._autoRemoveUnusedLocalFiles&&t._localStorage.removeUnusedLocalFiles(t._currentBranchCommittedAtDate,(function(){}))}catch(e){i=e}e(i)}i&&e(i)}))},d.prototype.resetBinding=function(e){delete this._href,this._current&&this._current._resetBinding(),this._localStorage?this._discardEveryBranchButCurrent(e):(this._baseBranchData=void 0,this._pushedBranchData=void 0,this._pulledBranchData=void 0,e&&e())},d.prototype.resetIdentity=function(e){delete this._href,this._current?(this._current._resetIdentity(),this._id=this._current.compositeId):this._id=l.generateUuid(),this._localStorage?this._discardEveryBranchButCurrent(e):(this._baseBranchData=void 0,this._pushedBranchData=void 0,this._pulledBranchData=void 0,e&&e())},d.prototype.setLocalData=function(e,t){if(!this._current)throw new n(n.INVALID_STATE,"No current branch set.");this._current.setLocalData(e,t)},d.prototype.getLocalData=function(e){if(!this._current)throw new n(n.INVALID_STATE,"No current branch set.");return this._current.getLocalData(e)},d.prototype._loadBranch=function(e,t,i){if("function"!=typeof i)throw new n(n.INVALID_PARAMS,'Param "callback" must be a function.');var r=this;c.exists(e,(function(n){n?c.readFile(e,"utf8",(function(n,s){var a;if(!n)try{(a=new o(void 0,t,e).parse(s))._localStorage=r._localStorage}catch(e){n=e}i(n,a)})):i()}))},d.prototype._discardEveryBranchButCurrent=function(e){if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");var t,i=this,o=3,r=function(n){n&&!t&&(t=n),0===--o&&(!t&&i._autoRemoveUnusedLocalFiles&&i._localStorage.removeUnusedLocalFiles(i._currentBranchCommittedAtDate,(function(){})),e(t))};this._localStorage.discardPushedBranch(r),this._localStorage.discardPulledBranch(r),this._localStorage.discardBaseBranch(r)},d.prototype._setPath=function(e){this._localStorage?this._localStorage.compositePath=e:c.canUseFileSystem&&(this._localStorage=new s(e,this._options.preserveFileExtensions),this._current&&(this._current._localStorage=this._localStorage)),this._path=e},e.exports=d},function(e,t,i){var n=i(44),o=i(109),r=i(2),s=i(4);function a(e,t,i){e?e=this._setData(e,t):(e={"manifest-format-version":6,id:s.generateUuid()},this.originalManifestFormatVersion=6,this._core=new n(e,this,t),this._data=e);this._pendingElements=[],this.manifestPath=i}function c(e){var t=e["manifest-format-version"];if(t<6){if(t<4)throw new r(r.INVALID_DATA,"Encountered manifest format version "+e["manifest-format-version"]+". Format version conversion not yet implemented for that version.");t<5&&function e(t){var i,n,o=t.components;if(o)for(n=o.length,i=0;i<n;i++){delete o[i].localStorageAssetId}var r=t.children;if(r)for(n=r.length,i=0;i<n;i++)e(r[i])}(e),t<6&&function e(t,i){i&&t.path&&delete t.path;var n,o=t.components;if("object"==typeof o)for(n=0;n<o.length;n++){var r=o[n];"number"==typeof r.version&&(r.version=r.version.toString())}var s=t.children;if("object"==typeof s)for(n=0;n<s.length;n++){e(s[n])}}(e,!0)}}a._newBranchAsCopyOfCore=function(e,t){var i=new a(JSON.parse(JSON.stringify(e._data))),n=i._core;return i._localStorage=t,i._resetIdentity((function(i){var o=e.getComponentWithId(i.id);if(!o)throw new r(r.INVALID_STATE,"Could not find original component.");if("modified"===o.state||!o.etag)throw new r(r.INVALID_STATE,"Cannot create a new composite from a branch that contains modified or unbound components.");var s=e._getHrefOfComponent(o);if(!s)throw new r(r.INVALID_STATE,"Cannot determine the href of component id "+o.id);n._setSourceHrefOfComponent(s,i),t&&t.removeComponentAsset(i,n._local())})),i},a._newBranchAsCopyOfCoreWithAssets=function(e,t,i){const n=JSON.parse(JSON.stringify(e._data));n.children=[],n.components=[];const o=new a(n);o._localStorage=t,o._resetBinding();const r=e.getChildrenOf().map(e=>new Promise((t,i)=>{o.copyChild(e,o.rootNode,void 0,void 0,void 0,e=>e?i(e):t())})),s=e.getComponentsOf().map(e=>new Promise((t,i)=>{o.copyComponent(e,o.rootNode,void 0,void 0,e=>e?i(e):t())}));Promise.all([...r,...s]).then(()=>{o._reset(!0),i(null,o)},i)},Object.defineProperties(a.prototype,{compositeId:{get(){return this._core.rootNode.id},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e||""===e)throw new r(r.INVALID_PARAMS,"Expecting a non-empty string.");if(t._allNodes[e])throw new r(r.DUPLICATE_VALUE,"There is already a node with the same id.");delete t._allNodes[this._data.id],this._data.id=e,t._allNodes[e]=this._core.rootNode,t._setDirty()}},rootNode:{get(){return this._core.rootNode},set(e){this._core.rootNode=e}},name:{get(){return this._core.rootNode.name},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new r(r.INVALID_PARAMS,"Expecting a string or undefined.");t.rootNode.name=e}},type:{get(){return this._core.rootNode.type},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e||""===e)throw new r(r.INVALID_PARAMS,"Expecting a non-empty string.");t.rootNode.type=e}},compositeHref:{get(){return this._data.local?this._data.local.compositeHref:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new r(r.INVALID_PARAMS,"Expecting a string or undefined.");t._local().compositeHref=s.ensureRelativeHrefStartsWithSlash(e),t._setDirty(!0)}},compositeLinks:{get(){return this._data.local?this._data.local.links:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if(!s.validateLinks(e))throw new r(r.INVALID_PARAMS,"Expecting an object or undefined.");t._local().links=e,t._setDirty(!0)}},compositeAssetId:{get(){return this._data.local?this._data.local.assetId:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new r(r.INVALID_PARAMS,"Expecting a string or undefined.");t._local().assetId=e,t._setDirty(!0)}},_collaborationType:{get(){return this._data.local?this._data.local.collaborationType:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");e?t._local().collaborationType=e:delete t._local().collaborationType,t._setDirty(!0)}},_clientDataString:{get(){return this._data.local?this._data.local.clientDataString:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");e?t._local().clientDataString=e:delete t._local().clientDataString,t._setDirty(!0)}},manifestEtag:{get(){return this._data.local?this._data.local.manifestEtag:void 0},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new r(r.INVALID_PARAMS,"Expecting a string or undefined.");t._local().manifestEtag=e,t._setDirty(!0)}},compositeState:{get(){return this._data.state||"unmodified"},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new r(r.INVALID_PARAMS,"Expecting a string.");if("unmodified"!==e&&"modified"!==e&&"pendingDelete"!==e&&"committedDelete"!==e&&"pendingDiscard"!==e)throw new r(r.INVALID_PARAMS,'State must be "modified", "unmodified", "pendingDiscard", "pendingDelete", or "committedDelete".');if("pendingDelete"===e&&"committedDelete"===e&&("pending"===this.compositeArchivalState||"archived"===this.compositeArchivalState))throw new r(r.INVALID_STATE,"Cannot delete an archived composite.");this._data.state=e,t._setDirty(!0)}},compositeArchivalState:{get(){return this._core._local().archivalState||"active"},set(e){var t=this._core;if(t._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new r(r.INVALID_PARAMS,"Expecting a string.");if("pending"!==e&&"archived"!==e&&"active"!==e)throw new r(r.INVALID_PARAMS,'State must be "pending", "archived", or undefined.');if("archived"===this.compositeArchivalState)throw new r(r.INVALID_STATE,"Composite has already been archived.");if("active"!==e&&("pendingDelete"===this.compositeState||"committedDelete"===this.compositeState))throw new r(r.INVALID_STATE,"Cannot archive a deleted composite.");"active"===e?delete this._core._local().archivalState:this._core._local().archivalState=e,t._setDirty(!0)}},isBound:{get(){return this.manifestEtag&&this.compositeHref},set(){throw new r(r.READ_ONLY,"Cannot set the property isBound. Use resetIdentity instead.")}},_localStorage:{get(){return this._core._localStorage},set(e){this._core._localStorage=e}},hasLocalStorage:{get(){return this._core.hasLocalStorage},set(e){this._core.hasLocalStorage=e}},_isDirty:{get(){return this._core._isDirty},set(e){this._core._isDirty=e}},isDirty:{get(){return this._core.isDirty},set(e){this._core.isDirty=e}},localData:{get(){return this._core._stringify(!1)},set(){throw new r(r.READ_ONLY,"Cannot set the property localData.")}},prettifiedLocalData:{get(){return this._core._stringify(!1,!0)},set(){throw new r(r.READ_ONLY,"Cannot set the property localData.")}},remoteData:{get(){return this._core._stringify(!0)},set(){throw new r(r.READ_ONLY,"Cannot set the property remoteData.")}},pendingElements:{get(){return this._pendingElements},set(){throw new r(r.READ_ONLY,"Cannot set the property pendingElements.")}},changeCount:{get(){return this._core.changeCount},set(e){this._core.changeCount=e}},readOnly:{get(){return this._core._readOnly},set(e){this._core._readOnly=e}}}),a.prototype.parse=function(e){if("string"!=typeof e)throw new r(r.INVALID_PARAMS,'Param "data" must be a string');var t=null;try{t=JSON.parse(e)}catch(e){throw new r(r.INVALID_JSON,"Manifest could not be parsed. Underlying error: "+e.message)}return this._setData(t,this._core._readOnly)},a.prototype.getElementWithId=function(e){return this._createElement(this._core.getChildWithId(e))},a.prototype.getElementWithAbsolutePath=function(e){return this._createElement(this._core.getChildWithAbsolutePath(e))},a.prototype.addElement=function(e,t,i,n,o,s){if("string"!=typeof e)throw new r(r.INVALID_PARAMS,"Element must have a name of type string");if("string"!=typeof t)throw new r(r.INVALID_PARAMS,"Element must have a type of type string");if("string"!=typeof i)throw new r(r.INVALID_PARAMS,"Element must have a path of type string");var a=this._core.addChild(e,n,o,s);try{a.path=i}catch(e){throw this._core.removeChild(a),e}return a._data.type=t,this._createElement(a)},a.prototype.updateElement=function(e){var t=this.getChildWithId(e.rootNode.id);if(!t)throw new r(r.INVALID_PARAMS,"Element does not exist in branch.");var i=this._core.replaceChild(e.rootNode,t.path);return this._deleteElement(e),i},a.prototype.abandonElement=function(e){this._deleteElement(e)},a.prototype.getChildWithId=function(e){return this._core.getChildWithId(e)},a.prototype.getChildWithAbsolutePath=function(e){return this._core.getChildWithAbsolutePath(e)},a.prototype.getChildrenOf=function(e){return this._core.getChildrenOf(e)},a.prototype.addChild=function(e,t,i,n){return this._core.addChild(e,t,i,n)},a.prototype.removeChild=function(e){return this._core.removeChild(e)},a.prototype.moveChild=function(e,t,i){return this._core.moveChild(e,t,i)},a.prototype.copyChild=function(e,t,i,n,o,r){return this._core.copyChild(e,t,i,n,o,r)},a.prototype.replaceChild=function(e,t,i,n){return this._core.replaceChild(e,t,i,n)},a.prototype.allComponents=function(){return this._core.allComponents()},a.prototype.getComponentWithId=function(e){return this._core.getComponentWithId(e)},a.prototype.getComponentWithAbsolutePath=function(e){return this._core.getComponentWithAbsolutePath(e)},a.prototype.getComponentsOf=function(e){return this._core.getComponentsOf(e)},a.prototype.addComponent=function(e,t,i,n,o,r,s,a,c,l){return this._core.addComponent(e,t,i,n,o,r,s,a,c,l)},a.prototype.addComponentWithUploadResults=function(e,t,i,n,o){return this._core.addComponentWithUploadResults(e,t,i,n,o)},a.prototype.updateComponent=function(e,t,i,n){return this._core.updateComponent(e,t,i,n)},a.prototype.updateComponentWithUploadResults=function(e,t){return this._core.updateComponentWithUploadResults(e,t)},a.prototype.removeComponent=function(e){return this._core.removeComponent(e)},a.prototype.moveComponent=function(e,t){return this._core.moveComponent(e,t)},a.prototype.copyComponent=function(e,t,i,n,o){return this._core.copyComponent(e,t,i,n,o)},a.prototype.replaceComponent=function(e,t,i,n){return this._core.replaceComponent(e,t,i,n)},a.prototype.assetOfComponent=function(e,t){return this._core.assetOfComponent(e,t)},a.prototype.copy=function(){var e=new a(JSON.parse(JSON.stringify(this._data)));return e._localStorage=this._localStorage,e},a.prototype.setLocalData=function(e,t){if("string"!=typeof e)throw new r(r.INVALID_DATA,"Local data key must be a string.");if(this._local().customData=this._local().customData||{},Object(t)===t)try{JSON.stringify(t)}catch(e){throw new r(r.INVALID_DATA,"Local data value must be serializable.",e)}this._local().customData[e]=t,this._setDirty(!0)},a.prototype.getLocalData=function(e){if("string"!=typeof e)throw new r(r.INVALID_DATA,"Local data key must be a string.");return this._local().customData&&this._local().customData[e]},a.prototype._createElement=function(e){var t;if(e){var i=JSON.parse(JSON.stringify(e._data));i["manifest-format-version"]=this._data["manifest-format-version"],delete i.path,(t=new o(i,this,this._core._readOnly))&&this._localStorage&&(t._localStorage=this._localStorage,t._updateLocalDataFromBranch(this),this._localStorage.registerInMemoryBranchOrElement(t))}return t&&this._pendingElements.push(t),t},a.prototype._deleteElement=function(e){var t=this._pendingElements.indexOf(e);if(t<0)throw new r(r.INVALID_PARAMS,"Unknown element.");this._pendingElements.splice(t,1),this._localStorage&&this._localStorage.unregisterInMemoryBranchOrElement(e)},a.prototype._updateLocalDataFromBranch=function(e){if(this._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");if(!this._localStorage)throw new r(r.NO_LOCAL_STORAGE,"No local storage.");if(!e._localStorage)throw new r(r.NO_LOCAL_STORAGE,"No local storage for source.");if(this._localStorage.compositePath!==e._localStorage.compositePath)throw new r(r.INVALID_PARAMS,"Branches must have same storage path.");this._core._localStorage.copyLocalStorageData(e,e._core._local(),this,this._core._local()),this._core._copySourceHrefsFrom(e._core)},a.prototype._verify=function(e){return"string"!=typeof e.id?new r(r.INVALID_DATA,"Manifest is missing an id of type string"):"string"!=typeof e.name?new r(r.INVALID_DATA,"Manifest is missing a name of type string"):"string"!=typeof e.type?new r(r.INVALID_DATA,"Manifest is missing a type of type string"):"number"!=typeof e["manifest-format-version"]?new r(r.INVALID_DATA,"Manifest is missing a manifest-format-version of type number"):null},a.prototype._setData=function(e,t){this.originalManifestFormatVersion=e["manifest-format-version"],c(e),e.local&&(e.local.version=2);var i=this._verify(e);if(null===i)return e["manifest-format-version"]=6,this._core=new n(e,this,t),this._data=e,this;throw i},a.prototype._reset=function(e,t){if(this._readOnly)throw new r(r.READ_ONLY,"This object is read-only.");this._data.local&&(delete this._data.local.manifestEtag,delete this._data.local.compositeHref,delete this._data.local.compositeLinks,delete this._data.local.compositeAssetId,delete this._data.local.customData),e||(this._data.id=s.generateUuid()),this._data.state="modified",this._core._recursiveReset(this._data,t),this._core._setDirty()},a.prototype._resetBinding=function(e){this._reset(!0,e)},a.prototype._resetIdentity=function(e){this._reset(!1,e)},a.prototype._local=function(){return this._core._local()},a.prototype._setDirty=function(e){this._core._setDirty(e)},a.prototype._setPathOfNode=function(e,t){this._core._setPathOfNode(e,t)},a.prototype._verifyIntegrity=function(e,t,i){return this._core._verifyIntegrity(e,t,i)},e.exports=a},function(e,t){e.exports=class{constructor(e,t,i){this.filename=e,this.size=t,this.range=i}}},function(e,t){e.exports=require("xml2js")},function(e,t){e.exports=require("ws")},function(e){e.exports=JSON.parse('{"name":"cc-libraries-api-js","version":"3.8.27","private":true,"description":"Adobe Creative Cloud Libraries API for JavaScript","dependencies":{"dcx-js":"git+ssh://git@git.corp.adobe.com:ProjectCentral/dcx-js.git#v1.7.69","fs-extra":"8.1.0","glob":"7.1.1","node-fetch":"2.6.0","punycode":"2.1.1","uuid":"3.3.2","uuid-browser":"3.1.0","yauzl":"2.9.1","yazl":"2.4.3"},"optionalDependencies":{"@ccx-public/ingest":"^3.5.0","bufferutil":"4.0.1","ffi-napi":"git+ssh://git@git.corp.adobe.com:ProjectCentral/node-ffi-napi-temp.git#2.4.6-sigfix","font-manager":"git+ssh://git@git.corp.adobe.com:ProjectCentral/font-manager.git#v0.3.8","fs-ext":"2.0.0","image-size":"0.6.2","node-ProxyResolver":"git+ssh://git@git.corp.adobe.com:ProjectCentral/node-ProxyResolver.git#v2.0.2","node-thumbnailgenerator":"git+ssh://git@git.corp.adobe.com:ProjectCentral/node-ThumbnailGenerator.git#v2.0.5","node-vulcanjs":"git+ssh://git@git.corp.adobe.com:slade/VulcanJS.git#v1.3.1","node_ssl":"git+ssh://git@git.corp.adobe.com:ProjectCentral/node_ssl.git#v1.3.0","node-ngl":"git+ssh://git@git.corp.adobe.com:ProjectCentral/node-ngllib-prebuilt.git#v1.0.11","fs-xtra":"git+ssh://git@git.corp.adobe.com:ProjectCentral/fs-xtra.git#v1.0.3","ref-napi":"1.4.2","restify":"7.2.1","ws":"7.2.3","xml2js":"0.4.23"},"devDependencies":{"7zip":"0.0.6","@adobe/tessa-npm-plugin":"^1.0.1","@babel/core":"^7.1.2","@babel/preset-env":"^7.1.0","@ccx/hyperdrive-builder":"git+ssh://git@git.corp.adobe.com:CCX/hyperdrive-builder.git#v3.0.45","babel-loader":"^8.0.4","fetch":"^1.1.0","grunt":"1.0.1","grunt-contrib-clean":"1.0.0","grunt-contrib-compress":"1.3.0","grunt-contrib-copy":"1.0.0","grunt-eslint":"21.0.0","grunt-jsdoc":"2.4.0","grunt-node-gyp":"4.0.0","ignore-loader":"^0.1.2","ink-docstrap":"1.3.2","jasmine-node":"1.14.5","jsftp":"2.1.3","markdown-toc":"^1.2.0","matchdep":"1.0.1","mkdirp":"0.5.1","mockery":"2.0.0","mustache":"2.3.0","nock":"9.0.14","nyc":"^15.0.0","raw-loader":"^0.5.1","request":"2.87.0","request-promise-native":"^1.0.7","sugar":"1.4.1","webpack":"^4.20.2","webpack-node-externals":"^1.7.2","zock":"git+ssh://git@git.corp.adobe.com:DMA/zock.git#master"},"engines":{"node":">=12.14.0"},"bin":{"cc-libraries":"./scripts/cli"},"main":"src/main.js","scripts":{"test":"nyc grunt test","testWithoutCoverage":"grunt test","install":"node ./scripts/skip_native || node-gyp rebuild","linter":"grunt linter","tessa":"tessa-npm-plugin update","tessa-plugin-pr":"tessa-npm-plugin check --errorOnNewVulnerability","start":"node server","debug":"node server.js --debug","generate-rest-docs-toc":"markdown-toc -i --maxdepth=4 \'./technical_specs/Server REST API.md\'"},"cepPanels":["2.6.64","2.10.86","2.11.27","2.13.141","3.4.23","3.8.294"],"thor":[{"product":"ACCC","subproduct":"Application","version":"5.1.0","certification":"Release Candidate","name":"ACCCx5_1_0_{{build}}","volume":"Creative Cloud","build":"^\\\\d+$"},{"product":"ACCC","subproduct":"HDSetup","version":"5.1.0","certification":"Release Candidate","name":"HDSetup","volume":"Release"}]}')},function(e,t,i){var n=i(17),o={},r={obtainLock:function(e,t){o[e]||(o[e]=new n),o[e].obtain(t)},releaseLock:function(e){o[e]&&o[e].release()},isLocked:function(e){return!!o[e]&&o[e].isLocked()},hasPendingRequest:function(e){return!!o[e]&&o[e].hasPendingRequest()}};e.exports=r},function(e,t,i){var n=i(12),o={getStockData:function(e){return e&&e.getValue(n.STOCK_NAMESPACE,n.STOCK_DATA_KEY)},getStockDataForElement:function(e,t,i){var n=void 0===t?e.getPrimaryRepresentation():e.representations[t],r=o.getStockData(n);return r&&n.isExternalLink&&(e._config.shouldPrefetchExternalLink(n)&&!n.getCachedContentPath()||n.getCachedExternalLinkError())?o.getStockDataForElement(e,void 0===t?0:t+1,i||r.content_id):(!r&&i&&(r={content_id:i}),r)},getElementStockId:function(e){var t=o.getStockDataForElement(e);if(t)return String(t.content_id)},getElementStockLicense:function(e){var t=o.getStockDataForElement(e);if(t&&t.state===n.STOCK_STATE_PURCHASED)return String(t.license)}};e.exports=o},function(e,t){e.exports=require("url")},function(e,t){e.exports=require("crypto")},function(e,t,i){var n=i(2),o=i(4);function r(e,t){e?this._setData(e):this._data={},this._readOnly=t}var s={unmodified:"unmodified",modified:"modified",pendingDiscard:"pendingDiscard",pendingDelete:"pendingDelete",committedDelete:"committedDelete"};r.STATES=s,r._UploadResults=function(e){this.compositeId=e,this.records={}},r._UploadRecord=function(e,t,i,n,o,r){this.id=e,this.etag=t,this.version=i,this.md5=n,this.length=o,this.type=r},Object.defineProperties(r.prototype,{id:{get(){return this._data.id},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(this._owner)throw new n(n.READ_ONLY,"Cannot change the id of a component that is part of a branch or element.");if("string"!=typeof e||""===e)throw new n(n.INVALID_PARAMS,"Expecting a non-empty string.");this._data.id=e,this._setDirty()}},name:{get(){return this._data.name},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.name=e,this._setDirty()}},type:{get(){return this._data.type},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e||""===e)throw new n(n.INVALID_PARAMS,"Expecting a non-empty string.");this._data.type=e,this._setDirty()}},path:{get(){return this._data.path},set(e){if(this._data.path!==e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!o.isValidPath(e))throw new n(n.INVALID_PARAMS,"Expecting a valid path.");this._owner?this._owner._core._setPathOfComponent(this,e):(this._data.path=e,this._parentPath=""),this._setDirty()}}},parentPath:{get(){return this._parentPath},set(){throw new n(n.READ_ONLY,"parentPath is read-only.")}},absolutePath:{get(){return this._data.path&&this._owner?o.appendPathElements(this._parentPath,this._data.path):void 0},set(){throw new n(n.READ_ONLY,"absolutePath is read-only.")}},relationship:{get(){return this._data.rel},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.rel=e,this._setDirty()}},state:{get(){return this._data.state},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string.");if(!s.hasOwnProperty(e))throw new n(n.INVALID_PARAMS,'State must be "modified", "unmodified", "pendingDiscard", "pendingDelete", or "committedDelete".');this._data.state=e,this._setDirty()}},etag:{get(){return this._data.etag},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.etag=e,this._setDirty()}},md5:{get(){return this._data.md5},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.md5=e,this._setDirty()}},version:{get(){return this._data.version},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(void 0!==e&&"string"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.version=e,this._setDirty()}},length:{get(){return this._data.length},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("number"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a number or undefined.");this._data.length=e,this._setDirty()}},width:{get(){return this._data.width},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("number"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a number or undefined.");this._data.width=e,this._setDirty()}},height:{get(){return this._data.height},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("number"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a number or undefined.");this._data.height=e,this._setDirty()}}});var a={name:!0,id:!0,state:!0,path:!0,rel:!0,type:!0,etag:!0,length:!0,version:!0,md5:!0,width:!0,height:!0};r.prototype.getCustomKeys=function(){var e,t=[],i=Object.keys(this._data),n=i.length;for(e=0;e<n;e++){var o=i[e];a[o]||t.push(o)}return t},r.prototype.getValue=function(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');return this._data[e]},r.prototype.setValue=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');this._data[e]=t,this._setDirty()},r.prototype.removeValue=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');delete this._data[e],this._setDirty()},r.prototype.getLink=function(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');return this._data._links?this._data._links[e]:void 0},r.prototype.setLink=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("object"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "link" must be an object.');if("string"!=typeof t)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');var i=this._data._links;i||(i=this._data._links={}),i[t]=e,this._setDirty()},r.prototype.removeLink=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');var t=this._data._links;t&&(delete t[e],Object.keys(t).length<1&&delete this._data._links,this._setDirty())},r.prototype.isEqualTo=function(e,t){return o.objectsEqual(this._data,e._data,t)},r.prototype._setData=function(e){var t=this._verify(e);if(null===t)return this._data=e,this;throw t},r.prototype._setDirty=function(){this._owner&&this._owner._setDirty()},r.prototype._verify=function(e){return"string"!=typeof e.id?new n(n.INVALID_DATA,"Component is missing an id of type string"):null},e.exports=r},function(e,t,i){const n=i(2),o=i(123),r=i(124),s=i(1),a=i(17),c=i(10),l=i(6),h=i(23),d=i(3),_=i(127),p=i(8).promisify;e.exports=class{constructor(e,t,i){if(this._collection=e,this._dcxComposite=t,this._dcxBranch=t.current,this._listenerManager=new d(["change"],e=>this._services.log(e)),i?(this._publicId=i,this._writable=!1):this._collection.isTeam?this._writable=this._collection.isWritable:this._writable=!0,this._filterCache={},this._renditionCache=new _(this),this._autoGCMode={},this._transactionCount=0,this._commitInProgress=!1,this._pendingCommit=!1,this._onCommitCallbacks=[],this._dcxLock=new a,this._networkLock=new a,this._syncState=void 0,this._deletedLocally=!1,this._deletedFromServer=!1,this._waitForSyncToFinishCallbacks=[],this._errors=[],this._pushFailedDueToQuota=!1,this._numUpdateConflicts=0,this._numActiveCopyNodeOperations=0,this._pendingCopyNodeOperations=[],this._dcxBranch.getChildrenOf().forEach(e=>{e.name===this._config.ELEMENTS_NAME&&(this._dcxElementsNode=e),e.name===this._config.REMOVED_ELEMENTS_NAME&&(this._dcxRemovedElementsNode=e),e.name===this._config.GROUPS_NAME&&(this._dcxGroupsNode=e)}),this._dcxElementsNode||(this._dcxElementsNode=this._dcxBranch.addChild(this._config.ELEMENTS_NAME)),this._dcxCompositeRenditionMap=c.getCompositeRenditionMap(this._dcxBranch),this._elements=[],this._removedElements=[],this._groups=[],this._dcxBranch.getChildrenOf(this._dcxElementsNode).forEach(e=>{const t=new r(this,e);this._addElementToFilter(t),this._elements.push(t)}),this._dcxRemovedElementsNode){this._dcxBranch.getChildrenOf(this._dcxRemovedElementsNode).forEach(e=>{const t=new r(this,e);this._removedElements.push(t)}),this._sortRemovedElements()}if(this._dcxGroupsNode){this._dcxBranch.getChildrenOf(this._dcxGroupsNode).forEach(e=>{const t=new o(this,e);this._groups.push(t)})}this._services.hasFileSystem()||(this._dcxBaseBranch=this._dcxBranch.copy())}get _services(){return this._collection._services}get _config(){return this._collection._config}get _analytics(){return this._collection._analytics}get _storageInterface(){return this._collection._storageInterface}get _localisation(){return this._collection._localisation}_getRemovedElementsNode(){return this._dcxRemovedElementsNode||(this._dcxRemovedElementsNode=this._dcxBranch.addChild(this._config.REMOVED_ELEMENTS_NAME)),this._dcxRemovedElementsNode}_getGroupsNode(){return this._dcxGroupsNode||(this._dcxGroupsNode=this._dcxBranch.addChild(this._config.GROUPS_NAME)),this._dcxGroupsNode}_markDeletedLocally(e){this._deletedLocally=e,this._elements.forEach(t=>{t._markDeletedLocally(e)}),this._groups.forEach(t=>{t._markDeletedLocally(e)}),e&&this._listenerManager.removeAll()}_removeAllListeners(){this._listenerManager.removeAll(),this._elements.forEach(e=>{e._removeAllListeners()})}_toJSON(){return{id:this.id,name:this.name,elements:this._elements.map(e=>e._toJSON()),renditionCache:this._renditionCache.serializeCache(),groups:this._groups.map(e=>e._toJSON())}}_getRenditionCache(){const e={},t=t=>{e[t.id]=JSON.parse(JSON.stringify(t._renditionCache))};return this._elements.forEach(t),this._removedElements.forEach(t),e}_doCommitCallbacks(e){const t=this._onCommitCallbacks;this._onCommitCallbacks=[],t.forEach(t=>{t.waitForSuccess&&!e?this._onCommitCallbacks.push(t):this._waitForCommit(t.callback)})}_doCommit(e){const t=()=>{if(e&&!this._config.SHARED_LOCAL_STORAGE){if(this._deletedLocally)return;this._collection._clearSyncErrors(),this._push(),this._collection._resetPollBackoff()}},i=e=>{this._doCommitCallbacks(e),t()};if(!this._services.hasFileSystem())return void i();if(this._commitInProgress)return void(this._pendingCommit=!0);this._commitInProgress=!0;const n=(e,t)=>{e&&(e=l.getCommitError(e,this.id,t)),this._collection._reportCommitError(e)};this._storageInterface.commitManifest(this,(t,o)=>{n(t,"Failed to write composite to disk"),this._commitInProgress=!1,this._pendingCommit?(this._pendingCommit=!1,0===this._transactionCount&&this._doCommit(e)):i(o)})}_waitForCommit(e,t){this._commitInProgress||this._transactionCount>0?this._onCommitCallbacks.push({callback:e,waitForSuccess:t}):this._renditionCache._waitForCommit(e)}_notifyChange(){this._listenerManager.notify("change"),this._collection._notifyChange()}_commit(e,t){0===this._transactionCount&&(t||(this._updateModifiedTime(),this._notifyChange()),this._doCommit(!e))}_unblockCommits(){this._commitInProgress||0!==this._transactionCount||(this._services.log("Unblocking queued commits"),this._doCommitCallbacks(!0))}_wrapOperation(e,t){let i;this._beginOperation();try{i=e.call(t)}catch(e){throw this._transactionCount--,e}return this._endOperation(),i}_beginOperation(){this._transactionCount++}_endOperation(){this._transactionCount--,this._commit()}_updateModifiedTime(){const e=Date.now();this._dcxBranch.rootNode.setValue(this._config.MODIFIED_KEY,e)}_updateCreatedTime(){const e=Date.now();this._dcxBranch.rootNode.setValue(this._config.CREATED_KEY,e),this._dcxBranch.rootNode.setValue(this._config.MODIFIED_KEY,e)}_getMissingLocalComponents(){return this._elements.reduce((e,t)=>e.concat(t._getMissingLocalComponents()),[])}_gcLocalData(e){const t=[],i={},n=[];if(this._removedElements.forEach(e=>{e._shouldGCLocalData()&&(t.push(e),e._forEachRepresentation(e=>{const t=e._dcxComponent,o=e._getCurrentComponentPath();t&&o&&t.etag&&"modified"!==t.state?(i[o]=i[o]||[],i[o].push(t.id)):o&&n.push(o)}))}),0===t.length)return void e(null);n.forEach(e=>{delete i[e]}),this._elements.forEach(e=>{e._forEachRepresentation(e=>{const t=e._getCurrentComponentPath();t&&delete i[t]})});const o=[];Object.keys(i).forEach(e=>{o.push.apply(o,i[e])}),t.forEach(e=>this._renditionCache.clearCache(e)),this._services.log("Removing local files for components: [ "+o.join(", ")+" ]"),this._dcxComposite.removeLocalFilesForComponentsWithIDs(o,e)}_checkRenditionType(e,t){if(!e||-1===this._config.VALID_LIBRARY_RENDITION_TYPES.indexOf(e)){if(t)return t(new s(s.INVALID_PARAMETER,"composite rendition type not supported: "+e)),!1;throw new s(s.INVALID_PARAMETER,"composite rendition type not supported: "+e)}return!0}_setRenditionFromPath(e,t,i,n){if(c.checkDeletedState(this,n))return;const o=this._dcxCompositeRenditionMap[e],r=t&&this._services.getFileNameFromPath(t),s=this._services.fileUtils.getFileExtension(r),a=this._services.uuid()+"."+s;this._services.fileUtils.checkFileSize(t,s=>{s?n(s):this._storageInterface.notifyStartWrite(this,[],()=>{this._dcxBranch.addComponent(r,i,"rendition",a,t,!0,void 0,this._dcxBranch.rootNode,void 0,(t,i)=>{t?n(t):c.checkDeletedState(this,n)||(i.setValue(this._config.MODIFIED_KEY,Date.now()),i.setValue(this._config.RENDITION_TYPE_KEY,e),o&&this._dcxBranch.removeComponent(o),this._dcxCompositeRenditionMap=c.getCompositeRenditionMap(this._dcxBranch),this._commit(),n(null))})})})}_setRendition(e,t,i,n,o){const r=this._services.fs;let s;const a=t=>{t?o(l.getCommitError(t,this.id,"error writing library rendition")):c.checkDeletedState(this,o)||this._setRenditionFromPath(e,s,n,o)},d=this.collection._getTempDir();this._services.fileUtils.ensurePathExists(d,e=>{if(e)return void o(l.getCommitError(e,this.id,"error creating temp directory"));if(c.checkDeletedState(this,o))return;const _=h.getExtensions(n)[0],p=this._services.uuid()+"."+_;s=d+this._services.getPathSeparator()+p,"buffer"===i?r.writeFile(s,t,a):r.writeFile(s,t,i,a)})}_setRenditionInBrowser(e,t,i,n){const o=this._dcxCompositeRenditionMap[e],r=this._collection._syncManager,s=this._services.uuid();r.uploadNewComponentForLibrary(t,s,i,"rendition",this,(t,i)=>{t?n(t):c.checkDeletedState(this,n)||(i.setValue(this._config.MODIFIED_KEY,Date.now()),i.setValue(this._config.RENDITION_TYPE_KEY,e),o&&this._dcxBranch.removeComponent(o),this._dcxCompositeRenditionMap=c.getCompositeRenditionMap(this._dcxBranch),this._commit(),n(null))})}_getFilterKey(e){return e&&-1!==this._config.ELEMENT_TYPE_FILTERS.indexOf(e)?e:"*"}_removeElementFromFilter(e){const t=this._getFilterKey(e.type);if(this._filterCache[t]){const i=this._filterCache[t].indexOf(e);-1!==i&&this._filterCache[t].splice(i,1)}}_addElementToFilter(e){const t=this._getFilterKey(e.type);this._filterCache[t]=this._filterCache[t]||[],this._filterCache[t].push(e)}_doCreateGroup(e,t,i){const n=this._getGroupsNode(),r=this._dcxBranch.addChild(e,void 0,void 0,n);r.type=this._config.GROUP_TYPE,r.setValue(this._config.CLASSIFIER_KEY,i),r.setValue(this._config.ORDER_KEY,t);const s=new o(this,r);return s._updateCreatedTime(),this._groups.push(s),s}_doRemoveGroup(e,t){const i=this._groups.indexOf(e);this._groups.splice(i,1),this.elements.slice().forEach(i=>{void 0!==i.getOrderInGroup(e)&&(i._doSetOrderInGroup(e,void 0,!0),t&&t(i))}),this._dcxBranch.removeChild(e._dcxNode),e._markDeletedLocally(!0)}_getNumberOfElementsInGroup(e){if(e)return this.elements.reduce((t,i)=>t+i.getOrderInGroup(e)!==void 0?1:0,0)}_doCopyGroup(e,t,i,n,o){const r=e.library!==t&&t._groups.every(t=>t.id!==e.id)?e.id:this._services.uuid();this._doCopyDCXGroup(e,t,i,n,r,o)}_doCopyDCXGroup(e,t,i,n,r,s){t._beginOperation(),n&&this._beginOperation();const a=e=>{t._endOperation(),n&&this.endOperation(),s(e)};this._storageInterface.notifyStartWrite(t,[this],()=>{const l=t._getGroupsNode();t._dcxBranch.copyChild(e._dcxNode,l,void 0,r,r,(r,l)=>{if(c.checkDeletedState(this,s))return;if(r)return void a(r);const h=new o(t,l);t._groups.push(h);const d=()=>{c.checkDeletedState(this,s)||(t._endOperation(),n&&(this._doRemoveGroup(e),this.endOperation()),s(null,h))};if(!i)return void d();const _=this.elements.filter(t=>void 0!==t.getOrderInGroup(e)),u=p(this._doCopyElement.bind(this));Promise.all(_.map(e=>u(e,t,n))).then(t=>{_.forEach((i,n)=>{const o=i.getOrderInGroup(e),r=t[n];r._doSetOrderInGroup(h,o,!0),this._analytics.reportCopyElement(r,i)}),d()}).catch(a)})})}_doCreateElement(e,t){const i=this._dcxBranch.addChild(e,void 0,void 0,this._dcxElementsNode);i.path=i.id,i.type=t;const n=new r(this,i);return n._updateCreatedTime(),this._elements.push(n),this._addElementToFilter(n),n}_doRemoveElement(e,t){let i=this._elements.indexOf(e);-1!==i&&this._elements.splice(i,1),i=this._removedElements.indexOf(e),-1!==i&&this._removedElements.splice(i,1),this._removeElementFromFilter(e),t&&this._dcxBranch.removeChild(e._dcxNode),e._markDeletedLocally(!0)}_ensureRemovedElementsSpace(){for(;this.removedElements.length>=this._config.MAX_REMOVED_ELEMENTS;)this._doRemoveElement(this.removedElements[0],!0)}_sortRemovedElements(){this._removedElements.sort((e,t)=>e.removed-t.removed)}_doMarkElementRemoved(e,t){const i=this._elements.indexOf(e);-1!==i&&(this._ensureRemovedElementsSpace(),this._elements.splice(i,1),this._removeElementFromFilter(e),this._removedElements.push(e),this._sortRemovedElements(),t&&(e._dcxNode=this._dcxBranch.moveChild(e._dcxNode,void 0,this._getRemovedElementsNode()),e._updateTimestampOnRemove()))}_doRestoreElement(e,t){const i=this._removedElements.indexOf(e);-1!==i&&(this._removedElements.splice(i,1),this._elements.push(e),this._addElementToFilter(e),t&&(e._dcxNode=this._dcxBranch.moveChild(e._dcxNode,void 0,this._dcxElementsNode),e._updateTimestampOnRestore(),e._stripObsoleteGroupsData()))}_doCopyDCXNode(e,t,i,n,o){if(this._numActiveCopyNodeOperations<this._config.MAX_DCX_CONCURRENT_COPIES)return this._numActiveCopyNodeOperations++,void e.copyChild(t,i,void 0,n,n,(e,t)=>{this._numActiveCopyNodeOperations--,o(e,t),this._pendingCopyNodeOperations.length>0&&this._pendingCopyNodeOperations.shift()()});this._pendingCopyNodeOperations.push(()=>this._doCopyDCXNode(e,t,i,n,o))}_doCopyDCXElement(e,t,i,n,o){t._beginOperation(),this._storageInterface.notifyStartWrite(t,[this],()=>{this._doCopyDCXNode(t._dcxBranch,e._dcxNode,t._dcxElementsNode,n,(n,s)=>{if(c.checkDeletedState(this,o))return;if(n)return t._endOperation(),void o(n);const a=new r(t,s);t._addElementToFilter(a),t._elements.push(a),a._stripObsoleteGroupsData();const l=()=>{c.checkDeletedState(this,o)||(t._endOperation(),i&&this._wrapOperation(()=>this._doRemoveElement(e,!0)),o(null,a))};this._services.hasFileSystem()?t._renditionCache.copyCache(e,a).then(l,l):l()})})}_doCopyElement(e,t,i,n){if(t._elements.length>=this._config.MAX_ELEMENTS)return void n(new s(s.EXCEEDS_MAX_LIBRARY_SIZE,"Library cannot have more than "+this._config.MAX_ELEMENTS+" elements",this.id));let o=e.id;t._elements.every(e=>e.id!==o)&&t._removedElements.every(e=>e.id!==o)||(o=this._services.uuid()),this._doCopyDCXElement(e,t,i,o,n)}jasmineToString(){return this.toString()}toString(){return JSON.stringify(this._toJSON())}_setSyncState(e){this._syncState!==e&&(this._syncState=e,this._collection._updateSyncState(),this._checkSyncFinishedAndNotify())}_isSyncing(){return void 0!==this._syncState}_checkSyncFinishedAndNotify(){if(!this._isSyncing()){const e=this._waitForSyncToFinishCallbacks;this._waitForSyncToFinishCallbacks=[],e.forEach(e=>e())}}_waitForSyncToFinish(e){this._waitForSyncToFinishCallbacks.push(e),this._checkSyncFinishedAndNotify()}_getClientData(){let e={};if(this._dcxComposite.clientDataString)try{e=JSON.parse(this._dcxComposite.clientDataString)}catch(e){}return e}_getClientDataValue(e){return this._getClientData()[e]}_setClientDataValue(e,t){const i=this._getClientData();i[e]=t,this._dcxComposite.clientDataString=JSON.stringify(i)}_setCollaboration(e){const t=e&&e.collaboration&&e.collaboration.toLowerCase(),i=e&&e.collaboration_role&&e.collaboration_role.toLowerCase(),n=this._getClientDataValue(this._config.DATA_COLLABORATION_ROLE);if(this.collaboration!==t||n!==i){const e=c.collaborationStateToDCX(t);this._dcxComposite.collaborationType=e,this._setClientDataValue(this._config.DATA_COLLABORATION_ROLE,i),this._commit(!0,!0),this._notifyChange(),this._revertLocalChangesIfNecessary()}}_isDeletedError(e){const t=e&&(e.code===n.NO_COMPOSITE||e.code===n.DELETED_COMPOSITE),i=e&&e.code===n.UNEXPECTED_RESPONSE&&e.response&&401===e.response.statusCode;return t||this.collection.isPublic&&i}_isAlreadyExistsError(e){const t=e&&e.code===n.ALREADY_EXISTS,i=e&&e.code===n.UNEXPECTED_RESPONSE&&e.response&&409===e.response.statusCode;return t||i}_isReadOnlyError(e){if("incoming"!==this.collaboration)return!1;let t=!1;return!e||e.code!==n.COMPONENT_UPLOAD_ERROR&&e.code!==n.UNEXPECTED_RESPONSE||(e.code===n.UNEXPECTED_RESPONSE&&e.response&&403===e.response.statusCode&&(t=!0),e.code===n.COMPONENT_UPLOAD_ERROR&&Array.isArray(e.failedComponents)&&e.failedComponents.length>0&&(t=!0,e.failedComponents.forEach(e=>{e.error&&e.error.code===n.UNEXPECTED_RESPONSE&&e.error.response&&403===e.error.response.statusCode||(t=!1)}))),t}_mergeAndSwitchToBranch(e,t,i){const n=void 0!==t,s=e.localData,a=(t,a)=>{if(c.checkDeletedState(this,i))return;if(t)return void i(l.getCommitError(t,this.id));this._services.log("Starting merge "+(n?"(local)":"(remote)"));const h={},d=e=>h[e]=(h[e]||0)+1;a.name!==this.name&&(e.name=this.name);const _=e.rootNode.getValue(this._config.MODIFIED_KEY),p=Math.max(_||0,this.modified||0);a!==this._dcxBranch&&p&&_!==p&&e.rootNode.setValue(this._config.MODIFIED_KEY,p);const u=e=>{const t={};return c.getCustomDCXData(e.rootNode).forEach(e=>{t[e.namespace+"#"+e.key]=e.value}),t};let m={};const g=u(this._dcxBranch),f=u(a),E=u(e);Object.keys(g).forEach(e=>{m[e]=!0,JSON.stringify(g[e])!==JSON.stringify(f[e])&&(E[e]=g[e])}),Object.keys(E).forEach(e=>{m[e]||f[e]&&!g[e]&&delete E[e]});const y=c.getCompositeRenditionMap(e),v=c.getCompositeRenditionMap(a);let A,C,I;Object.keys(this._dcxCompositeRenditionMap).forEach(t=>{const i=this._dcxCompositeRenditionMap[t],n=v[t],o=y[t];if(!n||i.id!==n.id)if(o){(i.getValue(this._config.MODIFIED_KEY)||0)>(o.getValue(this._config.MODIFIED_KEY)||0)&&(e.removeComponent(o),e.copyComponent(i,e.rootNode))}else e.copyComponent(i,e.rootNode)}),Object.keys(v).forEach(t=>{const i=this._dcxCompositeRenditionMap[t],n=v[t],o=y[t];!i&&o&&o.id===n.id&&e.removeComponent(o)}),e.getChildrenOf().forEach(e=>{e.name===this._config.ELEMENTS_NAME&&(A=e),e.name===this._config.REMOVED_ELEMENTS_NAME&&(C=e),e.name===this._config.GROUPS_NAME&&(I=e)}),A||(A=e.addChild(this._config.ELEMENTS_NAME));const S=()=>{C||(C=e.addChild(this._config.REMOVED_ELEMENTS_NAME))},L=()=>{I||(I=e.addChild(this._config.GROUPS_NAME))},T=[],R={},O=[],b=(e,t,i,n)=>{const o=t.getValue(this._config.ORDER_KEY),r=i&&i.getValue(this._config.ORDER_KEY),s=n&&n.getValue(this._config.ORDER_KEY);if(s!==o)e._dcxNode.setValue(this._config.ORDER_KEY,o);else if(r!==s)return e.order!==r&&e._dcxNode.setValue(this._config.ORDER_KEY,r),!0;return!1};this._groups.forEach(t=>{const i=t.id,n=t._dcxNode,o=t.modified,r=e.getChildWithId(i),s=r&&r.getValue(this._config.MODIFIED_KEY),c=a&&a.getChildWithId(i),l=c&&c.getValue(this._config.MODIFIED_KEY);if(!l&&!s||l&&!s&&o!==l){d("g1: group created locally");const i=e.copyChild(n,(L(),I),void 0,void 0,void 0);t._setDCXNode(i)}else l&&!s&&o===l?(d("g2: group deleted on server"),O.push(t)):l===o&&l===s?(d("g3: no changes to group modified time"),t._setDCXNode(r),b(t,n,r,c)&&T.push(t)):l===o&&l!==s?(d("g4: updated group on server"),t._setDCXNode(r),T.push(t),b(t,n,r,c)):l!==o&&l===s?(d("g5: updated group locally"),t._setDCXNode(e.replaceChild(n,void 0,void 0)),b(t,n,r,c)&&T.push(t)):l!==o&&l!==s?(d("g6: updated group locally and on server (conflict)"),t._setDCXNode(e.replaceChild(n,void 0,void 0)),b(t,n,r,c)&&T.push(t)):this._services.log("ERROR: unexpected group merge case: base="+l+", current="+o+", pulled="+s);R[i]=!0}),O.forEach(e=>this._doRemoveGroup(e));const N=[],D=[],P=[],w=[],x=[],k=t=>{const i=t.id,o=t._dcxNode,s=t.modified,c=t.removed,l=e.getChildWithId(i),h=l&&l.getValue(this._config.MODIFIED_KEY),_=l&&l.getValue(this._config.REMOVED_KEY),p=a&&a.getChildWithId(i),u=p&&p.getValue(this._config.MODIFIED_KEY),m=p&&p.getValue(this._config.REMOVED_KEY);this._dcxBranch=e;const g=()=>c?(S(),C):A,f=()=>!c&&t.removed?(P.push(t),!0):!(!c||t.removed)&&(w.push(t),!0),E=()=>{let e=!1;const i=o.getValue(this._config.DESCRIPTION_DATA_KEY)||{time:0},n=l&&l.getValue(this._config.DESCRIPTION_DATA_KEY)||{time:0},r=p&&p.getValue(this._config.DESCRIPTION_DATA_KEY)||{time:0};if(i.time!==r.time){const e=o.getValue(this._config.DESCRIPTION_KEY);t._dcxNode.setValue(this._config.DESCRIPTION_KEY,e),t._dcxNode.setValue(this._config.DESCRIPTION_DATA_KEY,i)}else n.time!==r.time&&(e=!0);const s=o.getValue(this._config.GROUPS_KEY)||{},a=l&&l.getValue(this._config.GROUPS_KEY)||{},c=p&&p.getValue(this._config.GROUPS_KEY)||{},h={};return Object.keys(s).forEach(t=>{const i=s[t],n=a[t],o=c[t];o&&i.order===o.order?n||(e=!0):h[t]=i}),Object.keys(a).forEach(t=>{const i=s[t],n=a[t],o=c[t];o&&!i||h[t]||(h[t]=n,o&&n.order===o.order||(e=!0))}),(Object.keys(h).length>0||Object.keys(a).length>0)&&JSON.stringify(a)!==JSON.stringify(h)&&t._dcxNode.setValue(this._config.GROUPS_KEY,h),e};if(!u&&!h||u&&!h&&s!==u){d("e1: created element locally");const i=e.copyChild(o,g(),void 0,void 0,void 0);t._setDCXNode(i,!0)}else if(u&&!h&&s===u)d("e2: deleted element on server"),D.push(t);else if(u===s&&u===h){d("e3: no changes to element modified time"),t._setDCXNode(l,!0),m!==c&&(m===_?c&&!_?(d("e3a: removed element locally"),S(),t._dcxNode=e.moveChild(t._dcxNode,void 0,C),t._updateTimestampOnRemove(c)):_&&!c&&(d("e3b: restored element locally"),t._dcxNode=e.moveChild(t._dcxNode,void 0,A),t._updateTimestampOnRestore()):c||(d("e3c: remove/restore element conflict - local restore wins"),t._dcxNode=e.moveChild(t._dcxNode,void 0,A),t._updateTimestampOnRestore()));const i=f(),o=E();(i||o)&&T.push(t),t._ensureRemovedDataValid(n&&!this._config.SHARED_LOCAL_STORAGE)}else if(u===s&&u!==h)d("e4: updated element on server"),t._setDCXNode(l,n),T.push(t),f(),E(),t._ensureModifiedDataValid(n&&!this._config.SHARED_LOCAL_STORAGE);else if(u!==s&&u===h){d("e5: updated element locally");const i=e.replaceChild(o,void 0,void 0);t._setDCXNode(i,!0),(c&&!_||_&&!c)&&(t._dcxNode=e.moveChild(t._dcxNode,void 0,g())),E()&&T.push(t)}else if(u!==s&&u!==h){d("e6: updated element locally and on server (conflict)"),t._setDCXNode(l),T.push(t),f(),t._ensureModifiedDataValid(n&&!this._config.SHARED_LOCAL_STORAGE);const i=this._services.uuid(),s=e.copyChild(o,g(),void 0,i,i),a=new r(this,s);if(N.push(a),R[a.id]=!0,this._services.hasFileSystem()){const e=e=>this._renditionCache.copyCache(t,a).then(e,e);x.push(e)}this._analytics.reportCollisionElement(t)}else this._services.log("ERROR: unexpected element merge case: base="+u+", current="+s+", pulled="+h);this._dcxBranch=this._dcxComposite.current,R[i]=!0};this._elements.forEach(k),this._removedElements.forEach(k);const M=e=>{e.removed?this._removedElements.push(e):(this._addElementToFilter(e),this._elements.push(e))};N.forEach(M),this._sortRemovedElements(),D.forEach(e=>this._doRemoveElement(e,!1)),P.forEach(e=>this._doMarkElementRemoved(e,!1)),w.forEach(e=>this._doRestoreElement(e,!1)),this._dcxBranch=e,this._dcxElementsNode=A,this._dcxRemovedElementsNode=C,this._dcxGroupsNode=I,this._dcxCompositeRenditionMap=c.getCompositeRenditionMap(e);const U=(t,i)=>{if(!R[t.id]){const s=t.getValue(this._config.MODIFIED_KEY),c=a&&a.getChildWithId(t.id),l=c&&c.getValue(this._config.MODIFIED_KEY);if(l&&s&&l===s)d(i?"g7: deleted group locally":"e7: deleted element locally"),e.removeChild(t);else if(d(i?"g8: created group on server":"e8: created element on server"),i){const e=new o(this,t);this._groups.push(e)}else{const e=new r(this,t);M(e),e._ensureCreatedDataValid(n&&!this._config.SHARED_LOCAL_STORAGE)}}},F=this._dcxBranch.getChildrenOf(this._dcxElementsNode),V=this._dcxRemovedElementsNode?this._dcxBranch.getChildrenOf(this._dcxRemovedElementsNode):[],B=this._dcxGroupsNode?this._dcxBranch.getChildrenOf(this._dcxGroupsNode):[];F.forEach(e=>U(e)),V.forEach(e=>U(e)),B.forEach(e=>U(e,!0)),Object.keys(h).sort().forEach(e=>{const t=h[e];this._services.log(`Merge Case ${e} (${t})`)}),this._transactionCount++,Promise.all(x.map(e=>new Promise(t=>e(t)))).then(()=>{c.checkDeletedState(this,i)||(this._transactionCount--,this._storageInterface.resolvePullWithBranch(this,e,s,n,t=>{c.checkDeletedState(this,i)||(t?i(l.getCommitError(t,this.id)):(this._services.hasFileSystem()||(this._dcxBaseBranch=e.copy()),this._config.SHARED_LOCAL_STORAGE||n||this._prefetchRenditions(),i(null),T.forEach(e=>e._listenerManager.notify("change")),this._notifyChange()))}))})};this._waitForCommit(()=>{c.checkDeletedState(this,i)||(t?a(null,t):"unmodified"===this._dcxBranch.compositeState?a(null,this._dcxBranch):this._loadBaseBranch(a))})}_pull(e){if(!this._dcxComposite.href||!this._dcxBranch.isBound)return void e(null,!1);if(this._deletedFromServer)return void e(null,!1);const t=(t,i)=>{c.checkDeletedState(this,e)||(t&&this._collection._reportSyncError(t),this._setSyncState(),this._networkLock.release(),e(t,i))};this._networkLock.obtain(i=>{i?e(null):c.checkDeletedState(this,e)||(this._setSyncState("downloading"),this._collection._syncManager.pullLibrary(this,(i,n)=>{c.checkDeletedState(this,e)||(this._isDeletedError(i)?this._services.hasFileSystem()&&"modified"===this._dcxBranch.compositeState&&"incoming"!==this.collaboration?(this._doRebindToServer(!1,e),this._networkLock.release()):(this._deletedFromServer=!0,this._notifyChange(),t(null,!0)):i?t(l.getSyncError(i,this.id)):n?this._mergeAndSwitchToBranch(n,void 0,i=>{c.checkDeletedState(this,e)||t(i,!0)}):t(null,!1))}))})}_pushWithParameters(e,t=(()=>{})){const i=!this._dcxComposite.isBound,o=(e,n)=>{t(null,n),this.collection._onLibraryPush&&this.collection._onLibraryPush(this,i&&n)};if(!this._config.SYNCING_ENABLED)return void o(0,!1);if(this._collection._retryTimeoutId)return void o(0,!1);if(this._dcxBranch.isBound&&"modified"!==this._dcxBranch.compositeState)return void o(0,!1);if(this._deletedFromServer)return void o(0,!1);if(!this.isWritable)return void o(0,!1);if(this._pushPending)return void o(0,!1);const r=(e,i)=>{c.checkDeletedState(this,o)||(this._pushFailedDueToQuota=!1,e&&(this._collection._reportSyncError(e),e.code===s.EXCEEDS_QUOTA&&(this._pushFailedDueToQuota=!0)),this._setSyncState(),this._collection._syncManager.pullMissingComponents(this,()=>{c.checkDeletedState(this,t)||(this._networkLock.release(),this._prefetchRenditions(),o(0,i))}))};this._pushPending=!0,this._networkLock.obtain(t=>{t?o(0,!1):this._waitForCommit(()=>{if(c.checkDeletedState(this,o))return;let t;this._pushPending=!1,this._services.hasFileSystem()||(t=this._dcxBranch.copy()),this._setSyncState("uploading"),this._collection._syncManager.pushLibrary(this,e,e=>{if(!c.checkDeletedState(this,o))if(this._isDeletedError(e))this._services.hasFileSystem()&&"modified"===this._dcxBranch.compositeState&&"incoming"!==this.collaboration&&!this._collection.isTeam?(this._doRebindToServer(!1,o),this._networkLock.release()):(this._deletedFromServer=!0,this._notifyChange(),r(null,!0));else{if(this._isAlreadyExistsError(e)){const t=this._localisation.translate("LIBS_RECOVERED_LIBRARY",{name:""}),i=this._collection._recoveredLibraryCount>this._config.MAX_RECOVERED_LIBRARIES;if(this._dcxComposite.name.endsWith(t)||i){const t=i?"count exceeded":"already recovered";return this._services.log(`Failed to recover library ${t}: ${this.id}`),void r(l.getSyncError(e,this.id))}return this._dcxComposite.name=this._localisation.translate("LIBS_RECOVERED_LIBRARY",{name:this._dcxComposite.name}),this._services.log(`Recovering library due to 409 error: ${this.id}`),this._collection._recoveredLibraryCount++,this._doRebindToServer(!0,o),void this._networkLock.release()}if(this._isReadOnlyError(e))return this._services.log("Push failed due to read only. Reverting: "+this.id),this._setClientDataValue(this._config.DATA_COLLABORATION_ROLE,"viewer"),void this._revertLocalChangesIfNecessary(e=>r(e,!1));if(e&&e.code===s.TRANSFER_ABORTED)r(null,!0);else{if(e&&e.code===n.UPDATE_CONFLICT){if(this._services.log("Push failed due to conflict: "+this.id),this._numUpdateConflicts++,this._numUpdateConflicts<=this._config.MAX_UPDATE_CONFLICTS)return this._sync(!1,o),void this._networkLock.release();this._analytics.reportUnexpectedState(this,"updateConflict"),this._services.log("Reached maximum number of update-conflict retries: "+this.id)}this._numUpdateConflicts=0,e&&e.code===n.COMPONENT_UPLOAD_ERROR&&(this._services.log("Push failed due to component upload failure: "+this.id),c.fixLocalComponents(this,e.failedComponents)),e?r(l.getSyncError(e,this.id)):this._storageInterface.acceptPush(this,e=>{c.checkDeletedState(this,o)||(e?r(l.getCommitError(e,this.id),!0):(this._services.hasFileSystem()||(this._dcxBaseBranch=t),r(null,!0)))})}}})})})}_loadBaseBranch(e){this._services.hasFileSystem()?this._dcxComposite.loadBaseBranch((t,i)=>{this._waitForCommit(()=>e(t,i))}):e(null,this._dcxBaseBranch)}_revertLocalChangesIfNecessary(e=(()=>{})){this.isWritable||"modified"!==this._dcxBranch.compositeState?e(null):this._loadBaseBranch((t,i)=>{this._transactionCount++,c.recoverReadOnlyEdits(this,i,t=>{t&&this._services.log("Error recovering library changes: "+t),this._transactionCount--;const n=i.copy(),o=this.collaboration,r=this._getClientDataValue(this._config.DATA_COLLABORATION_ROLE);this._mergeAndSwitchToBranch(n,this._dcxBranch,t=>{if(t)this._services.log("Error Reverting: "+this.id),e(t);else{const t=c.collaborationStateToDCX(o);this._dcxComposite.collaborationType=t,this._setClientDataValue(this._config.DATA_COLLABORATION_ROLE,r),this._commit(!0,!0),this._waitForCommit(()=>{this._notifyChange(),e(null)})}})})})}_push(e){this._pushWithParameters(!1,e)}_abortPushOrPull(){this._networkLock.abortPendingOperations(new s(s.TRANSFER_ABORTED)),this._collection._syncManager.abortPushOrPull(this.id)}_deleteFromServer(e,t){if(this._deletingFromServerInProgress||this._abortPushOrPull(),!this._dcxComposite.href)return void t(null);if(this._deletedFromServer)return void t(null);this._deletingFromServerInProgress=!0;const i=e=>{this._deletingFromServerInProgress=!1,this._setSyncState(),this._networkLock.release(),t(e)};this._networkLock.obtain(o=>{o?t(null):this._deletedFromDisk?i(null):(this._setSyncState("uploading"),this._collection._prepareCompositeForDelete(this._dcxComposite),this._commit(!0,!0),this._waitForCommit(()=>{this._deletedFromDisk?i(null):this._collection._syncManager.pushDeletedLibrary(this,this.collaboration,e,t=>{t?this._isDeletedError(t)?(this._deletedFromServer=!0,t=null):(e||t.code!==n.UPDATE_CONFLICT)&&(t=l.getSyncError(t,this.id),this._collection._reportSyncError(t)):this._deletedFromServer=!0,i(t)})}))})}_doRebindToServer(e,t){this._deletedFromServer=!1;const i=e||"incoming"===this.collaboration?"resetIdentity":"resetBinding",n=this.id;this._dcxComposite[i](e=>{c.checkDeletedState(this,t)||(e?t(e):(this._transactionCount++,this.id!==n&&(this._collection._libraryIdMap[this.id]=this,delete this._collection._libraryIdMap[n]),this._services.fileUtils.moveLibrary(this,n,e=>{c.checkDeletedState(this,t)||(this._transactionCount--,e?t(e):(this._collection._prepareCompositeForPush(this._dcxComposite),this._setCollaboration(),this._commit(!1,!0),this._pushWithParameters(!0,t)))})))})}_sync(e,t){const i=(e,i)=>{t&&this._waitForSyncToFinish(()=>t(e,i))};if(this._config.SHARED_LOCAL_STORAGE||!this._config.SYNCING_ENABLED)return void i(null,!1);if(this._collection._retryTimeoutId)return void i(null,!1);this._collection._clearSyncErrors(this.id);const n=(e,t)=>{c.checkDeletedState(this,i)||(e?i(e,t):this._push((e,n)=>{c.checkDeletedState(this,i)||i(e,t||n)}))};e?n(null,!1):this._pull(n)}_getCompositeDir(){return this._collection._getCompositeDir(this.id)}_getRenditionCacheDir(){return this._collection._getRenditionCacheDir(this.id)}_setAutoGC(e,t){!1===t?this._autoGCMode[e]=!1:delete this._autoGCMode[e],this._dcxComposite.autoRemoveUnusedLocalFiles=0===Object.keys(this._autoGCMode)}_prefetchRenditions(){return this._services.hasFileSystem()?Promise.all(this.elements.map(e=>e._prefetchRenditions())):Promise.resolve()}get id(){return this._publicId||this._dcxComposite.id}get collection(){return this._collection}get isWritable(){const e=this._getClientDataValue(this._config.DATA_COLLABORATION_ROLE);return this._writable&&"viewer"!==e}get isPushedToServer(){return this._dcxComposite.isBound}get name(){return this._dcxComposite.name||""}set name(e){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);this._dcxComposite.name=e,this._commit()}get modified(){return this._dcxBranch.rootNode.getValue(this._config.MODIFIED_KEY)}get created(){return this._dcxBranch.rootNode.getValue(this._config.CREATED_KEY)}get elements(){return this._elements}get removedElements(){return this._removedElements}get isDeletedFromServer(){return this._deletedFromServer}get isDeletedLocally(){return this._deletedLocally}get isQuotaExceeded(){return this._pushFailedDueToQuota}get toolkitId(){return this.getValue(this._config.TOOLKIT_NAMESPACE,this._config.TOOLKIT_ID_KEY)}get collaboration(){const e=this._dcxComposite.collaborationType;return c.collaborationStateFromDCX(e)}get syncState(){return this._syncState}get syncProgress(){const e=this._collection._syncProgressMap[this.id];return e&&e.progress}addChangeListener(e){c.checkDeletedState(this),this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}getGroups(e){return e=e||this._config.DEFAULT_GROUP_CLASSIFIER,this._groups.filter(t=>e instanceof RegExp?e.test(t.classifierName):e===t.classifierName)}getGroupById(e){return this._groups.find(t=>t.id===e)}createGroup(e,t,i){if(i=i||this._config.DEFAULT_GROUP_CLASSIFIER,c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);const n=this._doCreateGroup(e,t,i);return this._commit(),this._analytics.reportCreateGroup(n),n}removeGroup(e,t){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);if(!e)throw new s(s.INVALID_PARAMETER,"No group specified",this.id);if(-1===this._groups.indexOf(e))throw new s(s.INVALID_PARAMETER,"group not in this library",this.id);let i=0;this._doRemoveGroup(e,e=>{t?(this.removeElement(e),i++):e._listenerManager.notify("change")}),this._commit(),this._analytics.reportDeleteGroup(e,t,i)}moveGroup(e,t,i,n){if(c.checkDeletedState(this,n))return;if(!this.isWritable)return void n(new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id));if(!e)return void n(new s(s.INVALID_PARAMETER,"No group specified",this.id));if(-1===this._groups.indexOf(e))return void n(new s(s.INVALID_PARAMETER,"Group not in this library",this.id));if(!t)return void n(new s(s.INVALID_PARAMETER,"No destination library specified",this.id));if(this===t)return void n(new s(s.INVALID_PARAMETER,"Move must have a different destination library",this.id));if(!t.isWritable)return void n(new s(s.NOT_ALLOWED,"you do not have write access to the destination library",t.id));const o=i?this._getNumberOfElementsInGroup(e):void 0;return this._doCopyGroup(e,t,i,!0,(t,r)=>{t?n(t):(this._analytics.reportMoveGroup(r,e,i,o),n(null,r))})}copyGroup(e,t,i,n){if(c.checkDeletedState(this,n))return;if(!e)return void n(new s(s.INVALID_PARAMETER,"No group specified",this.id));if(-1===this._groups.indexOf(e))return void n(new s(s.INVALID_PARAMETER,"Group not in this library",this.id));if(!t)return void n(new s(s.INVALID_PARAMETER,"No destination library specified",this.id));if(!t.isWritable)return void n(new s(s.NOT_ALLOWED,"you do not have write access to the destination library",t.id));const o=i?this._getNumberOfElementsInGroup(e):void 0;return this._doCopyGroup(e,t,i,!1,(t,r)=>{t?n(t):(this._analytics.reportCopyGroup(r,e,i,o),n(null,r))})}createElement(e,t,i=!1){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);const n=((i=i&&t===this._config.COLOR_ELEMENT_TYPE)?2:1)*this._config.MAX_ELEMENTS;if(this._elements.length>=n)throw new s(s.EXCEEDS_MAX_LIBRARY_SIZE,"Library cannot have more than "+this._config.MAX_ELEMENTS+" elements",this.id);return this._wrapOperation(()=>{const i=this._doCreateElement(e,t);return this._analytics.reportCreateElement(i),i.beginOperation(),i})}removeElement(e,t){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);if(!e)throw new s(s.INVALID_PARAMETER,"No element specified",this.id);if(-1===this._elements.indexOf(e)){if(-1===this._removedElements.indexOf(e))throw new s(s.INVALID_PARAMETER,"Element not in this library",this.id);if(!t)throw new s(s.INVALID_PARAMETER,"Element already removed",this.id)}return this._wrapOperation(()=>{for(;e._transactionCount>0;)e.endOperation();t?this._doRemoveElement(e,!0):this._doMarkElementRemoved(e,!0),this._analytics.reportDeleteElement(e,t)})}restoreElement(e){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);if(!e)throw new s(s.INVALID_PARAMETER,"No element specified",this.id);if(-1===this._removedElements.indexOf(e)){if(-1===this._elements.indexOf(e))throw new s(s.INVALID_PARAMETER,"Element not in this library",this.id);throw new s(s.INVALID_PARAMETER,"Element already restored",this.id)}if(this._elements.length>=this._config.MAX_ELEMENTS)throw new s(s.EXCEEDS_MAX_LIBRARY_SIZE,"Library cannot have more than "+this._config.MAX_ELEMENTS+" elements",this.id);return this._wrapOperation(()=>{this._doRestoreElement(e,!0),this._analytics.reportRestoreElement(e)})}copyElement(e,t,i){if(!c.checkDeletedState(this,i))if(e)if(-1!==this._elements.indexOf(e)||-1!==this._removedElements.indexOf(e))if(t){if(t.isWritable)return this._doCopyElement(e,t,!1,(t,n)=>{t?i(t):(this._analytics.reportCopyElement(n,e),i(null,n))});i(new s(s.NOT_ALLOWED,"you do not have write access to the destination library",t.id))}else i(new s(s.INVALID_PARAMETER,"No destination library specified",this.id));else i(new s(s.INVALID_PARAMETER,"Element not in this library",this.id));else i(new s(s.INVALID_PARAMETER,"No element specified",this.id))}moveElement(e,t,i){if(!c.checkDeletedState(this,i))if(this.isWritable)if(e)if(-1!==this._elements.indexOf(e)||-1!==this._removedElements.indexOf(e))if(t)if(this!==t){if(t.isWritable)return this._doCopyElement(e,t,!0,(t,n)=>{t?i(t):(this._analytics.reportMoveElement(n,e),i(null,n))});i(new s(s.NOT_ALLOWED,"you do not have write access to the destination library",t.id))}else i(new s(s.INVALID_PARAMETER,"Move must have a different destination library",this.id));else i(new s(s.INVALID_PARAMETER,"No destination library specified",this.id));else i(new s(s.INVALID_PARAMETER,"Element not in this library",this.id));else i(new s(s.INVALID_PARAMETER,"No element specified",this.id));else i(new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id))}getValues(){return c.getCustomDCXData(this._dcxBranch.rootNode)}setValue(e,t,i){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);if(e===this._config.DL_NAMESPACE)throw new s(s.INVALID_PARAMETER,"Reserved namespace",this.id);const n=c.getDCXKey(e,t);let o;try{o=JSON.parse(JSON.stringify(i))}catch(e){throw new s(s.INVALID_PARAMETER,"Value cannot be serialized to JSON",this.id)}this._dcxBranch.rootNode.setValue(n,o),this._commit()}getValue(e,t){if(e===this._config.DL_NAMESPACE)throw new s(s.INVALID_PARAMETER,"Reserved namespace",this.id);const i=c.getDCXKey(e,t);return this._dcxBranch.rootNode.getValue(i)}removeValue(e,t){if(e===this._config.DL_NAMESPACE)throw new s(s.INVALID_PARAMETER,"Reserved namespace",this.id);const i=c.getDCXKey(e,t);this._dcxBranch.rootNode.removeValue(i)}getRenditionPath(e,t){if(!this._services.hasFileSystem())return void t(new s(s.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this.id));if(c.checkDeletedState(this,t))return;if(!this._checkRenditionType(e,t))return;const i=this._dcxCompositeRenditionMap[e];if(!i)return t(null);const n=this._dcxBranch.assetOfComponent(i);if(n)return t(null,n);this._networkLock.obtain(e=>{if(e)return void t(e);if(c.checkDeletedState(this,t))return void this._networkLock.release();this._setSyncState("downloading"),this._collection._syncManager.downloadComponent(this._dcxBranch,i,e=>{this._networkLock.release(),this._setSyncState(),e?t(l.getSyncError(e,this.id)):c.checkDeletedState(this,t)||(this._commit(!0,!0),t(null,this._dcxBranch.assetOfComponent(i)))})})}getRenditionURL(e){c.checkDeletedState(this),this._checkRenditionType(e);const t=this._dcxCompositeRenditionMap[e];if(t){return this._collection._syncManager.getContentURL(t)}}getAuthenticatedRenditionURL(e,t){if(c.checkDeletedState(this,t))return;if(!this._checkRenditionType(e,t))return;const i=this.getRenditionURL(e);if(!i)return t(null);this._collection._syncManager.appendAccessTokenToURL(i,t)}setRendition(e,t,i,n,o){if(!c.checkDeletedState(this,o)&&this._checkRenditionType(e,o))if(t)if(this.isWritable)if(this._services.hasFileSystem()){if(!c.checkEncoding(i,["utf8","ascii","base64","buffer"],o))return;this._setRendition(e,t,i,n,o)}else{if(void 0!==i)return void o(new s(s.INVALID_PARAMETER,"Encoding parameter not supported in-browser"));this._setRenditionInBrowser(e,t,n,o)}else o(new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id));else o(new s(s.INVALID_PARAMETER,"content must exist",this.id))}setRenditionFromPath(e,t,i,n){c.checkDeletedState(this,n)||this._checkRenditionType(e,n)&&("string"==typeof t?this._services.hasFileSystem()?this.isWritable?this._setRenditionFromPath(e,t,i,n):n(new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id)):n(new s(s.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this.id)):n(new s(s.INVALID_PARAMETER,"path must be a string",this.id)))}removeRendition(e){if(c.checkDeletedState(this),this._checkRenditionType(e),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);const t=this._dcxCompositeRenditionMap[e];if(t)return this._wrapOperation(()=>{this._dcxBranch.removeComponent(t),this._dcxCompositeRenditionMap=c.getCompositeRenditionMap(this._dcxBranch),this._commit()})}beginOperation(){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);this._beginOperation()}endOperation(){if(c.checkDeletedState(this),!this.isWritable)throw new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id);this._endOperation()}getFilteredElements(e){if(!e)throw new s(s.INVALID_PARAMETER,"must specify element type to filter",this.id);if("*"!==e&&-1===this._config.ELEMENT_TYPE_FILTERS.indexOf(e))throw new s(s.INVALID_PARAMETER,"must specify '*', or an element type in config.ELEMENT_TYPE_FILTERS",this.id);const t=this._getFilterKey(e);return this._filterCache[t]=this._filterCache[t]||[],this._filterCache[t]}sync(e){c.checkDeletedState(this,e)||this._sync(!1,e)}rebindToServer(e){this._services.hasFileSystem()?c.checkDeletedState(this,e)||(this.isWritable?this._deletedFromServer?this._doRebindToServer(!1,e):e(null):e(new s(s.NOT_ALLOWED,"you do not have write access to this library",this.id))):e(new s(s.REQUIRES_FILESYSTEM,"rebindToServer requires a filesystem",this.id))}getElementById(e,t){const i=this.elements.find(t=>t.id===e);return i||t?i:this.removedElements.find(t=>t.id===e)}}},function(e,t){const i=/^team!.+/,n=/^platform-cs(-stage)?(-[a-zA-Z0-9]+)?\.adobe\.io$/;e.exports={isACPHost:function(e){return n.test(e)},getCloudIdFromUrn:function(e){return`team!${e.replace(/:/g,"_")}`},getUrnFromCloudId:function(e){return e.replace(/^team!/,"").replace(/_/g,":")},isTeam:function(e){return i.test(e)}}},function(e,t,i){const n=i(135),o=i(136),r=i(17),s=i(3),a=i(6),c=["public","team"];e.exports=class{static waitForPushNew(e){return{condition:"on_pushed_new",libraryId:e}}static waitForDelete(e){return{condition:"on_deleted",libraryId:e}}constructor(e){this._collection=e,this._bookmarks=[],this._bookmarkData=[],this._queuedOperations=[],this._lock=new r,this._listenerManager=new s(["change"],e=>this._services.log(e))}get _services(){return this._collection._services}get _storageInterface(){return this._collection._storageInterface}get _config(){return this._collection._config}get _syncManager(){return this._collection._syncManager}_getBookmarksDir(){return this._collection._getBaseDir()}_toJSON(){return{version:this._config.BOOKMARKS_FILE_VERSION,bookmark_data:this._bookmarkData,queued_operations:this._queuedOperations,bookmarks:this._bookmarks.filter(e=>"public"===e.type).map(e=>({id:e.id,url:e.url})),etag:'"0"'}}_fromJSON(e){if(!e||e.version&&e.version!==this._config.BOOKMARKS_FILE_VERSION)return this._services.log("Unsupported bookmarks.json file - ignoring"),void(this._bookmarkData=[]);e.version||(this._services.log("Legacy bookmarks.json file - migrating"),e.bookmark_data=e.bookmarks.map(e=>({type:"public",...e}))),this._bookmarkData=e.bookmark_data,this._queuedOperations=e.queued_operations||[],this._ensureBookmarks()}_serialize(e){return this._config.isNewBookmarkFormatSupported(e)?this._toJSON():this._bookmarks.filter(e=>"public"===e.type).map(e=>({_id:e.id,_url:e.url}))}_deserialize(e){this._fromJSON(e)}get _nextOperationToPush(){const e=[];return this._queuedOperations.find(t=>{if(!(t.condition||t.id&&e.includes(t.id)))return t;"create"===t.operation&&t.data&&e.push(t.data.id)})}_checkAndApplyCondition(e){const t=e.condition&&e.condition.condition,i=e.condition&&e.condition.libraryId,n=this._collection._apiRoot.getLoadedCollections().reduce((e,t)=>e||t._getLocalLibraryById(i),null);return"on_pushed_new"===t&&n&&n._dcxBranch&&n._dcxBranch.compositeAssetId?(e.data.urn=n._dcxBranch.compositeAssetId,delete e.condition,!0):"on_deleted"===t&&!n&&(delete e.condition,!0)}_isConditionStale(e){const t=e.condition&&e.condition.condition,i=e.condition&&e.condition.libraryId,n=i&&this._collection._apiRoot.getLibraryById(i);return"on_pushed_new"===t&&!n||"on_deleted"===t&&n}_checkAndApplyConditions(){const e=this._queuedOperations.filter(e=>!this._isConditionStale(e)),t=e.reduce((e,t)=>this._checkAndApplyCondition(t)||e,!1)||e.length!==this._queuedOperations.length;return this._queuedOperations=e,t}_pushOperation(e){if("remove"===e.operation){const t=this._queuedOperations.findIndex(t=>"create"===t.operation&&t.data&&t.data.id===e.id);if(t>=(this._isPushing?1:0))return void this._queuedOperations.splice(t,1)}this._queuedOperations.push(e)}_ensureBookmarks(){const e={};this._bookmarks.forEach(t=>e[t.id]=t);const t={},i=[];this._queuedOperations.forEach(e=>{"remove"===e.operation?t[e.id]=!0:"create"===e.operation&&i.push(e.data)}),this._bookmarks=[];const r=i=>{c.includes(i.type)&&!t[i.id]&&(e[i.id]?(this._bookmarks.push(e[i.id]),delete e[i.id]):"public"===i.type?this._bookmarks.push(new n(i.id,i.url)):"team"===i.type&&this._bookmarks.push(new o(i.id,i.urn,i.team_urn,i.org_id)))};this._bookmarkData.forEach(r),i.forEach(r),Object.keys(e).forEach(t=>{const i=e[t];i._onRemove&&i._onRemove()}),this._listenerManager.notify("change")}_saveAndPushChanges(){return this._ensureBookmarks(),this._lock.execute(()=>this._save().then(()=>this._push()))}_load(){if(!this._services.hasFileSystem())return Promise.resolve();this._services.log("Loading bookmarks");const e=this._getBookmarksDir()+this._services.getPathSeparator()+this._config.BOOKMARKS_FILENAME;return this._services.fileUtils.readJSONData(e).then(e=>this._fromJSON(e)).catch(e=>{this._collection._reportCommitError(a.getCommitError(e,null,"bookmarks could not be loaded"))})}_save(){return this._services.hasFileSystem()?(this._services.log("Saving bookmarks"),this._services.fileUtils.writeJSONData(this._getBookmarksDir(),this._config.BOOKMARKS_FILENAME,this._toJSON()).catch(e=>{this._collection._reportCommitError(a.getCommitError(e,null,"bookmarks could not be saved"))})):Promise.resolve()}_sync(){return this._push().then(()=>this._pull())}_pull(){return this._syncManager.getBookmarks().then(e=>(this._bookmarkData=e&&e.bookmarks||[],this._ensureBookmarks(),this._save())).catch(e=>this._collection._reportSyncError(e))}_push(){if(this._checkAndApplyConditions())return this._ensureBookmarks(),this._save().then(()=>this._push());const e=this._nextOperationToPush;if(!e)return Promise.resolve();this._isPushing=!0;const t=()=>{const t=this._queuedOperations.indexOf(e);return-1!==t&&this._queuedOperations.splice(t,1),this._ensureBookmarks(),this._isPushing=!1,this._save().then(()=>this._push())},i=e=>{this._isPushing=!1,this._collection._reportSyncError(e)};return"create"===e.operation?this._syncManager.createBookmarks({bookmarks:[e.data]}).then(()=>(this._bookmarkData.push(e.data),t()),i):"remove"===e.operation?this._syncManager.removeBookmark(e.id).then(()=>{const i=this._bookmarkData.findIndex(t=>t.id===e.id);return-1!==i&&this._bookmarkData.splice(i,1),t()},i):(this._services.log(`Unknown bookmark operation ${e.operation}`),t())}load(){return this._lock.execute(()=>this._load())}sync(){return this._lock.execute(()=>this._sync())}getBookmarks(){return this._bookmarks}findBookmark(e){return this.getBookmarks().find(t=>t.isReferenceTo(e))}createBookmark(e,t,i,n,o=(()=>{})){const r=e=>{const t=this._bookmarks.find(t=>t.id===e);o(null,t)};if(this._config.SHARED_LOCAL_STORAGE)return void this._storageInterface.createBookmark(this._collection,e,t,i,n,(e,i)=>{!e&&i?(this._deserialize(i),r(t)):o(e)});const s=this._bookmarks.find(e=>e.id===t);s?o(null,s):(this._services.log("Creating bookmark: "+e+" data: "+JSON.stringify(i)),this._pushOperation({operation:"create",condition:n,data:{id:t,type:e,...i}}),this._saveAndPushChanges(),r(t))}removeBookmark(e,t,i=(()=>{})){this._config.SHARED_LOCAL_STORAGE?this._storageInterface.removeBookmark(this._collection,e,i):(this._services.log(`Removing bookmark: ${JSON.stringify(e.toJSON())}`),this._bookmarks.includes(e)&&(this._pushOperation({operation:"remove",condition:t,id:e.id}),this._saveAndPushChanges()),i(null))}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}}},function(e,t,i){var n=i(5),o={getCollectionBookmarksData:function(e,t){return{isPublic:e.isPublic,userId:e.userId,cloudId:e.cloudId,bookmarks:e._bookmarkManager?e._bookmarkManager._serialize(t):[]}},validateBookmarks:function(e){const t=e.getLoadedCollections(),i=t.find(e=>e.isPrivate),o=t.filter(e=>!e.isPrivate);if(!i)return Promise.resolve();i.bookmarks.forEach(e=>{const t=o.find(t=>!t.getLibraryById(e.id)&&t.canLoadLibrary(e));t?(t._loadingBookmarks=t._loadingBookmarks||{},t._loadingBookmarks[e.id]?n.log("BookmarkUtil",`Bookmark already loading: ${e.id} url: ${e.url}`):(n.log("BookmarkUtil",`Loading library for bookmark: ${e.id}`),t._loadingBookmarks[e.id]=new Promise(o=>t.loadLibrary(e,(t,r)=>{t||r||(n.log("BookmarkUtil",`Bookmarked library no longer exists: ${e.id} url: ${e.url}`),i.removeBookmark(e,e=>{n.log("BookmarkUtil",`Cleaning up bookmark ${e?`failed: ${e}`:"succeeded"}`),o()})),n.log("BookmarkUtil",`Loading bookmarked library: ${e.id} url: ${e.url} ${t?`failed: ${t}`:"succeeded"}`),o()})).then(()=>delete t._loadingBookmarks[e.id]))):n.log("BookmarkUtil",`Collection not found for loading bookmark: ${e.id} url: ${e.url}`)});const r=[];return o.forEach(e=>{e._getLibrariesToUnload().forEach(t=>{n.log("BookmarkUtil",`Unloading bookmarked library: ${t.id}`),r.push(new Promise(i=>e.unloadLibrary(t,e=>{n.log("BookmarkUtil",`Unloading bookmarked library: ${t.id} ${e?`failed: ${e}`:"succeeded"}`),i()})))})}),Promise.all(r)},sendBookmarksChanged:function(e,t){e.getLoadedCollections().forEach(e=>{e.isPrivate&&t.broadcast("bookmarkschanged",t=>o.getCollectionBookmarksData(e,t.version))})}};e.exports=o},function(e,t,i){var n,o=i(20),r=i(15),s=i(0),a=i(31),c={};c.getLibraryData=function(e){const t=i=>{const n=`memo_${i?"p":"r"}`;return t[n]||(t[n]=i?e._dcxBranch.prettifiedLocalData:e._dcxBranch.localData),t[n]};return{isPublic:e.collection.isPublic,isTeam:e.collection.isTeam,platformDirectoryId:e.collection.platformDirectoryId,userId:e.collection.userId,cloudId:e.collection.cloudId,id:e.id,path:e._dcxComposite.path,manifest:t,deletedFromServer:e._deletedFromServer,isDeletedFromServer:e._deletedFromServer,renditionCache:e._renditionCache.serializeCache()}},c.getElementRenditionCacheData=function(e){return{isPublic:e.library.collection.isPublic,isTeam:e.library.collection.isTeam,userId:e.library.collection.userId,cloudId:e.library.collection.cloudId,platformDirectoryId:e.library.collection.platformDirectoryId,id:e.library.id,elementId:e.id,renditionCache:e.library._renditionCache.serializeElementCache(e)}},c.getDeletedLibraryData=function(e,t){return{isPublic:e.isPublic,isTeam:e.isTeam,userId:e.userId,cloudId:e.cloudId,platformDirectoryId:e.platformDirectoryId,id:t}},c.getSyncStateData=function(e){var t={isPublic:e.isPublic,isTeam:e.isTeam,platformDirectoryId:e.platformDirectoryId,userId:e.userId,cloudId:e.cloudId,state:e._syncState,libraryStates:[],progress:e._syncProgress,progressMap:e._syncProgressMap,externalLinkDownloadProgressMap:e._externalLinkDownloadProgressMap,newLibraryProgress:e.getNewLibrarySyncProgress(),errors:[],initialSyncInProgress:e._initialSyncInProgress};return e.libraries.forEach(e=>{t.libraryStates.push({id:e.id,state:e._syncState})}),e._syncErrors.forEach(e=>{t.errors.push({code:e.code,message:e._message,libraryId:e.libraryId})}),t},c.prepareErrorForSerialization=function(e,t){return t=t||[e],Object.keys(e).forEach(i=>{if("underlyingError"===i&&e.underlyingError)-1===t.indexOf(e.underlyingError)?e.underlyingError=c.prepareErrorForSerialization(e.underlyingError,t.concat([e.underlyingError])):delete e.underlyingError;else try{JSON.stringify(e[i])}catch(t){delete e[i]}}),e},c.getCollectionData=function(e){var t={rootDir:e._config.ROOT_DIR,isPublic:e.isPublic,isTeam:e.isTeam,platformDirectoryId:e.platformDirectoryId,team:e._team,userId:e.userId,cloudId:e.cloudId,cloudInfo:e.cloudInfo,storageHost:e._syncManager._storageHost,collaborationHost:e._syncManager._collaborationHost,imageHost:e._syncManager._imageHost,imageXHost:e._syncManager._imageXHost,typekitHost:e._syncManager._typekitHost,requiresCommunitySession:e._syncManager._requiresCommunitySession,libraries:[]};return e.libraries.forEach(e=>{t.libraries.push(c.getLibraryData(e))}),t},c.getOperationsData=function(e){var t=e.operations.map((function(e){return{id:e.id,type:e.type,data:e.data,progress:e.progress}}));return{isPublic:e.isPublic,userId:e.userId,cloudId:e.cloudId,operations:t}},c.getAPIVersion=function(e){return e.getOption("SHARED_LOCAL_STORAGE_VERSION")},c.getCodeVersion=function(e){var t=a.version;return e&&(t+="-3"),t},c.getDeviceDescription=function(e){if(!n||e){var t,i=o.platform(),s={darwin:"mac",win32:"win",win64:"win"}[i]||i;if("darwin"===i)try{t=r.execSync("sw_vers -productVersion",{timeout:1e3}).toString().trim()}catch(e){}else t=o.release();n=s,t&&(n+="-"+t)}return n},c.getEnvironmentData=function(e,t){var i;return void 0!==t&&t<e.getOption("SHARED_LOCAL_STORAGE_MIN_CLIENT_VERSION")&&(i="client"),void 0!==t&&t>e.getOption("SHARED_LOCAL_STORAGE_MAX_CLIENT_VERSION")&&(i="server"),{updateRequired:i,version:c.getAPIVersion(e),codeVersion:c.getCodeVersion(),buildNumber:"3",environment:s.getEnvironment().LABEL,syncingEnabled:e.getOption("SYNCING_ENABLED"),analyticsEnabled:e.getOption("ANALYTICS_ENABLED"),whitelistedDomains:e.getOption("ADOBE_AUTHENTICATED_DOMAINS").concat(e.getOption("WHITELISTED_DOMAINS")),elementActionProductMap:e._config.formatElementActionMapForClient(t),deviceId:e.getOption("DEVICE_ID"),deviceDescription:e.getOption("DEVICE_DESCRIPTION"),maxElements:e.getOption("MAX_ELEMENTS"),maxRemovedElements:e.getOption("MAX_REMOVED_ELEMENTS"),maxComponentSize:e.getOption("MAX_COMPONENT_SIZE"),localSettings:e.getOption("LOCAL_SETTINGS"),shaCache:e.getOption("SHA_CACHE"),defaultContentLocations:e.getOption("DEFAULT_CONTENT_LOCATIONS")}},e.exports=c},function(e,t,i){const n=i(0),o=i(5);var r={getLibraryCollection:function(e,t,i,n,o,r){return t?e.getLoadedTeamCollectionById(r):i?e.getLoadedPublicCollectionById(o):e.getLoadedCollectionById(n,o)},triggerRenditionPrefetch:function(e){e.getLoadedCollections().forEach(e=>{e.libraries.forEach(e=>e._prefetchRenditions())})},findElement:function(e,t,i){t=t||"";var n=new RegExp("cloud-asset://(.+)/([A-Za-z0-9-]+);node=([A-Za-z0-9-]+)"),o=t.match(n);if(o){var s,a,c,l=o[1],h=o[2],d=o[3];e.getLoadedCollections().every((function(e){return l!==e._syncManager.getElementRefDomainPath()||(s=e,(a=e.getLibraryById(h))&&(c=a.getElementById(d)),!1)})),c?i(null,c):0===e.getLoadedCollections().length?i("NO_COLLECTIONS_PRESENT"):s?a?a.sync((function(){(c=a.getElementById(d))?i(null,c):"error"===s.syncState?i("COLLECTION_SYNC_ERROR"):i("ELEMENT_NOT_FOUND")})):s.sync((function(){(a=s.getLibraryById(h))?r.findElement(e,t,i):"error"===s.syncState?i("COLLECTION_SYNC_ERROR"):i("LIBRARY_NOT_FOUND")})):i("COLLECTION_NOT_FOUND")}else i("UNPARSABLE_ELEMENT_REF")},fixRenditions:function(e){const t=e&&e.filter(e=>!e.isPublic)[0],i=t&&t.userId;if(!i)return;const r="VALIDATE_RENDITIONS_"+i;if(n.getValue(r))return;n.setValue(r,!0);const s=n.getValue("VALIDATE_RENDITIONS_SIZE_THRESHOLD");o.log("VALIDATE_RENDITIONS","Rendition invalidation check starting"),e.forEach(e=>{e.libraries.forEach(e=>{let t=!1;e.elements.forEach(i=>{const n=e._renditionCache.checkAndInvalidateRenditions(i,s);n&&(o.log("VALIDATE_RENDITIONS",n),t=!0)}),t&&(e._commit(!0,!0),e._notifyChange())})}),o.log("VALIDATE_RENDITIONS","Rendition invalidation check ending")}};e.exports=r},function(e,t){e.exports=require("uri-templates")},function(e,t,i){var n=i(2),o=i(14),r=i(108),s=i(36),a=i(11),c=i(4);function l(e,t,i){this._readOnly=i,this._owner=t,this._setData(e),this._localStorage=void 0}function h(e,t,i,o,r,s,a,l){var h=t._owner._core,d=e._owner._core,_=i&&e.id===t.id,p=d._getSourceHrefOfComponent(e),u=h.getComponentWithId(t.id),m=!(u&&u.etag||"unmodified"!==e.state),g=!_&&!p,f=g;if(r&&!u&&(p||g)&&e.id===t.id&&(t._data.id=c.generateUuid(),t.state="modified",t.etag=void 0,t.version=void 0,t.md5=void 0,t.length=void 0),s&&s._copyComponentMapping(e.id,l,t.id,a)&&(f=!1,_||(t.state="modified")),g){if(m){if(p=d._getHrefOfComponent(e),h._setSourceHrefOfComponent(p,t,a),!p&&f)throw new n(n.INVALID_STATE,"Failed to determine the source href of a component that does not have a local file.")}else if(f)throw new n(n.INVALID_STATE,"Could not use server-to-server copy for component "+e.id)}else h._setSourceHrefOfComponent(p,t,a);p&&(t.state="modified")}Object.defineProperties(l.prototype,{rootNode:{get(){return this.getChildWithAbsolutePath(r.ROOT_PATH)},set(){throw new n(n.READ_ONLY,'Property "rootNode" is read-only.')}},hasLocalStorage:{get(){return this._localStorage},set(){throw new n(n.READ_ONLY,"Cannot set the property hasLocalStorage.")}},isDirty:{get(){return this._isDirty},set(){throw new n(n.READ_ONLY,"Cannot set the property isDirty.")}},changeCount:{get(){return this._data.local&&this._data.local.change||0},set(){throw new n(n.READ_ONLY,"Cannot set the property changeCount.")}}}),l.prototype.getChildWithId=function(e){return this._allNodes[e]},l.prototype.getChildWithAbsolutePath=function(e){var t=this._absolutePaths[e.toLowerCase()];return t&&t instanceof r?t:void 0},l.prototype.getChildrenOf=function(e){if(!(e=e?this._allNodes[e.id]:this.rootNode))throw new n(n.INVALID_PARAMS,"Unknown node");var t,i=[],o=e._data.children;if(Array.isArray(o))for(t=0;t<o.length;t++){var r=o[t],s=this._allNodes[r.id];if(!s)throw new n(n.INVALID_DATA,"Node not in cache");i[i.length]=s}return i},l.prototype.addChild=function(e,t,i,o){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(t=t||c.generateUuid(),this._allNodes[t])throw new n(n.DUPLICATE_VALUE,"Node already exists in branch.");if(i&&("number"!=typeof i||i%1!=0))throw new n(n.INVALID_PARAMS,'Param "index" must be an integer.');var s=o?this._allNodes[o.id]:this.rootNode;if(!s)throw new n(n.INVALID_PARAMS,"Unknown parent node.");var a=new r;a.id=t,e&&(a.name=e),a._parentPath=s.absolutePath||s._parentPath;var l=s._data.children;return l?(i>=0&&i<=l.length||(i=l.length),i===l.length?l[i]=a._data:l.splice(i,0,a._data)):s._data.children=[a._data],this._allNodes[a.id]=a,a._owner=this._owner,this._setDirty(),a},l.prototype.removeChild=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "node".');if(e.isRoot)throw new n(n.INVALID_PARAMS,"Cannot remove the root node.");var t=e.id;if(!t)throw new n(n.INVALID_PARAMS,'Param "node" must have an id.');var i=this._nodeDataOfParentOfNode(e);if(!i)throw new n(n.INVALID_PARAMS,"Node not found in this branch.");return i.parentNodeData.children.splice(i.index,1),0===i.parentNodeData.children.length&&delete i.parentNodeData.children,e=this._allNodes[t],this._removeNodeFromCachesRecursively(e._data),this._setDirty(),e},l.prototype.moveChild=function(e,t,i){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "node".');if(e.isRoot)throw new n(n.INVALID_PARAMS,"Cannot move the root node.");if(t&&("number"!=typeof t||t%1!=0))throw new n(n.INVALID_PARAMS,'Param "index" must be an integer.');var o=e.id;if(!o)throw new n(n.INVALID_PARAMS,'Param "node" must have an id.');var r=this._nodeDataOfParentOfNode(e);if(e=this._allNodes[o],!r)throw new n(n.INVALID_PARAMS,"Node not found in this branch.");var s=i?this._allNodes[i.id]:this.rootNode;if(!s)throw new n(n.INVALID_PARAMS,"Unknown parent node.");if(this._nodeIdIsDescendantOf(s.id,e._data))throw new n(n.INVALID_PARAMS,"Must not create a cycle.");var a=r.parentNodeData.children.splice(r.index,1)[0];try{var c=s._data.children;c?(t>=0&&t<=c.length||(t=c.length),t===c.length?c[t]=a:c.splice(t,0,a)):s._data.children=[a]}catch(e){throw r.parentNodeData.children.splice(r.index,0,a),e}return 0===r.parentNodeData.children.length&&delete r.parentNodeData.children,this._setDirty(),this._allNodes[o]},l.prototype.copyChild=function(e,t,i,n,o,r){return this._copyChild(e,t,i,n,o,!1,r)},l.prototype.replaceChild=function(e,t,i,n){return this._copyChild(e,void 0,void 0,t,i||e.id,!0,n)},l.prototype.allComponents=function(){var e,t=[];for(e in this._allComponents)this._allComponents.hasOwnProperty(e)&&t.push(this._allComponents[e]);return t},l.prototype.getComponentWithId=function(e){return this._allComponents[e]},l.prototype.getComponentWithAbsolutePath=function(e){var t=this._absolutePaths[e.toLowerCase()];return t&&t instanceof s?t:void 0},l.prototype.getComponentsOf=function(e){if(!(e=e?this._allNodes[e.id]:this.rootNode))throw new n(n.INVALID_PARAMS,"Unknown node");var t,i=[],o=e._data.components;if(Array.isArray(o))for(t=0;t<o.length;t++){var r=o[t],s=this._allComponents[r.id];if(!s)throw new n(n.INVALID_DATA,"Component not in cache");i[i.length]=s}return i},l.prototype.addComponent=function(e,t,i,o,r,a,l,h,d,_){var p=this._localStorage;if(!p)throw new n(n.NO_LOCAL_STORAGE,"No local storage. Use AdobeDCXCompositeXfer.uploadNewComponent() followed by addComponentWithUploadResults()");if("function"!=typeof _&&r)throw new n(n.INVALID_PARAMS,'Param "callback" must be a function.');if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(d&&"string"!=typeof d)throw new n(n.INVALID_PARAMS,'Param "id" must be of type string.');if(!r&&!l)throw new n(n.INVALID_PARAMS,"Must provide either source or sourceHref.");try{if(l){var u=this._getBranchOf(this).compositeHref;if(u){var m=c.endPointOf(u),g=c.endPointOf(l);if(m&&g&&m!==g)throw new n(n.WRONG_ENDPOINT,"Given source href has an invalid endpoint: "+g)}}var f=this._local();d=d||c.generateUuid();var E=new s;E.id=d,E.name=e,E.type=t,E.relationship=i,E.path=o,E.state="modified";var y=this,v=function(e){if(!e)try{if(d&&y._allComponents[d])throw new n(n.DUPLICATE_VALUE,'The "id" of a component must be unique.');var t=h?y._allNodes[h.id]:y.rootNode;if(!t)throw new n(n.INVALID_PARAMS,"Unknown parent node.");var i=y._normalizedAbsolutePathForItem(E,t);if(y._absolutePaths[i])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+i);if(!c.isValidAbsolutePath(i))throw new n(n.INVALID_PARAMS,"Invalid absolute path: "+i);E._parentPath=t.absolutePath||t._parentPath;var o=t._data.components;o?o.push(E._data):t._data.components=[E._data],E._owner=y._owner,l&&y._setSourceHrefOfComponent(l,E),y._allComponents[E.id]=E,y._absolutePaths[i]=E,y._setDirty()}catch(t){p.removeComponentAsset(E,f),l&&y._setSourceHrefOfComponent(void 0,E),E=void 0,e=t}if(_)return _(e,E);if(e)throw e;return E};if(!r)return v();p.ingestComponentAsset(E,r,a,f,v)}catch(e){if(_)return _(e);throw e}},l.prototype.addComponentWithUploadResults=function(e,t,i,o,r){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(r.compositeId!==this._owner.compositeId)throw new n(n.INVALID_PARAMS,"Param uploadResults does not appear valid to be for this composite.");var a=Object.keys(r.records);if(1!==a.length)throw new n(n.INVALID_PARAMS,"Param uploadResults must contain records of exactly one component upload.");if(this._localStorage)throw new n(n.INVALID_PARAMS,"This method is for in-browser use only. Use addComponent() instead.");var c=r.records[a[0]],l=c.id;if(this._allComponents[l])throw new n(n.DUPLICATE_VALUE,"Duplicate component id: "+l);var h=o?this._allNodes[o.id]:this.rootNode;if(!h)throw new n(n.INVALID_PARAMS,"Unknown parent node.");var d=new s;d.id=l,d.name=e,d.type=c.type,d.relationship=t,d.path=i,d.state="unmodified",d.etag=c.etag,d.length=c.length,d.version=c.version,d.md5=c.md5;var _=this._normalizedAbsolutePathForItem(d,h);if(this._absolutePaths[_])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+_);d._parentPath=h.absolutePath||h._parentPath;var p=h._data.components;return p?p.push(d._data):h._data.components=[d._data],d._owner=this._owner,this._allComponents[l]=d,this._absolutePaths[_]=d,this._setDirty(),d},l.prototype.updateComponent=function(e,t,i,o){var r=this._localStorage;if(!r)throw new n(n.NO_LOCAL_STORAGE,"No local storage. Use AdobeDCXCompositeXfer.uploadComponent() to upload a new component asset and then call updateComponentWithUploadResults()");if("function"!=typeof o)throw new n(n.INVALID_PARAMS,'Param "callback" must be a function.');if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!(e=this._allComponents[e.id]))throw new n(n.INVALID_PARAMS,"Unknown component.");try{var s=this;r.ingestComponentAsset(e,t,i,this._local(),(function(t){if(!t)try{"modified"!==e.state?e.state="modified":s._setDirty(),s._setSourceHrefOfComponent(void 0,e)}catch(i){t=i,e=void 0}o(t,e)}))}catch(e){o(e)}},l.prototype.updateComponentWithUploadResults=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!(e=this._allComponents[e.id]))throw new n(n.INVALID_PARAMS,"Unknown component.");if(this._localStorage)throw new n(n.INVALID_PARAMS,"This method is for in-browser use only. Use updateComponent() instead.");if(t.compositeId!==this._owner.compositeId)throw new n(n.INVALID_PARAMS,"Param uploadResults does not appear valid to be for this composite.");var i=t.records[e.id];if(!i)throw new n(n.INVALID_PARAMS,"Param uploadResults does not contain an upload record for the given component.");return e.etag=i.etag,e.version=i.version,e.md5=i.md5,e.length=i.length,e},l.prototype.removeComponent=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "component".');var t=e.id;if(!t)throw new n(n.INVALID_PARAMS,'Param "component" must have an id.');var i=this._nodeDataOfParentOfComponent(e);if(!i)throw new n(n.INVALID_PARAMS,"Component not found in this branch.");return i.parentNodeData.components.splice(i.index,1),0===i.parentNodeData.components.length&&delete i.parentNodeData.components,e=this._allComponents[t],delete this._allComponents[t],delete this._absolutePaths[this._normalizedAbsolutePathForItem(e)],this._localStorage&&(this._localStorage.removeComponentAsset(e,this._local()),this._setSourceHrefOfComponent(void 0,e)),e._owner=void 0,e._parentPath="",this._setDirty(),e},l.prototype.moveComponent=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "component".');var i=e.id;if(!i)throw new n(n.INVALID_PARAMS,'Param "component" must have an id.');var o=this._nodeDataOfParentOfComponent(e);if(!o)throw new n(n.INVALID_PARAMS,"Component not found in this branch.");var r=t?this._allNodes[t.id]:this.rootNode;if(!r)throw new n(n.INVALID_PARAMS,"Unknown parent node.");var s=this._normalizedAbsolutePathForItem(e,r);if(this._absolutePaths[s])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+s);var a=o.parentNodeData.components.splice(o.index,1)[0],c=r._data.components;return c?c.push(a):r._data.components=[a],0===o.parentNodeData.components.length&&delete o.parentNodeData.components,e=this._allComponents[i],delete this._absolutePaths[this._normalizedAbsolutePathForItem(e)],e._parentPath=r.absolutePath||r._parentPath,this._absolutePaths[s]=e,this._setDirty(),e},l.prototype.copyComponent=function(e,t,i,n,o){return this._copyComponent(e,t,i,n,!1,o)},l.prototype.replaceComponent=function(e,t,i,n){return this._copyComponent(e,void 0,t,i||e.id,!0,n)},l.prototype.assetOfComponent=function(e,t){try{if(!this._localStorage)throw new n(n.NO_LOCAL_STORAGE,"No local storage.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "component".');if(!e.id)throw new n(n.INVALID_PARAMS,'Param "component" must have an id.');var i=this._localStorage.componentAssetPath(e,this._local());if(!t)return i;a.exists(i,(function(e){t(void 0,e?i:null)}))}catch(e){if(!t)throw e;t(e)}},l.prototype._getHrefOfComponent=function(e){var t,i=this._getBranchOf(e);if(i.compositeLinks)return c.getUrlFromLinks(i.compositeLinks,o.COMPONENT,{component_id:e.id});var n=i.compositeHref;return n&&void 0!==e.version&&(t=c.appendPathElements(n,e.id),t+=";version="+e.version),t},l.prototype._setSourceHrefOfComponent=function(e,t,i){var n=t.id,o=this._componentSourceHrefLookup(!0,i);e?o[n]=e:o[n]&&delete o[n]},l.prototype._getSourceHrefOfComponent=function(e,t){var i=e.id,n=this._componentSourceHrefLookup(!1,t);if(n)return n[i]},l.prototype._copySourceHrefsFrom=function(e){var t=e._componentSourceHrefLookup(!1),i=this.allComponents(),n=i.length;if(n&&t){var o,r=this._componentSourceHrefLookup(!0);for(o=0;o<n;o++){var s=i[o].id;r[s]=t[s]}}},l.prototype._getBranchOf=function(e){return e._owner?this._getBranchOf(e._owner):e},l.prototype._isSameComposite=function(e){var t=this._getBranchOf(this),i=this._getBranchOf(e);return t._data.id===i._data.id&&(t.compositeHref===i.compositeHref&&this._localStorage===e._localStorage)},l.prototype._stringify=function(e,t){if(e){var i=this._data.local,n=null;try{delete this._data.local,n=JSON.stringify(this._data,void 0,t?2:void 0)}catch(e){throw e}finally{i&&(this._data.local=i)}return n}return JSON.stringify(this._data,void 0,t?2:void 0)},l.prototype._setData=function(e){var t=new r(e,this._readOnly,!0);t._owner=this._owner,t._parentPath="";var i={},o={},a={};o[t.id]=t,a[r.ROOT_PATH]=t;var l=this,h=function(e,t,i,o,a){var d,_,p,u=e.components;if(Array.isArray(u))for(d=0;d<u.length;d++){var m=u[d],g=new s(m,l._readOnly);if(t[g.id])throw new n(n.INVALID_DATA,"Duplicate component id: "+g.id);if(g._owner=l._owner,g._parentPath=a,o[p=l._normalizedAbsolutePathForItem(g)])throw new n(n.INVALID_DATA,"Duplicate absolute path: "+p);if(!c.isValidAbsolutePath(p))throw new n(n.INVALID_DATA,"Invalid absolute component path: "+p);t[g.id]=g,o[p]=g}var f=e.children;if(Array.isArray(f))for(d=0;d<f.length;d++){var E=f[d],y=new r(E,l._readOnly);if(i[y.id])throw new n(n.INVALID_DATA,"Duplicate node id: "+y.id);if(_=y.path,y._owner=l._owner,y._parentPath=a,_){if(o[p=l._normalizedAbsolutePathForItem(y)])throw new n(n.INVALID_DATA,"Duplicate absolute path: "+p);if(!c.isValidAbsolutePath(p))throw new n(n.INVALID_DATA,"Invalid node absolute path: "+p);o[p]=y}i[y.id]=y,h(E,t,i,o,y.path?c.appendPathElements(a,y.path):a)}};return h(e,i,o,a,r.ROOT_PATH),this._data=e,this._allComponents=i,this._allNodes=o,this._absolutePaths=a,this._isDirty=!1,this},l.prototype._removeNodeFromCachesRecursively=function(e){var t,i=e.components;if(Array.isArray(i))for(t=0;t<i.length;t++){var n=i[t].id,o=this._allComponents[n];delete this._allComponents[n],delete this._absolutePaths[this._normalizedAbsolutePathForItem(o)],o._owner=void 0,this._localStorage&&(this._localStorage.removeComponentAsset(o,this._local()),this._setSourceHrefOfComponent(void 0,o))}var r=e.children;if(Array.isArray(r))for(t=0;t<r.length;t++)this._removeNodeFromCachesRecursively(r[t]);var s=e.id,a=this._allNodes[s];delete this._allNodes[s],a.path&&delete this._absolutePaths[this._normalizedAbsolutePathForItem(a)],a._owner=void 0},l.prototype._local=function(){return this._data.local||(this._data.local={version:2}),this._data.local},l.prototype._componentSourceHrefLookup=function(e,t){if(e&&this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(t||(t=e?this._local():this._data.local)){var i=t["componentS2SCopy#srcHref"];return!i&&e&&(i=t["componentS2SCopy#srcHref"]={}),i}},l.prototype._recursiveReset=function(e,t){var i,n=e.components;if(n)for(i=n.length-1;i>=0;i--){var o=n[i];"committedDelete"===o.state?(delete n[i],delete this._allComponents[o.id],delete o._owner,this._localStorage&&this._localStorage.removeComponentAsset(o,this._local()),this._setSourceHrefOfComponent(void 0,o,this._local())):(delete o.etag,delete o.version,delete o.length,delete o.md5,o.state="modified",t&&t(o))}var r=e.children;if(r)for(i=0;i<r.length;i++)this._recursiveReset(r[i],t)},l.prototype._nodeIdIsDescendantOf=function(e,t){var i,n=t.children;if(n)for(i=0;i<n.length;i++){var o=n[i];if(o.id===e||this._nodeIdIsDescendantOf(e,o))return!0}return!1},l.prototype._recursivelyGetAllComponentsOfChild=function(e,t){t=t||[];var i,n,o=e._data||e,r=o.components;if(r)for(n=r.length,i=0;i<n;i++)t[t.length]=this._allComponents[r[i].id];var s=o.children;if(s)for(n=s.length,i=0;i<n;i++)t=this._recursivelyGetAllComponentsOfChild(s[i],t);return t},l.prototype._nodeDataOfParentOfNode=function(e,t){t=t||this._data;var i,n=e._data.id,o=t.children;if(o)for(i=0;i<o.length;i++){var r=o[i];if(r.id===n)return{parentNodeData:t,index:i};var s=this._nodeDataOfParentOfNode(e,r);if(s)return s}return null},l.prototype._nodeDataOfParentOfComponent=function(e,t){t=t||this._data;var i,n=e._data.id,o=t.components;if(o)for(i=0;i<o.length;i++){if(o[i].id===n)return{parentNodeData:t,index:i}}var r=t.children;if(r)for(i=0;i<r.length;i++){var s=r[i],a=this._nodeDataOfParentOfComponent(e,s);if(a)return a}return null},l.prototype._determineAbsolutePathChangesRecursively=function(e,t,i){var n,o=e.components;if(o)for(n=0;n<o.length;n++){var r=o[n],s=this._allComponents[r.id];i.push({item:s,parentPath:t,absPath:c.appendPathElements(t,r.path)})}var a=e.children;if(a)for(n=0;n<a.length;n++){var l=a[n],h=this._allNodes[l.id],d=l.path,_=d?c.appendPathElements(t,d):t;i.push({item:h,parentPath:t,absPath:d?_:void 0}),this._determineAbsolutePathChangesRecursively(l,_,i)}},l.prototype._setPathOfNode=function(e,t){const i=t?c.appendPathElements(e.parentPath,t):e.parentPath,o=[{item:e,absPath:t?i:void 0}];this._determineAbsolutePathChangesRecursively(e._data,i,o);for(let e=0;e<o.length;e++){const t=o[e],i=o[e].item;if(t.absPath){const e=t.absPath.toLowerCase(),o=this._absolutePaths[e];if(o){if(i.absolutePath&&o===this._normalizedAbsolutePathForItem(i))return;throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+e)}if(!c.isValidAbsolutePath(e))throw new n(n.INVALID_PARAMS,"Invalid absolute path: "+e)}}for(let e=0;e<o.length;e++){const t=o[e],i=t.item;if(i._data.path&&delete this._absolutePaths[this._normalizedAbsolutePathForItem(i)],t.absPath){const e=t.absPath.toLowerCase();this._absolutePaths[e]=t.item}t.parentPath&&(i._parentPath=t.parentPath)}e._data.path=t},l.prototype._setPathOfComponent=function(e,t){if(!this._allComponents[e.id])throw new n(n.INVALID_PARAMS,"Unknown component.");var i=c.appendPathElements(e.parentPath,t).toLowerCase();if(this._absolutePaths[i])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path for component: "+i);if(!c.isValidAbsolutePath(i))throw new n(n.INVALID_PARAMS,"Invalid absolute path: "+i);delete this._absolutePaths[this._normalizedAbsolutePathForItem(e)],this._absolutePaths[i]=e,e._data.path=t},l.prototype._setDirty=function(e){if(!e){if("pending"===this._local().archivalState||"archived"===this._local().archivalState)throw new n(n.INVALID_STATE,"Cannot modify an archived composite.");"pendingDiscard"!==this._data.state&&"pendingDelete"!==this._data.state&&"committedDelete"!==this._data.state||console.error("Modifying deleted composite")}this._isDirty=!0,this._local().change=this.changeCount+1,e||"unmodified"!==this._data.state&&this._data.state||(this._data.state="modified")},l.prototype._normalizedAbsolutePathForItem=function(e,t){return(t?c.appendPathElements(t.absolutePath||t._parentPath,e.path):e.absolutePath).toLowerCase()},l.prototype._hasSameEndpoint=function(e){var t=this._getBranchOf(this).compositeHref,i=this._getBranchOf(e).compositeHref;if(t&&i){var n=c.endPointOf(t),o=c.endPointOf(i);if(n&&o&&n!==o)return!1}return!0},l.prototype._copyComponent=function(e,t,i,o,r,s){if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "component".');if(s&&"function"!=typeof s)throw new n(n.INVALID_PARAMS,"Param callback must be a function.");var a=this,c=e._owner._core,l=this._isSameComposite(c),d=l||this._hasSameEndpoint(e),_=c._local(),p=this._localStorage,u=c._localStorage,m=p&&u;if(m&&!s&&!l)throw new n(n.INVALID_PARAMS,"Must pass a callback when copying between two different composites.");if(!m&&!d)throw new n(n.NO_LOCAL_STORAGE,"Cannot copy between two different endpoints without local storage.");var g=function(e,t,i){h(e,t,l,0,!o,m?p:void 0,i,_)},f=m?u.componentAssetPath(e,_):void 0;if(!s)return this._copyComponentModel(e,t,r,i,o,g);if(l||!f)try{s(void 0,this._copyComponentModel(e,t,r,i,o,g))}catch(e){s(e)}else{var E={};p.ingestComponentAsset(e,f,!0,E,(function(n){if(n)s(n);else try{_=E,s(void 0,a._copyComponentModel(e,t,r,i,o,g))}catch(e){s(e)}}))}},l.prototype._copyComponentModel=function(e,t,i,o,r,a){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "component".');var l=e._owner,h=new s(JSON.parse(JSON.stringify(e._data)));o?(h.path=o,h.id=r||c.generateUuid()):r&&(h.id=r),h._owner=this._owner,e.id===h.id&&this._isSameComposite(l._core)||(h.state="modified",h.etag=void 0,h.version=void 0,h.md5=void 0,h.length=void 0);var d,_,p=this._allComponents[h.id];if(p&&!i)throw new n(n.DUPLICATE_VALUE,"Component already exists.");if(i&&!p)throw new n(n.INVALID_PARAMS,"Could not find existing component.");if(i){var u=this._nodeDataOfParentOfComponent(p);if(!u)throw new n(n.INVALID_PARAMS,"Parent node of existing component not found in this branch.");var m=u.parentNodeData.id;if(!(_=this._allNodes[m]))throw new n(n.INVALID_STATE,"Unknown parent node.");d=u.index}else if(!(_=t?this._allNodes[t.id]:this.rootNode))throw new n(n.INVALID_PARAMS,"Unknown parent node.");h._parentPath=_.absolutePath||_._parentPath;var g=this._normalizedAbsolutePathForItem(h),f=this._absolutePaths[g];if(f&&f!==p)throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+g);if(!c.isValidAbsolutePath(g))throw new n(n.INVALID_PARAMS,"Component path must be a valid path for a component.");var E=this._local();a&&a(e,h,E=c.deepCopy(E));var y=_._data.components;return i?y[d]=h._data:y?y.push(h._data):_._data.components=[h._data],this._data.local=E,this._allComponents[h.id]=h,this._absolutePaths[g]=h,this._setDirty(),h},l.prototype._copyChild=function(e,t,i,o,r,s,a){if(!e)throw new n(n.INVALID_PARAMS,'Expecting param "node".');var c=this,l=e._owner._core,d=this._isSameComposite(l),_=d||this._hasSameEndpoint(e),p=l._local(),u=this._localStorage,m=l._localStorage,g=u&&m,f=l._recursivelyGetAllComponentsOfChild(e);if(f.length>0){if(g&&!a&&!d)throw new n(n.INVALID_PARAMS,"Must pass a callback when copying between two different composites.");if(!g&&!_)throw new n(n.NO_LOCAL_STORAGE,"Cannot copy components between two different endpoints without local storage.")}var E=function(e,t,i){h(e,t,d,0,!0,g?u:void 0,i,p)};if(!a)return this._copyChildModel(e,t,i,s,o,r,E);var y=function(){a(void 0,c._copyChildModel(e,t,i,s,o,r,E))};if(0===f.length||d||!g)try{y()}catch(e){a(e)}else{var v,A,C={},I=f.length,S=0,L=function(e){if(e&&!A&&(A=e),0===--S)if(A)a(A);else try{p=C,y()}catch(e){a(e)}};for(v=0;v<I;v++){var T=f[v],R=m.componentAssetPath(T,p);R&&(S++,u.ingestComponentAsset(T,R,!0,C,L))}if(0===S)try{y()}catch(e){a(e)}}},l.prototype._copyChildModel=function(e,t,i,o,a,l,h){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");var d=e._owner,_=new r(JSON.parse(JSON.stringify(e._data)));a?(_.path=a,_.id=l||c.generateUuid()):l&&(_.id=l),_._owner=this._owner,e.isRoot&&(delete _._data.local,delete _._data["manifest-format-version"]);var p,u=this._allNodes[_.id];if(u&&!o)throw new n(n.DUPLICATE_VALUE,"Child node already exists.");if(o&&!u)throw new n(n.INVALID_PARAMS,"Could not find existing node to replace.");if(o){var m=this._nodeDataOfParentOfNode(u);if(!m)throw new n(n.INVALID_PARAMS,"Parent of existing node not found in this branch.");var g=m.parentNodeData.id;if(!(p=this._allNodes[g]))throw new n(n.INVALID_STATE,"Unknown parent node.");i=m.index}else if(!(p=t?this._allNodes[t.id]:this.rootNode))throw new n(n.INVALID_PARAMS,"Unknown parent node.");if(_._parentPath=p.absolutePath||p._parentPath,_.path){var f=this._normalizedAbsolutePathForItem(_),E=this._absolutePaths[f];if(E&&E!==u)throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+f);if(!c.isValidAbsolutePath(f))throw new n(n.INVALID_PARAMS,"Node path must be a valid path for a node.")}var y=c.flatCopy(this._allNodes),v=c.flatCopy(this._allComponents),A=c.flatCopy(this._absolutePaths),C=c.deepCopy(this._local()),I=function(e,t,i,n,o,r){var s,a;delete i[e.id],e.path&&delete o[t._normalizedAbsolutePathForItem(e)];var c=e._data.children;if(c)for(a=c.length,s=0;s<a;s++)I(i[c[s].id],t,i,n,o,r);var l=e._data.components;if(l)for(a=l.length,s=0;s<a;s++){var h=n[l[s].id];delete n[h.id],delete o[t._normalizedAbsolutePathForItem(h)],t._localStorage&&(t._localStorage.removeComponentAsset(h,r),t._setSourceHrefOfComponent(void 0,h,r))}};u&&I(u,this,y,v,A,C);var S=function(e,t,i,o,a,l,d,_){if(o[e.id])throw new n(n.DUPLICATE_VALUE,"Duplicate node id: "+e.id);var p;if(o[e.id]=e,e.path){if(l[p=t._core._normalizedAbsolutePathForItem(e)])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+p);l[p]=e}var u,m,g=e._data.children;if(g)for(m=g.length,u=0;u<m;u++){var f=new r(g[u]);o[f.id]&&(f.id=c.generateUuid()),f._owner=t,f._parentPath=e.absolutePath||e._parentPath,S(f,t,i,o,a,l,d,_)}var E=e._data.components;if(E)for(m=E.length,u=0;u<m;u++){var y=new s(E[u]),v=y.id;if(a[v]&&(y.id=c.generateUuid(),y.state="modified",y.etag=void 0,y.version=void 0,y.md5=void 0,y.length=void 0),y._owner=t,y._parentPath=e.absolutePath||e._parentPath,h&&h(i.getComponentWithId(v),y,d),a[y.id])throw new n(n.DUPLICATE_VALUE,"Duplicate component id: "+y.id);if(a[y.id]=y,l[p=t._core._normalizedAbsolutePathForItem(y)])throw new n(n.DUPLICATE_VALUE,"Duplicate absolute path: "+p);l[p]=y}};if(S(_,this._owner,d,y,v,A,C,d._local()),o)p._data.children[i]=_._data;else{var L=p._data.children;L?(i>=0&&i<=L.length||(i=L.length),i===L.length?L[i]=_._data:L.splice(i,0,_._data)):p._data.children=[_._data]}return this._allNodes=y,this._allComponents=v,this._absolutePaths=A,this._data.local=C,this._setDirty(),_},l.prototype._verifyIntegrity=function(e,t,i){var o,s=this,a=[],l=!1,h=function(e){return a.push(new n(n.INVALID_STATE,e)),t&&(l||(t("Branch for composite "+s.rootNode.id+" has the following errors:"),l=!0),t("   "+e)),!1},d=function(e,t){return!!e||h(t)},_=[],p=function(e){(_.indexOf(e)<0||h("Item "+e.id+" encountered more than once"))&&_.push(e)},u=c.flatCopy(this._allComponents),m=c.flatCopy(this._allNodes),g=c.flatCopy(this._absolutePaths),f=Object.keys(g),E=f.length;for(o=0;o<E;o++){var y=f[o];d("/"===y.charAt(0),"Absolute path "+y+" does not start with a slash.")}var v=function(e,t){var i,n,o=e.children;if(o)for(i=0;i<o.length;i++){var r=o[i],a=m[r.id];(a||h("Node "+r.id+" is not in cache."))&&(p(a),d(a._data===r,"Node "+a.id+" _data property incorrect."),delete m[a.id],a.path&&a._owner&&(n=s._normalizedAbsolutePathForItem(a),(g[n]||h("Absolute path of node "+a.id+" ("+n+") is not in cache."))&&delete g[n]),d(a._parentPath===t,"Parent path of node "+a.id+" should be "+t+" but is "+a._parentPath),d(a._owner===s._owner,"Node "+a.id+" _owner property is not correct.")),v(r,r.path?c.appendPathElements(t,r.path):t)}var l=e.components;if(l)for(i=0;i<l.length;i++){var _=l[i],f=u[_.id];(f||h("Component "+_.id+" is not in cache."))&&(p(f),d(f._data===_,"Component "+f.id+" _data property incorrect."),delete u[f.id],f._owner&&(n=s._normalizedAbsolutePathForItem(f),(g[n]||h("Absolute path "+n+" is not in cache."))&&delete g[n]),d(f._parentPath===t,"Parent path of component "+f.id+" should be "+t+" but is "+f._parentPath),d(f._owner===s._owner,"Component "+f.id+" _owner property is not correct."))}},A=g[r.ROOT_PATH];d(A,"Cannot find root node via path")&&(d(A.id===this._data.id,"Root node has correct id"),d(A.path===r.ROOT_PATH,"Root node has correct path"),d(""===A._parentPath,"Root node has correct parent path"),d(A._owner===this._owner,"Root node has correct owner"),d(A._data===this._data,"Root node has correct data"),d(m[A.id]===A,"Cannot find root node via id")&&delete m[A.id],delete g[r.ROOT_PATH]),v(this._data,r.ROOT_PATH);var C=Object.keys(u);for(o=0;o<C.length;o++)h("Component "+C[o]+" is in cache but could not be found.");for(C=Object.keys(m),o=0;o<C.length;o++)h("Node "+C[o]+" is in cache but could not be found.");for(C=Object.keys(g),o=0;o<C.length;o++)h("Absolute path "+C[o]+" is in cache but could not be found.");if(this._localStorage){var I=this._localStorage.componentIds(this._local());for(o=0;o<I.length;o++)d(this._allComponents[I[o]],"Component "+I[o]+" is in local storage mapping but could not be found in the manifest.");if(e)for(I=Object.keys(this._allComponents),o=0;o<I.length;o++){var S=I[o],L=this._allComponents[S],T=this._localStorage.componentAssetPath(L,this._local());d(T,"Component "+S+" does not have an entry in local storage mapping.")&&i&&d(i.existsSync(T),"Asset "+T+" does not exist.")}var R=this._componentSourceHrefLookup();if(R)for(E=(I=Object.keys(R)).length,o=0;o<E;o++){var O=this._allComponents[I[o]];O?d("modified"===O.state,"Component "+I[o]+" is in local source href mapping but has a state of "+O.state):d(!1,"Component "+I[o]+" is in local source href mapping but could not be found in the manifest.")}}return a.length?a:null},e.exports=l},function(e,t,i){var n=i(2),o=i(11);function r(e,t,i){i?this._setData(i,e.href):this._data={"push-journal-format-version":3,"composite-href":e.href,"uploaded-components":{}},this._filePath=t,this._waitingCallbacks=[],this._commitInProgress=!1,this._needAnotherCommit=!1}r.readJournal=function(e,t,i,n){o.readFile(e,"utf8",(function(o,s){var a;if(o&&o.code&&i&&(o=void 0),!o)try{s=JSON.parse(s),a=new r(t,e,s)}catch(n){i?a=new r(t,e):o=n}n(o,o?void 0:a)}))},Object.defineProperties(r.prototype,{compositeHref:{get(){return this._data["composite-href"]},set(e){e?this._data["composite-href"]=e:delete this._data["composite-href"]}},manifestEtag:{get(){return this._data.etag},set(e){e?this._data.etag=e:delete this._data.etag}},currentBranchEtag:{get(){return this._data["current-branch-etag"]},set(e){e?this._data["current-branch-etag"]=e:delete this._data["current-branch-etag"]}},compositeAssetId:{get(){return this._data["composite-asset-id"]},set(e){e?this._data["composite-asset-id"]=e:delete this._data["composite-asset-id"]}},compositeLinks:{get(){return this._data["composite-links"]},set(e){e?this._data["composite-links"]=e:delete this._data["composite-links"]}},changeCount:{get(){return this._data.change},set(e){e?this._data.change=e:delete this._data.change}},compositeHasBeenCreated:{get(){return!!this._data["composite-created"]},set(e){e?this._data["composite-created"]=!0:delete this._data["composite-created"]}},compositeHasBeenDeleted:{get(){return!!this._data["composite-deleted"]},set(e){e?this._data["composite-deleted"]=!0:delete this._data["composite-deleted"]}},compositeHasBeenArchived:{get(){return!!this._data["composite-archived"]},set(e){e?this._data["composite-archived"]=!0:delete this._data["composite-archived"]}},isEmpty:{get(){return 0===Object.keys(this._data["uploaded-components"]).length&&!this.compositeHasBeenDeleted&&!this.manifestEtag},set(){throw new n(n.READ_ONLY,"This property is read-only.")}},isComplete:{get(){return!!(this._data.etag&&this._data.change||this._data["composite-deleted"]||this._data["composite-archived"])},set(){throw new n(n.READ_ONLY,"This property is read-only.")}}}),r.prototype.recordUploadedComponent=function(e,t,i,n,o,r,s){var a={etag:t,length:o,version:i,md5:n};r&&(a["storage-name"]=r),s&&(a["source-href"]=s),a.timestamp=(new Date).toISOString(),this._data["uploaded-components"][e]=a},r.prototype.idsOfAllUploadedComponents=function(){return Object.keys(this._data["uploaded-components"])};r.prototype.getRecordForUploadedComponent=function(e){var t=this._data["uploaded-components"][e];if(t&&!this.isComplete){var i=t.timestamp;if(!i)return this.removeRecordForUploadedComponent(e);if(i=new Date(i),isNaN(i.getTime()))return this.removeRecordForUploadedComponent(e);if(Date.now()-i.getTime()>=6048e5)return this.removeRecordForUploadedComponent(e)}return t},r.prototype.removeRecordForUploadedComponent=function(e){delete this._data["uploaded-components"][e]},r.prototype.applyToBranch=function(e,t){if(!this.isComplete)throw new n(n.INVALID_STATE,"Journal is not complete.");var i=e.isDirty;if(this.compositeHasBeenDeleted)e._data.state="committedDelete",e.manifestEtag=this.manifestEtag;else{this.compositeHasBeenArchived&&(e.compositeArchivalState="archived");var o,r="unmodified"!==e.compositeState&&this.changeCount!==e.changeCount,s=this.idsOfAllUploadedComponents(),a=s.length;for(o=0;o<a;o++){var c=s[o],l=e.getComponentWithId(c);if(l){var h=this.getRecordForUploadedComponent(l.id);l._data.etag=h.etag,l._data.length=h.length,l._data.version=h.version,l._data.md5=h.md5,h["source-href"]?e._core._getSourceHrefOfComponent(l)===h["source-href"]&&(l._data.state="unmodified",e._core._setSourceHrefOfComponent(void 0,l)):e.hasLocalStorage&&e._localStorage.componentAssetName(l,e._local())===h["storage-name"]?(l._data.state="unmodified",e._core._setSourceHrefOfComponent(void 0,l)):e.hasLocalStorage||(l._data.state="unmodified")}}e.manifestEtag=this.manifestEtag,["compositeHref","compositeAssetId","compositeLinks"].forEach(t=>{this[t]!==e[t]&&(e[t]=this[t])}),r||(e._data.state="unmodified")}t&&(e._isDirty=i)},r.prototype.commitChanges=function(e){if(this._filePath){var t=this,i=function(e){t._needAnotherCommit=!1,t._commitInProgress=!0,t._waitingCallbacks=[],o.writeFileAtomically(t._filePath,JSON.stringify(t._data),"utf8",(function(n){var o,r=e.length;for(o=0;o<r;o++)try{e[o](n)}catch(e){}t._needAnotherCommit?i(t._waitingCallbacks):t._commitInProgress=!1}))};t._commitInProgress?(this._needAnotherCommit=!0,e&&this._waitingCallbacks.push(e)):i(e?[e]:[])}else e&&e()},r.prototype._setData=function(e,t){if(e["push-journal-format-version"]<=2){var i=e["uploaded-components"];if(i){var n,o=Object.keys(i),r=o.length;for(n=0;n<r;n++){var s=i[o[n]];"number"==typeof s.version&&(s.version=String(s.version))}}e["push-journal-format-version"]=3}var a=this._verify(e,t);if(null===a)return this._data=e,this;throw a},r.prototype._verify=function(e,t){return 3!==e["push-journal-format-version"]?new n(n.INVALID_DATA,"Wrong push journal format version."):e["composite-href"]!==t?new n(n.INVALID_DATA,"Composite and journal hrefs mismatch."):e["uploaded-components"]?null:new n(n.INVALID_DATA,"Missing component list.")},e.exports=r},function(e,t){e.exports=class{}},function(e,t,i){const n=i(48),o=i(2),r=o.networkError,s=o.unexpectedResponse,a=i(11);e.exports=class extends n{uploadAssetAtComponentHref(e,t,i,n,a,c,l,h){const d={};t&&(d["Content-Type"]=t);const _=(t,i)=>{t?delete d["If-Match"]:d["If-Match"]="*";var n=this._service.invoke("PUT",e,d,l,void 0,(function(e,t){if(e)return i(r("Error uploading component",e,t));var n=t.statusCode;if(200===n||201===n||204===n){const n=t.responseText||t.response;if(!n||0===n.length)return i(void 0,t);var a;try{a=JSON.parse(n)}catch(n){return(e=new o(o.INVALID_DATA,"Invalid JSON returned by server",n)).response=t,i(e,t,a)}i(void 0,t,a)}else 507===n?((e=new o(o.EXCEEDS_QUOTA,"Exceeds quota",e)).response=t,i(e)):((e=s("Unexpected response uploading component",e)).response=t,i(e))}));return n.token=c,n};return _(n,(t,i,o)=>{if(t){if(!(i=t.response))return h(t);const o=i.statusCode;n||404!==o?!n||409!==o&&412!==o?h(t):this._checkForComponentAlreadyUploaded(e,l,(e,t)=>{e?h(null,e,{md5:t}):_(!1,h)}):_(!0,h)}else h(void 0,i,o)})}updateManifestAtHref(e,t,i,n,a){const c={"Content-Type":"application/vnd.adobe.dcx-manifest+json"};return n?c["If-Match"]="*":i&&(c["If-Match"]=i),this._service.invoke("PUT",e,c,t,void 0,(function(e,t){if(e)return a(r("Error updating manifest",e,t));const c=t.statusCode;!t.headers.etag||200!==c&&201!==c&&204!==c?412===c||i&&!n&&409===c?((e=new o(o.UPDATE_CONFLICT,"Manifest has been changed")).response=t,a(e)):a(s("Unexpected response updating manifest",e,t)):a(void 0,t)}))}_checkForComponentAlreadyUploaded(e,t,i){if(!(a.canUseFileSystem&&e&&t&&t.filename))return i();a.getMD5Hash(t.filename,(t,n)=>{if(t)return i();this.headRequest(e,(e,t)=>{if(e)return i();const o=t&&t.statusCode,r=t&&t.headers["content-md5"];200!==o||r!==n?i():i(t,r)})})}}},function(e,t,i){var n=i(2),o=n.networkError,r=n.unexpectedResponse,s=i(4),a=s.merge,c=s.appendPathElements;e.exports=class{constructor(e,t,i){if(this._service=e,this._server=t,this._allowedEndpointRegex=i,t&&(this._endPoint=s.endPointOf(t)),this.SYNC_ASYNC_DEFAULT_DELAY=5,this.ASYNC_DEFAULT_DELAY=1,this.DEFAULT_POLL_DELAY=10,this._maxRedirects=5,this._authenticationWhitelist=[],!this._endPoint)throw new n(n.INVALID_PARAMS,"Could not determine endpoint from: "+t);this.authenticationWhitelist=["adobe.com","adobe.io","fotolia.net"]}get maxRedirects(){return this._maxRedirects}set maxRedirects(e){if("number"!=typeof e)throw new n(n.INVALID_PARAMS,"Expecting a number.");this._maxRedirects=Math.floor(e)}get authenticationWhitelist(){return this._authenticationWhitelist}set authenticationWhitelist(e){if(!Array.isArray(e))throw new n(n.INVALID_PARAMS,"Expecting an array.");this._authenticationWhitelist=e}isValidHref(e){const t=s.endPointOf(e);return!t||this._isEndpointAllowed(t)}isDomainOnWhitelist(e){var t=s.parseURI(e).authority;if(!t||0===t.length)return!0;var i=t.length;const n=this._authenticationWhitelist.length;for(let e=0;e<n;e++){var o=this._authenticationWhitelist[e],r=o.length;if((i>r?t.slice(-r):t)===o)return!0}return!1}getAsset(e,t,i,c){if(!(e=this._resolveUrl(e)))return c(new n(n.WRONG_ENDPOINT,"Wrong endpoint: "+e));var l,h={};"string"==typeof t?h["If-None-Match"]=t:a(h,t);var d,_=this,p=0;function u(e,t){if(e)return c(o("Error downloading an asset",e,t));var i=t.statusCode;if(200===i)c(void 0,t);else if(304===i)c(void 0,t);else if(301===i||302===i||303===i||307===i)if(!_._service.handlesRedirects&&_.maxRedirects)if(p<_.maxRedirects){var n=t.headers.location;n?d(n):c(r("Missing location header in redirect response",e,t))}else c(r("Too many redirects",e,t));else c(r("Unexpected response getting an asset",e,t));else c(r("Unexpected response getting an asset",e,t))}return(l=(d=function(t){var n={responseType:i};return t&&(p++,n.reuseRequestDesc=l,_.isDomainOnWhitelist(t)||(h.Authorization=null)),_._service.invoke("GET",t||e,h,void 0,n,u)})()).progress=s.noOp,l}getAssetAsType(e,t,i,n){return this.getAsset(e,i,t,(function(e,t){if(e)return n(e);if(200===t.statusCode){var i=t.response||t.responseText;n(void 0,i,t.headers.etag,t)}else 304===t.statusCode?n(void 0,null,t.headers.etag,t):n(r("Unexpected response getting asset",e,t))}))}headRequest(e,t){return this._service.invoke("HEAD",e,{},void 0,void 0,(function(e,i){if(e)return t(e);t(e,i)}))}abortAll(){this._service.abortAll()}_resolveUrl(e){if(void 0===e)return;const t=s.endPointOf(e);if(t){if(!this._isEndpointAllowed(t))return;return e}return c(this._server,e)}_isEndpointAllowed(e){return this._allowedEndpointRegex&&this._allowedEndpointRegex.test(e)||e===this._endPoint}_makeRelativeUrl(e){var t=s.endPointOf(e);if(t){if(t!==this._endPoint)return;var i=s.parseURI(e);(i.scheme||i.authority)&&(e=i.path,i.query&&(e+="?"+i.query),i.fragment&&(e+="#"+i.fragment))}return e}_parseAsyncResponse(e){var t=e.responseText||e.response;if(!t)throw new n(n.INVALID_DATA,"No body data.");var i={},o=t.indexOf("\n");if(-1===o)throw new n(n.INVALID_DATA,"Could not find status line.");var r=t.slice(0,13===t.charCodeAt(o-1)?o-1:o).split(" ");if(i.statusCode=parseInt(r[1],10),!i.statusCode)throw new n(n.INVALID_DATA,"Could not find status code.");r.length>2&&(i.statusText=r[2]);var a=t.search(/\r?\n\r?\n/);-1===a&&(a=t.length);var c=t.slice(o+1,a);i.headers=s.parseHeaders(c);var l="\r"===t.charAt(a)?a+4:a+2;return i.response=t.slice(l),i}_pollForAsyncResponse(e,t,i,n=this._parseAsyncResponse,a){var c=Date.now()+1e3*t,l={responseType:"text",reuseRequestDesc:i,noSoonerThen:c};s.log("asynchronous request - polling"),i=this._service.invoke("GET",e,void 0,void 0,l,(t,c)=>{if(t)return a(o("Error polling for an asynchronous reponse",t,c));var l=c.statusCode;if(202===l){s.log("asynchronous request - not yet ready");var h=c.headers["retry-after"];h&&(h=parseInt(h,10)),this._pollForAsyncResponse(e,h||this.DEFAULT_POLL_DELAY,i,n,a)}else if(200===l){s.log("asynchronous request - success");try{c=n(c)}catch(e){return a(r("Error parsing response body.",e,c))}200===(l=c.statusCode)||201===l||204===l?a(void 0,c):a(r("Unexpected response polling for an asynchronous response",t,c))}else s.log("asynchronous request - error"),a(r("Unexpected response polling for an asynchronous response",t,c))})}_handle202Response(e,t,i,n,o){var s,a=e.responseText||e.response;try{s=JSON.parse(a)}catch(t){return o(r("Error parsing 202 response body.",t,e))}var c=s.href;if(!c)return o(r("202 response missing an href.",void 0,e));var l=e.headers["retry-after"];l=l?parseInt(l,10):i,this._pollForAsyncResponse(this._resolveUrl(c),l,t,n,o)}_doHeadRequest(e){return new Promise((t,i)=>{this.headRequest(e,(e,o)=>e?i(new n(n.NETWORK_ERROR,"HEAD request failed",e)):[200,202,204].includes(o.statusCode)?void t(o):i(n.wrapError(n.UNEXPECTED_RESPONSE,"HEAD request yielded unexpected response",void 0,o)))})}_getCopyDelegate(e,t,i){if(!this.isValidHref(e))return i(new n(n.WRONG_ENDPOINT,`Source href is not compatible with this service: ${e}`));i(null,(i,n,o,r,s,a)=>this.copyAssetToComponentId(i,n,t,o,r,s,e,a))}}},function(e,t,i){const n=i(47),o=i(2),r=i(14),s=i(4),a=i(28),c=i(115),l=o.networkError,h=o.unexpectedResponse,d=i(116),_=i(43),p=/^(https:\/\/cc-api-storage(?:-stage)?\.adobe\.io(?::443)?\/.+)\/([^;/]+)/,u=/\/[^/]+$/,m=/[\\/:*?"|><]/g,g=/^CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]$/i;e.exports=class extends n{constructor(e,t,i,n){super(e,t,i),this.setRootDocument(n)}getRootDocument(e){const t={_links:{[r.OPS]:{href:`${this._server}/content/directory/ops`},[r.RESOLVE_ID]:{href:`${this._server}/content/directory/resolve{?repositoryId,id,rel_type}`},[r.RESOLVE_PATH]:{href:`${this._server}/content/directory/resolve{?repositoryId,path,rel_type}`}},children:[{"repo:name":"assets",_links:{[r.PRIMARY]:{href:`${this._server}/discovery`}}},{"repo:name":"repositories",_links:{[r.PRIMARY]:{href:`${this._server}/content/directory`}}}]};this.setRootDocument(t),e(null,t)}setRootDocument(e){this._rootDocument=e,this._rootLinks=e&&e._links}getAssets(e){let t;try{t=this._getUrlFromRootDocument("assets")}catch(t){return e(t)}this._getAllPages(t).then(({result:t,etag:i,headers:n})=>e(null,t,i,n),e)}getRepositories(e){let t;try{t=this._getUrlFromRootDocument("repositories")}catch(t){return e(t)}this._getAllPages(t).then(({result:t,etag:i,headers:n})=>e(null,t,i,n),e)}getEffectiveACFromLinks(e,t){const i=e=>{t(new o(o.UNEXPECTED_RESPONSE,"Unable to get permissions for object",e))},n=s.getUrlFromLinks(e,r.AC_EFFECTIVE);this._getResponse(n).then(e=>{const n=e&&e.result,o=n&&n[r.PRIMARY]||n["*"];if(!o)return i();t(null,o)},i)}getLinksFromUrn(e,t){const i=s.getUrlFromLinks(this._rootLinks,r.RESOLVE_ID,{id:e});this._getLinks(i).then(e=>t(null,e),t)}getLinksFromPath(e,t,i){const n=s.getUrlFromLinks(this._rootLinks,r.RESOLVE_PATH,{repositoryId:e,path:t});this._getLinks(n).then(e=>i(null,e),i)}getCollection(e,t,i){const n={};t&&(n["If-None-Match"]=t),this._getAllPages(e,n).then(({result:e,etag:t,headers:n})=>i(null,e,t,n),i)}getComponent(e,t,i){const n=this.getComponentHref(e,e.version);return this.getAsset(n,void 0,t,i)}getRenditionOfComponent(e,t,i,n,o){this.getComponentRenditionHref(e,e.version,i).then(e=>{this.getAsset(e,{accept:t},n,o)},o)}getCompositeManifest(e,t,i){const n=this.getCompositeManifestHref(e);return this.getAssetAsType(n,"text",t,i)}createCompositeDirectory(e,t,i){if(t)return i(new o(o.INVALID_PARAMS));this._createComposite(e).then(({response:t})=>{const n=this._getLinksFromResponse(t);e.links=n,e.href=s.getUrlFromLinks(n,r.PRIMARY),e.assetId=t.headers["x-resource-id"],i(void 0,t)},i)}deleteCompositeDirectory(e,t){t(new o(o.INVALID_STATE,"Composites can only be discarded on platform."))}discardComposite(e,t){const i={"Content-Type":"application/vnd.adobecloud.directory+json","If-Match":"*"};this._service.invoke("POST",s.getUrlFromLinks(e.links,r.DISCARD),i,void 0,{responseType:"text"},(i,n)=>{const o=()=>{t(l("Error disposing composite directory",i,n))};return i||![200,201,204,403,404].includes(n.statusCode)?o():403===n.statusCode?this._getLinks(s.getUrlFromLinks(e.links,r.PRIMARY)).then(e=>{if(s.getUrlFromLinks(e,r.DISCARD))return o();t(void 0,n)},o):void t(void 0,n)})}renameCompositeIfNecessary(e,t){if(this._doesRepoNameMatchPath(e))return t();const i=s.getUrlFromLinks(e.links,r.METADATA);this._getResponse(i).then(({result:n})=>{const r=n["repo:path"],s=r.replace(u,""),a=n["repo:repositoryId"];if(s===r||!a)return t(new o(o.UNEXPECTED_RESPONSE,`Could not get metadata: ${i}`));this._findAvailablePath(e,s,a).then(i=>{this._invokeOperation("move",{href:e.href,"if-match":"*"},{path:i,"repo:repositoryId":a,"if-match":"*"},i=>{if(i)return t(i);this._getLinks(e.href).then(i=>{e.links=i,t()},t)})},t)},t)}uploadComponent(e,t,i,n,c,l){if(!e._owner||!e._owner.compositeLinks)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");const h=e._owner.compositeLinks,d=h[r.CREATE]&&h[r.CREATE]["repo:maxsingletransfersize"]||9437184;if(c instanceof a&&c.size>=d)return this._blockUploadComponent(e,t,i,n,c,l);const _=s.getUrlFromLinks(e._owner.compositeLinks,r.COMPONENT,{component_id:e.id});return this.uploadAssetAtComponentHref(_,e.type,e._owner.compositeHref,t,i,n,c,l)}_blockUploadComponent(e,t,i,n,o,a){const l=new c,h=s.getUrlFromLinks(e._owner.compositeLinks,r.BLOCK_INITIALIZE),d=JSON.stringify({component_id:e.id,"repo:size":o.size,"repo:blocksize":6e6,"repo:reltype":r.COMPONENT,"repo:if-match":t?null:"*","dc:format":e.type});return this._postRequest(h,{"Content-Type":"application/vnd.adobecloud.bulk-transfer+json"},d,l).then(t=>{const{result:i}=this._processJsonResponse(t),n=i["repo:blocksize"],a=i._links[r.BLOCK_TRANSFER],c=s.getUrlFromLinks(i._links,r.BLOCK_FINALIZE),h=[];for(let t=0,i=0;i<o.size;t++,i+=n){const r=a[t].href,s=Math.min(o.size,i+n)-1;h.push(this._uploadBlock(r,o.filename,e.type,i,s,l))}return Promise.all(h).then(()=>this._postRequest(c,{"Content-Type":"application/vnd.adobecloud.bulk-transfer+json"},JSON.stringify(i),l))}).then(()=>this._doHeadRequest(s.getUrlFromLinks(e._owner.compositeLinks,r.COMPONENT,{component_id:e.id,revision:e.version}))).then(e=>a(null,e,{}),a),l}_uploadBlock(e,t,i,n,o,r){const s={Authorization:null,"X-Request-Id":null,"Content-Length":o-n+1,"Content-Type":i},c=new a(t,void 0,{start:n,end:o});return new Promise((t,i)=>{const n={method:"PUT",href:e,headers:s,callback:(n,o)=>{n?i(n):[200,201,204].includes(o.statusCode)?t():i(h(`Unexpected status code from: ${e}`,void 0,o))},body:c,options:{responseType:"json"}};this._service._doRequest(n),r&&r.push(n,!0)})}copyAssetToComponentId(e,t,i,n,o,r,s,a){this._invokeOperation("copy",{href:s,"if-match":"*"},{href:`${i}?component_id=${e}`,"if-match":"*"},a)}updateManifest(e,t,i,n){const o=s.getUrlFromLinks(e.compositeLinks,r.MANIFEST);return this.updateManifestAtHref(o,t,e.manifestEtag,i,n)}updateManifestAtHref(e,t,i,n,r){const s={"Content-Type":"application/vnd.adobe.dcx-manifest+json"};return n?s["If-Match"]="*":i&&(s["If-Match"]=i),this._service.invoke("PUT",e,s,t,void 0,(function(e,t){if(e)return r(l("Error updating manifest",e,t));const s=t.statusCode;!t.headers.etag||200!==s&&201!==s&&204!==s?412===s||i&&!n&&409===s?((e=new o(o.UPDATE_CONFLICT,"Manifest has been changed")).response=t,r(e)):r(h("Unexpected response updating manifest",e,t)):r(void 0,t)}))}getHrefForComposite(e){return e.href}getCompositeManifestHref(e){return s.getUrlFromLinks(e.links,r.MANIFEST)}getBranchManifestHref(e){return s.getUrlFromLinks(e.compositeLinks,r.MANIFEST)}getComponentHref(e,t){const i=e._owner;if(!i||!i.compositeLinks)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");return s.getUrlFromLinks(i.compositeLinks,r.COMPONENT,{revision:t,component_id:e.id})}getComponentRenditionHref(e,t,i){return this._getLinks(this.getComponentHref(e,t)).then(e=>s.getUrlFromLinks(e,r.RENDITION,{size:i}))}_invokeOperation(e,t,i,n){const a=s.getUrlFromLinks(this._rootLinks,r.OPS),c={op:e,target:i,source:t};s.log(`[invoke operation]: ${JSON.stringify(c,void 0,2)}`);const d=(e,t)=>{let i;if(e){if(!(t=e.response))return n(e);507===t.statusCode?((e=new o(o.EXCEEDS_QUOTA,"Exceeds quota",e)).response=t,n(e)):n(e)}else{try{i=JSON.parse(t.responseText||t.response)}catch(i){return(e=new o(o.INVALID_DATA,"Invalid JSON returned by server",i)).response=t,n(e)}if(i.error)return(e=new o(o.UNEXPECTED_RESPONSE,"Error in operation result: "+JSON.stringify(i.error,void 0,2))).response=t,n(e);n(void 0,t,i&&i.asset)}},_=this._service.invoke("POST",a,{"Content-Type":"application/json"},JSON.stringify([c]),{responseType:"text"},(t,i)=>{if(t)return d(l("Error invoking operation "+e,t,i));const n=i.statusCode;200===n||201===n||204===n?d(void 0,i):202===n?this._handle202Response(i,_,this.SYNC_ASYNC_DEFAULT_DELAY,e=>e,(function(e,t){d(e,t)})):d(h("Unexpected response for operation "+e,t,i),i)});return _}_getLinks(e){return this._doHeadRequest(e).then(e=>this._getLinksFromResponse(e))}_getLinksFromResponse(e){const t=e&&e.headers.link;if(!t)throw new o(o.UNEXPECTED_RESPONSE,"HEAD request did not return link header");const i=d.parse(t);return i&&i.refs.reduce((e,{rel:t,uri:i,...n})=>(t&&(e[t]=e[t]||[],e[t].push({href:i,...n})),e),{})}_getAllPages(e,t){let i;return this._getPagedResponse(e,t).then((function e(t){if(t&&t.result&&t.result.children)return i?i.result.children=i.result.children.concat(t.result.children):i=t,t&&t.next?t.next().then(e):void 0})).then(()=>i)}_getPagedResponse(e,t={}){return this._getResponse(e,t).then(({result:e,etag:t,headers:i})=>{let n;if(e&&e._page&&e._page.next&&e._links&&e._links[r.PAGE]){const t=new _(e._links[r.PAGE].href);n=()=>this._getPagedResponse(t.fill({...e._page,start:e._page.next,resource:r.PRIMARY}))}return{result:e,etag:t,headers:i,next:n}})}_processJsonResponse(e){let t;try{const i=e.responseText||e.response;t=JSON.parse(i)}catch(t){const i=new o(o.INVALID_DATA,"Invalid JSON returned by server",t);throw i.response=e,i}return{result:t,etag:e.headers.etag,headers:e.headers,response:e}}_getResponse(e,t){return new Promise((i,n)=>{this._service.invoke("GET",e,t,void 0,{responseType:"text"},(t,o)=>{if(t)return n(l(`Error reading from: ${e}`,t,o));200===o.statusCode?i(this._processJsonResponse(o)):304===o.statusCode?i({etag:o.headers.etag,headers:o.headers}):n(h(`Unexpected status code from: ${e}`,void 0,o))})})}_postRequest(e,t,i,n){return new Promise((o,r)=>{const s=(t,i)=>r(l(`Error reading from: ${e}`,t,i)),a=this._service.invoke("POST",e,t,i,{responseType:"text"},(t,i)=>{if(t)return s(t,i);200===i.statusCode||201===i.statusCode||204===i.statusCode?o(i):202===i.statusCode?this._handle202Response(i,a,this.SYNC_ASYNC_DEFAULT_DELAY,void 0,(e,t)=>{e?s(e,t):o(t)}):r(h(`Unexpected status code from: ${e}`,void 0,i))});n&&n.push(a)})}_createComposite(e,t=0){return new Promise((i,n)=>{const o={"Content-Type":e.type},r=new _(e.href),s=this._getCompositeRepoName(e,t),a=r.fill({path:s});this._service.invoke("POST",a,o,void 0,void 0,(o,r)=>o||![200,201,204,409].includes(r.statusCode)?n(l("Error creating composite directory",o,r)):409===r.statusCode?i(this._createComposite(e,t+1)):i({href:a,response:r}))})}_findAvailablePath(e,t,i,n=0){return new Promise((o,a)=>{const c=`${t}/${this._getCompositeRepoName(e,n)}`,h=s.getUrlFromLinks(this._rootLinks,r.RESOLVE_PATH,{path:c,repositoryId:i});this.headRequest(h,(r,s)=>r?a(r):404===s.statusCode?o(c):200===s.statusCode||403===s.statusCode?o(this._findAvailablePath(e,t,i,n+1)):a(l("Unexpected status code",r)))})}_getCompositeRepoName(e,t=0){let i=e.name;return g.test(i)&&(i=`${i} `),`${i}${t?` ${t}`:""}${s.getExtension(e.type)}`.replace(m,"_")}_doesRepoNameMatchPath(e){return new RegExp(`/${this._encodeURIComponent(e.name)}(%20[0-9]+)?${s.getExtension(e.type).replace(".","\\.")}`).test(s.getUrlFromLinks(e.links,r.PATH))}_getStorageLinkTemplate(e){this._storageLinkCache=this._storageLinkCache||{},this._storageLinkCache[e]=this._storageLinkCache[e]||{};const t=this._storageLinkCache[e];if(Date.now()<t.expiresAt){const e=new _(t.template);if(e)return Promise.resolve(e)}return t.fetchingPromise||(t.fetchingPromise=this._doHeadRequest(e).then(t=>{const i=t&&t.headers&&t.headers["x-resource-urn"];return i?new Promise((t,n)=>this.getLinksFromUrn(i,(i,o)=>{if(i)return n(i);try{const i=s.getTemplateFromLinks(o,r.COMPONENT);this._storageLinkCache[e]={template:i,expiresAt:Date.now()+36e5},t(new _(i))}catch(i){n(i)}})):Promise.reject(new o(o.INVALID_DATA,`Request for composite did not return a URN: ${e}`))}),t.fetchingPromise.catch(()=>delete this._storageLinkCache[e].fetchingPromise)),t.fetchingPromise}_getCopyDelegate(e,t,i){super._getCopyDelegate(e,t,(n,r)=>{if(!n)return i(null,r);const[,s,a]=p.exec(e)||[];if(!s||!a)return i(new o(o.INVALID_PARAMS,`Href is not for a component: ${e}`));this._getStorageLinkTemplate(s).then(e=>{const n=e.fill({component_id:a});i(null,(e,i,o,r,s,a)=>this.copyAssetToComponentId(e,i,t,o,r,s,n,a))},i)})}_handle202Response(e,t,i,n,o){const r=e&&e.headers&&e.headers.location;if(!r)return o(h("202 response missing an href.",void 0,e));this._pollForAsyncResponse(this._resolveUrl(r),i,t,n,o)}_getUrlFromRootDocument(e){try{const t=this._rootDocument.children.find(t=>t["repo:name"]===e);return new _(t._links[r.PRIMARY].href).fill({})}catch(t){throw new o(o.INVALID_DATA,`${e} does not exist in document root`,t)}}_encodeURIComponent(e){return encodeURIComponent(e).replace(/!/g,"%21")}}},function(e,t,i){var n=i(26),o=i(36),r=i(27),s=i(2),a=i(45),c=i(4),l=i(11);const h=i(28);var d,_,p=o.STATES;function u(e,t,i){return s.wrapError(s.UNEXPECTED_RESPONSE,e,t,i)}function m(e,t,i){this._session=e,this._callback=t,this._cleanup=i,this._componentsPending=0,this.bytesTransfered=0,this.bytesTotal=0,this.onProgress=c.noOp;var n=this;this._reportProgress=function(e){if(e>0){n.bytesTransfered+=e;var t=n.onProgress;t&&t(n.bytesTransfered,n.bytesTotal)}}}m.prototype._callCallback=function(e,t){var i=this._callback;i&&(this._callback=void 0,i(e,t))},m.prototype._xferComplete=function(e,t){var i=this._cleanup;i?(this._cleanup=void 0,i(e,t)):this._callCallback(e,t)},m.prototype.abort=function(e){this._aborted||(this._aborted=!0,e||(this._callback=void 0,e=new Error("Aborted")),this._xferComplete(e),this._session._service.abortAllWithToken(this))};var g={};function f(e,t={}){return{etag:t["repo:etag"]||e.headers.etag,version:t["repo:version"]||e.headers["x-latest-version"]||e.headers.version||e.headers.revision,md5:t.md5||e.headers["content-md5"],length:t["repo:size"]||t.size||parseInt(e.headers["content-length"])}}g.pullComposite=function(e,t,i){if(!e.hasLocalStorage)throw new s(s.INVALID_PARAMS,"No local storage. Use AdobeDCXCompositeXfer.pullCompositeManifestOnly() to pull down the composite without local storage.");return this._pullComposite(e,t,"all",i)},g.pullMinimumComposite=function(e,t,i){if(!e.hasLocalStorage)throw new s(s.INVALID_PARAMS,"No local storage. Use AdobeDCXCompositeXfer.pullCompositeManifestOnly() to pull down the composite without local storage.");return this._pullComposite(e,t,"min",i)},g.pullCompositeManifestOnly=function(e,t,i){return this._pullComposite(e,t,"none",i)},g.downloadComponents=function(e,t,i,n){var o=function e(t){return t._owner?e(t._owner):t}(t),r=new m(i,n);r._referenceBranch=o;const s=()=>g._pullComponents(r,o,e||t.allComponents());return o.hasLocalStorage?o._localStorage.loadPullJournal().then(e=>{r._journal=e,s()}):s(),r},g.pushComposite=function(e,t,i,n){var o,r=e._localStorage;(o=new m(i,n,(function(t,i){if(o._owner&&e.hasLocalStorage&&r.unregisterInMemoryBranchOrElement(o._owner),!e.hasLocalStorage){var n=o._journal;e._pushJournal=n.isEmpty?void 0:n}o._callCallback(t,i)})))._composite=e,o._overwriteExisting=t;var c=!e.isBound;if(o._compositeIsNew=c,e.hasLocalStorage)e._loadBranch(r.currentManifestPath(),!1,(function(t,i){if(t)return o._xferComplete(t);o._owner=i,e._localStorage.registerInMemoryBranchOrElement(i),a.readJournal(r.pushJournalPath(),e,!0,(function(t,i){if(t)return o._xferComplete(t);o._journal=i,g._pushComposite(e,o)}))}));else{if(!e.href)return o._xferComplete(new s(s.INVALID_STATE,"New composite has no href"));o._owner=e.current.copy(),o._journal=e._pushJournal||new a(e),g._pushComposite(e,o)}return o},g.uploadNewComponent=function(e,t,i,o,r,a){if(i._localStorage)throw new s(s.INVALID_PARAMS,"For in-browser use only. Use composite.current.addComponent() to add a new component asset");return d(o||c.generateUuid(),t,!0,i.collaborationType===n.COLLABORATION.SHARED_WITH_USER,e,i.id,i.href,r,a)},g.uploadComponent=function(e,t,i,o,r){if(i._localStorage)throw new s(s.INVALID_PARAMS,"For in-browser use only. Use composite.current.updateComponent() to update a component asset");return d(e.id,e.type,!1,i.collaborationType===n.COLLABORATION.SHARED_WITH_USER,t,i.id,i.href,o,r)},g.copyAssetForNewComponent=function(e,t,i,o,r,a){if(i._localStorage)throw new s(s.INVALID_PARAMS,"For in-browser use only. Use composite.current.addComponent() to add a new component asset");return _(o||c.generateUuid(),t,!0,i.collaborationType===n.COLLABORATION.SHARED_WITH_USER,e,i.id,i.href,r,a)},g.getURLForComponent=function(e,t){if(e._owner._localStorage)throw new s(s.INVALID_PARAMS,"For in-browser use only.");return t.getComponentHref(e,e.version)},g._pullComposite=function(e,t,i,n){if("string"!=typeof e.href)throw new s(s.INVALID_STATE,"Composite must have an href");var o;var a=function(n,a){if(n)return o._xferComplete(n);var c;a?(c=a.manifestEtag,o._referenceBranch=a):e.current&&(c=e.current.manifestEtag,o._referenceBranch=e.current);var l=t.getCompositeManifest(e,c,(function(t,n,c){if(t)return t.response&&404===t.response.statusCode?o._xferComplete(new s(s.NO_COMPOSITE,"Composite missing or deleted",t.underlyingError||t)):o._xferComplete(t);if(null===n&&!a)return o._xferComplete(void 0,null);var l;if(null!==n)try{if((l=(new r).parse(n))._localStorage=e._localStorage,l.compositeHref=e.href,l.compositeLinks=e.links,l.compositeAssetId=e.assetId,l._collaborationType=e.collaborationType,l._clientDataString=e.clientDataString,l.manifestEtag=c,l.compositeState===p.committedDelete||l.compositeState===p.pendingDelete)return void o._session.deleteCompositeDirectory(e,(function(e){return e?o._xferComplete(new s(s.DELETED_COMPOSITE,"Error deleting composite directory",e)):o._xferComplete(new s(s.DELETED_COMPOSITE,"Composite is deleted"))}));o._referenceBranch&&l.hasLocalStorage&&l._updateLocalDataFromBranch(o._referenceBranch)}catch(e){return o._xferComplete(new s(s.INVALID_JSON,"Corrupted manifest",e))}else l=a;var h,d,_=l.allComponents();for(h=0;h<_.length;++h)(d=_[h]).state===p.pendingDelete||d.state===p.committedDelete?l.removeComponent(d):d.state=p.unmodified;_=void 0,"all"===i?_=l.allComponents():"min"===i&&(d=l.getComponentWithAbsolutePath("/META-INF/metadata.xml"))&&(_=[d]),_?g._pullComponents(o,l,_):o._xferComplete(void 0,l)}));l&&(l.token=o,l.progress=o._reportProgress)};return(o=new m(t,n,(function(t,i){if(t){var n=t.pulledBranch;n?(n.compositeState=p.unmodified,n.hasLocalStorage?l.writeFileAtomically(e._localStorage.pulledManifestPath(),t.pulledBranch.localData,"utf8",(function(){o._callCallback(t)})):o._callCallback(t)):o._callCallback(t)}else{if(null===i)return o._callCallback(void 0,null);if(i.compositeState=p.unmodified,i.readOnly=!0,i.hasLocalStorage){var r=e._localStorage.pulledManifestPath();l.writeFileAtomically(r,i.localData,"utf8",(function(e){if(e)return o._callCallback(e);i.manifestPath=r,i._isDirty=!1,o._callCallback(void 0,i)}))}else e._options.xhrBaseBranchSupport&&(e._pulledBranchData=i.localData),o._callCallback(void 0,i)}})))._composite=e,e.hasLocalStorage?e._localStorage.loadPullJournal().then(t=>{o._journal=t,e.loadPulledBranch(a)}):a(),o},g._pullComponents=function(e,t,i){if(!t.hasLocalStorage)throw new s(s.INVALID_PARAMS,"No local storage.");var n,o=e._session;function r(n,o){if(e._componentsPending-=1,n?(e.failedComponents=e.failedComponents||[],e.failedComponents.push({component:o,error:n})):e._journal&&e._journal.saveComponentPath(o),0===e._componentsPending&&!e._aborted){var r=e.failedComponents;if(r){n=new s(s.COMPONENT_DOWNLOAD_ERROR,"Failed to download all components");var a,c=r.length;for(a=0;a<c;a++){var h=r[a].error;if(h.code===s.OUT_OF_SPACE){n=new s(h.code,h.message);break}}n.pulledBranch=t,n.failedComponents=r}t.readOnly&&t.manifestPath&&(!r||i.length>r.length)?l.writeFileAtomically(t.manifestPath,t.localData,"utf8",(function(i){n=n||i,e._xferComplete(n,n?void 0:t)})):e._xferComplete(n,n?void 0:t)}}function a(t){if(e._aborted)return;const i=e._journal;if(i&&i.restoreComponentPath(t))r(null,t);else{e.bytesTotal+=t.length||0;var n=t._owner._localStorage.tempPathForComponent(t),s=c.parentDirectory(n);l.ensureDirectoryExists(s,(function(i){if(i)return e.abort(i);var s=g._pullComponent(t,n,o,r);s.progress=e._reportProgress,s.token=e}))}}function h(e){t.assetOfComponent(e,(function(t,i){"string"!=typeof i?a(e):r(void 0,e)}))}for(e._componentsPending=i.length,n=0;n<i.length;++n){var d,_=i[n];if(e._referenceBranch){var p=e._referenceBranch.getComponentWithId(_.id);p&&(d=p.etag)}_.etag!==d?a(_):h(_)}0===e._componentsPending&&e._xferComplete(void 0,t)},g._pullComponent=function(e,t,i,n){var o=e._owner;if(!e._owner.hasLocalStorage)throw new s(s.INVALID_PARAMS,"No local storage. Use AdobeDCXCompositeXfer.pullCompositeManifestOnly() to pull down the composite without local storage.");return i.getComponent(e,new h(t),(function(i,r){if(i)n(i,e);else if(200===r.statusCode){var a=Number(r.headers["content-length"]);e.length&&!isNaN(a)&&a!==e.length?n(new s(s.UNEXPECTED_RESPONSE,"Incorrect content length",i,r)):o._localStorage.ingestComponentAsset(e,t,!1,o._local(),(function(t){n(t,e,r.headers.etag)}))}else 304===r.statusCode?n(void 0,e,r.headers.etag):n(u("Unexpected response getting a component",i,r),e)}))},g._pushComposite=function(e,t){if(!e.href)return t._xferComplete(new s(s.INVALID_STATE,"New composite has no href"));var i=t._owner,o=t._journal,r=t._compositeIsNew,a=t._overwriteExisting,c=t._session,h=i.changeCount,d=i.remoteData.length+50;if(t.bytesTotal=d,i.compositeState===p.committedDelete)return t._xferComplete(new s(s.DELETED_COMPOSITE,"Attempt to push a deleted composite"));if("archived"===i.compositeArchivalState)return t._xferComplete(new s(s.DELETED_COMPOSITE,"Attempt to push an archived composite"));var _="pending"===i.compositeArchivalState;if(_&&e.collaborationType===n.COLLABORATION.SHARED_WITH_USER)return t._xferComplete(new s(s.INVALID_STATE,"Attempt to archive composite that is shared with this user."));if(!r&&!_&&i.compositeState===p.unmodified)return t._xferComplete();if(i.compositeState===p.pendingDiscard)return r&&!a?t._xferComplete(new s(s.DELETED_COMPOSITE,"Attempt to delete unbound composite")):c.discardComposite(e,(function(e){t._xferComplete(e)}));if(i.compositeState===p.pendingDelete)return r&&!a?t._xferComplete(new s(s.DELETED_COMPOSITE,"Attempt to delete unbound composite")):e.collaborationType===n.COLLABORATION.SHARED_WITH_USER?t._xferComplete(new s(s.INVALID_STATE,"Attempt to delete composite that is shared with this user.")):g._deleteComposite(t,a,(function(e,i){t._xferComplete(e,i)}));function m(i,n){_?c.archiveCompositeDirectory(e,(function(o){if(o)return n(o);i.compositeArchivalState="archived",t._journal.compositeHasBeenArchived=!0,t._journal.commitChanges((function(t){if(t)return n(t);e.hasLocalStorage?l.writeFileAtomically(e._localStorage.pushedManifestPath(),i.localData,"utf8",(function(e){if(e)return n(e);n(void 0,i)})):n(void 0,i)}))})):n(void 0,i)}function f(i){if(r)return t._xferComplete(i);var n=c.getCompositeManifestHref(e);c.headRequest(n,(function(e,n){return e?t._xferComplete(e):404===n.statusCode?(i=new s(s.NO_COMPOSITE,"Composite does not exist; may have been deleted"),t._xferComplete(i)):t._xferComplete(i)}))}!function(e,t,i){if(e.isBound&&t.renameCompositeIfNecessary)return t.renameCompositeIfNecessary(e,i);i()}(e,c,n=>{if(n)return t._xferComplete(n);!function(e,t,i,n,o){function r(e){e||(t.compositeHasBeenCreated=!0);var i,n=t._compositeCreationCallbacks,o=n.length;for(i=0;i<o;i++)try{n[i](e)}catch(e){}t._compositeCreationCallbacks=void 0}e.isBound||t.compositeHasBeenCreated?o():t._compositeCreationCallbacks?t._compositeCreationCallbacks.push(o):(t._compositeCreationCallbacks=[o],n.createCompositeDirectory(e,i,(function(t,o){if(t){if(t.code!==s.ALREADY_EXISTS)return r(u("Unexpected response creating a composite directory",t,o));if(i)r();else{var a=n.getCompositeManifestHref(e);n.headRequest(a,(function(e,t){return e?r(e):404!==t.statusCode?r(e=new s(s.ALREADY_EXISTS,"Composite already exists and overwriteExisting not specified")):void r()}))}}else r()})))}(e,o,a,c,n=>{if(n)return t._xferComplete(n);this._applyCompositeChangesToBranchAndJournal(e,i,o,n=>{if(n)return t._xferComplete(n);g._pushComponents(t,i,(function(){var r=t.failedComponents;if(r){n=new s(s.COMPONENT_UPLOAD_ERROR,"One or more components failed to upload.");var _,u=r.length;for(_=0;_<u;_++){var g=r[_].error;if(g.code===s.EXCEEDS_QUOTA){n=new s(g.code,g.message);break}}return n.failedComponents=r,f(n)}if(i.compositeState===p.modified){i.compositeState=p.unmodified,o.manifestEtag&&o.currentBranchEtag===i.manifestEtag&&(i.manifestEtag=o.manifestEtag);var E=i.remoteData;t.bytesTotal+=E.length,t.bytesTotal-=d;var y=c.updateManifest(i,E,a,(function(n,r){if(n)return f(n);var s=r.headers.etag;o.manifestEtag=s,o.currentBranchEtag=i.manifestEtag,o.changeCount=h,o.commitChanges((function(n){if(n)return t._xferComplete(n);o.applyToBranch(i),i.compositeState=p.unmodified,e.hasLocalStorage?l.writeFileAtomically(e._localStorage.pushedManifestPath(),i.localData,"utf8",(function(e){if(e)return t._xferComplete(e);i._isDirty=!1,m(i,(function(e,i){t._xferComplete(e,i)}))})):(e._options.xhrBaseBranchSupport&&(e._pushedBranchData=i.localData),m(i,(function(e,i){t._xferComplete(e,i)})))}))}));y&&(y.progress=t._reportProgress,y.token=t)}else m(i,(function(e,i){t._xferComplete(e,i)}))}))})})})},g._applyCompositeChangesToBranchAndJournal=function(e,t,i,n){e.links&&(t.compositeLinks=e.links,i.compositeLinks=e.links),e.assetId&&(t.compositeAssetId=e.assetId,i.compositeAssetId=e.assetId),e.href!==t.compositeHref&&(t.compositeHref=e.href,i.compositeHref=e.href),i.commitChanges(n)},g._deleteComposite=function(e,t,i){var n=e._composite,o=e._owner,r=e._session;o.compositeState=p.committedDelete;var s=o.remoteData;e.bytesTotal=s.length,e._journal.manifestEtag&&e._journal.currentBranchEtag===o.manifestEtag&&(o.manifestEtag=e._journal.manifestEtag),r.updateManifest(o,s,t,(function(t){if(t)return i(t);r.deleteCompositeDirectory(n,(function(t){if(t)return i(t);e._journal.compositeHasBeenDeleted=!0,e._journal.commitChanges((function(e){if(e)return i(e);n.hasLocalStorage?l.writeFileAtomically(n._localStorage.pushedManifestPath(),o.localData,"utf8",(function(e){if(e)return i(e);i(void 0,o)})):i(void 0,o)}))}))}))},g._pushComponents=function(e,t,i){var o,r=t.allComponents(),a=e._composite,d=a._localStorage,_={},u=e._journal;function m(t,n,o){n?_[t.id]=n:delete _[t.id],o&&(e.failedComponents=e.failedComponents||[],e.failedComponents.push({component:t,error:o})),0===Object.keys(_).length&&u.commitChanges(i)}function g(t,i,o){m(t,"uploading"),l.info(i,(function(r,l){if(r)return r=new s(s.INVALID_STATE,"Component asset missing",r),void m(t,null,r);var d=l.size,_=c.filePathComponents(i).fileName,g=u.getRecordForUploadedComponent(t.id);if(g&&g.length===d&&g["storage-name"]===_)return t.etag=g.etag,t.version=g.version,t.md5=g.md5,t.length=g.length,t.state=p.unmodified,void m(t,null);e.bytesTotal+=d;var E=e._session.uploadComponent(t,o,a.collaborationType===n.COLLABORATION.SHARED_WITH_USER,e,new h(i,d),(function(e,i,n){if(!e){const{etag:o,version:r,md5:a}=f(i,n);o||(e=new s(s.UNEXPECTED_RESPONSE,"No etag")),r||(e=new s(s.UNEXPECTED_RESPONSE,"No version")),a||(e=new s(s.UNEXPECTED_RESPONSE,"No md5")),e||(t.etag=o,t.version=r,t.md5=a,t.length=d,t.state=p.unmodified,u.recordUploadedComponent(t.id,o,r,a,d,_),u.commitChanges())}m(t,null,e)}));E&&(E.progress=e._reportProgress,E.token=e)}))}function E(i,o,r){function c(){if(d){var e=d.componentAssetPath(i,t._local());if("string"==typeof e)return g(i,e,r)}}var l=u.getRecordForUploadedComponent(i.id);if(l&&l["source-href"]===o)return i.etag=l.etag,i.version=l.version,i.md5=l.md5,i.length=l.length,void(i.state=p.unmodified);m(i,"copying"),e._session._getCopyDelegate(o,e._composite.href,(t,l)=>{if(t)return c();var h=l(i.id,i.type,r,a.collaborationType===n.COLLABORATION.SHARED_WITH_USER,e,(function(e,t,n){if(e)return c();{const{etag:r,version:a,md5:c,length:l}=f(t,n);r||(e=new s(s.UNEXPECTED_RESPONSE,"No etag")),a||(e=new s(s.UNEXPECTED_RESPONSE,"No version")),c||(e=new s(s.UNEXPECTED_RESPONSE,"No md5")),l||(e=new s(s.UNEXPECTED_RESPONSE,"No length")),e||(i.etag=r,i.version=a,i.md5=c,i.length=l,i.state=p.unmodified,u.recordUploadedComponent(i.id,r,a,c,l,void 0,o),u.commitChanges())}m(i,null,e)}));h&&(h.progress=e._reportProgress,h.token=e)})}for(o=0;o<r.length;++o){var y=r[o],v=y.state,A=!y.etag;if(v||(v=p.unmodified),A||v===p.modified){var C=t._core._getSourceHrefOfComponent(y);if(t.hasLocalStorage||C){var I=A||e._compositeIsNew;if(C)E(y,C,I);else{var S=d.componentAssetPath(y,t._local());"string"==typeof S&&g(y,S,I)}}else{var L=new s(s.INVALID_STATE,"Component should not be modified or new without local storage");e.failedComponents=e.failedComponents||[],e.failedComponents.push({component:y,error:L})}}else v===p.unmodified?u.removeRecordForUploadedComponent(y.id):v!==p.committedDelete&&v!==p.pendingDelete||t.removeComponent(y)}0===Object.keys(_).length&&i()},d=function(e,t,i,n,r,a,c,l,h){if("function"!=typeof h)throw new s(s.INVALID_PARAMS,'Param "callback" must be a function.');var d=r.length||r.byteLength||r.size,_=new m(l,h);_.bytesTotal=d;var p=l.uploadAssetForComponentId(e,t,c,i,n,_,r,(function(i,n,r){var c;if(!i)try{c=new o._UploadResults(a),d=d||p.bytesSent,c.records[e]=function(e,t,i,n,r){if("number"!=typeof t)throw new s(s.UNEXPECTED_RESPONSE,"No length");const{etag:a,version:c,md5:l}=f(n,r);if(!a)throw new s(s.UNEXPECTED_RESPONSE,"No etag");if(!c)throw new s(s.UNEXPECTED_RESPONSE,"No version");if(!l)throw new s(s.UNEXPECTED_RESPONSE,"No md5");return new o._UploadRecord(e,a,c,l,t,i)}(e,d,t,n,r)}catch(e){i=e,c=void 0}_._xferComplete(i,c)}));return p&&(p.progress=_._reportProgress,p.token=_),_},_=function(e,t,i,n,r,a,c,l,h){if("function"!=typeof h)throw new s(s.INVALID_PARAMS,'Param "callback" must be a function.');var d=new m(l,h),_=l.copyAssetToComponentId(e,t,c,i,n,d,r,(function(i,n,r){if(!d._aborted){var c;if(!i)try{(c=new o._UploadResults(a)).records[e]=function(e,t,i,n){const{etag:r,version:a,md5:c,length:l}=f(n,t);if("number"!=typeof l)throw new s(s.UNEXPECTED_RESPONSE,"No length");if(!r)throw new s(s.UNEXPECTED_RESPONSE,"No etag");if(!a)throw new s(s.UNEXPECTED_RESPONSE,"No version");if(!c)throw new s(s.UNEXPECTED_RESPONSE,"No md5");return new o._UploadRecord(e,r,a,c,l,i)}(e,r,t,n)}catch(e){i=e,c=void 0}h(i,c)}}));return _&&(_.progress=d._reportProgress,_.token=d),d},e.exports=g},function(e,t,i){var n=i(26),o=i(27),r=i(2),s=i(4),a=i(11);let c,l;c=i(52),l=i(53);var h={isSnapshot:function(e,t){var i,n=!1,o=function(e,o){n||(n=!0,i&&i.isOpen&&i.close(),t(e,o))};l.open(e,{lazyEntries:!0},(function(e,t){e?-1!==["EPERM","EACCES","ENOENT"].indexOf(e.code)?o(e):o(new r(r.INVALID_DATA,"Error while opening snapshot: "+e)):((i=t).on("entry",(function(e){"mimetype"===e.fileName?i.openReadStream(e,(function(e,t){if(e)o(e);else{var i=[];t.on("data",(function(e){i.push(e)})),t.on("error",(function(e){o(e)})),t.on("end",(function(){var e=Buffer.concat(i).toString();e&&p(e,"dcxucf")?o(null,!0):o(null,!1)}))}})):o(null,!1)})).on("error",(function(e){o(e)})),i.readEntry())}))},importSnapshot:function(e,t,i,o,r,s){return this.importSnapshotToDirectory(e,t,i,o,r,(function(e,t){if(e)s(e);else try{var i=new n(null,null,t,null,null,null);i.loadCurrentFromLocalStorage((function(e){s(e,e?void 0:i)})),i.deleteTempFiles()}catch(e){s(e)}}))}};h.importSnapshotToDirectory=function(e,t,i,n,c,h){var d,_,u,g,f=!1,E=0,y=0,v=0,A=!1,C=function(e,t){if(!A){if(A=!0,d&&d.isOpen&&d.close(),e)return t&&a.deleteDirectory(t),void h(e);h(e,t)}},I={},S={};return a.ensureDirectoryExists(t,(function(h){h?C(h):l.open(e,{lazyEntries:!0},(function(e,l){e?-1!==["EPERM","EACCES","ENOENT"].indexOf(e.code)?C(e):C(new r(r.INVALID_DATA,"Error while opening snapshot: "+e)):((d=l).on("entry",(function(e){if(E++,y=0,v=0,m(e,n))if(1===E)"mimetype"===e.fileName?d.openReadStream(e,(function(e,t){if(e)C(e);else{var i=[];t.on("data",(function(e){i.push(e)})),t.on("error",(function(e){C(e)})),t.on("end",(function(){var e=Buffer.concat(i).toString();e&&p(e,"dcxucf")||C(new r(r.INVALID_DATA,"Bad mimetype")),d.readEntry()}))}})):C(new r(r.INVALID_DATA,"Missing mimetype file"));else if(2===E)"manifest"===e.fileName?d.openReadStream(e,(function(e,t){if(e)C(e);else{var i=[];t.on("data",(function(e){i.push(e)})),t.on("error",(function(e){C(e)})),t.on("end",(function(){var e=Buffer.concat(i).toString();if(e){if(_=JSON.parse(e),(u=new o(_))._resetIdentity(),n){var t=u.getComponentWithAbsolutePath("/META-INF/metadata.xml");t&&u.removeComponent(t)}g=_.id,d.readEntry()}else C(new r(r.INVALID_DATA,"Unable to parse manifest on import"))}))}})):C(new r(r.INVALID_DATA,"Missing manifest file"));else if(g){y=e.uncompressedSize;var i=t+"/"+g+"/components";a.ensureDirectoryExists(i,(function(t){t?C(t):d.openReadStream(e,(function(t,n){if(t)C(t);else{var o=s.generateUuid(),r=e.fileName.split("/"),l=r[r.length-1].split(".");l&&(o=o+"."+l[l.length-1]),I["/"+e.fileName]=o,n.on("end",(function(){d.readEntry()})),n.on("data",(function(e){v+=e.length,function(){if(!f){var e=(E-1)/d.entryCount;y&&(e+=v/(y*d.entryCount)),c(Math.round(100*e))}}()})).on("error",(function(e){C(e)})).pipe(a.createWriteStream(i+"/"+o))}}))}))}else C(new r(r.INVALID_DATA,"Missing manifest id"));else d.readEntry()})).on("error",(function(e){C(e)})).on("close",(function(){A||(f?C(new r(r.UNEXPECTED,"Import cancelled")):(Object.keys(I).forEach((function(e){var t=u.getComponentWithAbsolutePath(e);t&&(S[t.id]=I[e])})),_.local||(_.local={}),_.local["copyOnWrite#storageIds"]=S,i&&(_.local.compositeHref=i(_.id)),g?a.ensureDirectoryExists(t+"/"+g,(function(e){e?C(e):a.writeFile(t+"/"+g+"/manifest",JSON.stringify(_,void 0,2),(function(e){e?C(e):C(null,t+"/"+g)}))})):C(new r(r.INVALID_DATA,"Missing manifest id"))))})),d.readEntry())}))})),function(){f||(f=!0,d&&d.close())}},h.exportSnapshot=function(e,t,i,n,o){var l,h,_=!1,u=function(e){if(!_){if(_=!0,e)return void a.deleteFile(h,()=>o(e));a.move(h,t,!1,e=>o(e||null))}};try{h=t.replace(/([^\\/]+)$/,"."+s.generateUuid()+"_$1"),l=a.createWriteStream(h)}catch(e){return void u(e)}var m,g=new c.ZipFile;if(e.type&&p(e.type,"dcx")){m=e.type+"ucf",g.addBuffer(Buffer.from(m),"mimetype",{compress:!1});var f=d(e.current,i),y=JSON.stringify(f.manifest,void 0,2),v=f.lengths.total+y.length;g.addBuffer(Buffer.from(y),"manifest",{compress:!0});var A=f.componentMap,C=f.components.map((function(t){return{id:t.id,path:A&&A[t.id]||t.path,type:t.type,absolutePath:e.current.getComponentWithId(t.id).absolutePath.substring(1)}})).sort((function(e,t){return e.absolutePath<t.absolutePath?-1:e.absolutePath>t.absolutePath?1:0})),I=!1,S=0;return C.forEach((function(t){var i=e.path+"/components/"+t.path;E(t.type)?g.addFile(i,t.absolutePath,{compress:!0}):g.addFile(i,t.absolutePath,{compress:!1})})),g.end(),g.on("error",(function(){u(new r(r.INVALID_DATA,"Missing component file locally."))})),g.outputStream.on("error",(function(e){u(I?new r(r.UNEXPECTED,"Export cancelled"):e)})).on("data",(function(e){S+=e.length,I||n(Math.min(100,Math.round(100*S/v)))})).pipe(l).on("close",(function(){u(I?new r(r.UNEXPECTED,"Export cancelled"):null)})).on("error",(function(e){u(e)})),function(){I||(I=!0,g.outputStream.end())}}u(new r(r.INVALID_PARAMS,"Invalid composite type"))};var d=function(e,t){var i=JSON.parse(e.localData);t&&t(i);var n=_(i,i.local["copyOnWrite#storageIds"]||{});return delete i.local,delete i.manifestEtag,i.state="unmodified",{manifest:i,lengths:n.lengths,componentMap:n.componentMap,components:n.components}},_=function(e,t,i,n,o){return o=o||[],i=i||{},n=n||{total:0},e.components&&e.components.forEach((function(e){i[e.id]=t[e.id];var r=e.length||1e5;n[e.id]=r,n.total+=r,e.state="unmodified",delete e.version,delete e.md5,delete e.etag,o.push(e)})),e.children&&e.children.forEach((function(e){_(e,t,i,n,o)})),{lengths:n,componentMap:i,components:o}},p=function(e,t){var i=e.split("/");if(2===i.length){var n=i[1];if(n.length<t.length+2)return!1;if(n.substring(n.length-t.length)!==t)return!1;var o=n.length-(t.length+1);return"+"===n.charAt(o)}return!1},u=/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\.[^/\\]+$/i,m=function(e,t){if("mimetype"===e.fileName||"manifest"===e.fileName)return!0;var i=e.fileName.split("/");if(i){var n=i[i.length-1];return!t&&"metadata.xml"===n||n.match(u)}return!1},g=["text/"],f=["+json","+xml"],E=function(e){return g.forEach((function(t){if(e.startsWith(t))return!0})),f.forEach((function(t){if(e.endsWith(t))return!0})),!1};e.exports=h},function(e,t){e.exports=require("yazl")},function(e,t){e.exports=require("yauzl")},function(e,t,i){const n=i(55),o=i(1),r=i(6);e.exports=class extends n{_dosync(e,t){this._clearSyncErrors(),this._syncManager.getServerComposites(this,(i,n,s)=>{if(i)return i=r.getSyncError(i,void 0,{403:o.ACCESS_DENIED}),this._reportSyncError(i),void t(null,!1);const a=[];if(a.push(this._syncNewLibraries(n)),a.push(this._syncExistingLibraries(s,e)),a.push(this._handlePendingDeletes()),!e){const e=this._bookmarkManager.sync().then(()=>!1);a.push(e)}Promise.all(a).then(e=>{this._handleExternalPendingDeletes(),t(null,e.some(e=>e))})})}_ensureDefaultLibrary(){const e="ok"===this.syncState&&!this.isInitialSyncInProgress&&this._config.SYNCING_ENABLED,t=this.libraries.some(e=>!e.isDeletedLocally&&!e.isDeletedFromServer);if(e&&!t){const e=this._localisation.translate("LIBS_DEFAULT_LIBRARY_NAME");this._services.log("Creating default library: "+e),this.createLibrary(e)}}_updateSyncState(){super._updateSyncState(),this._ensureDefaultLibrary()}get bookmarks(){return this._bookmarkManager.getBookmarks()}get fontManager(){return this._fontManager}createBookmark(e,t,i,n){const o=this._isBookmarkDataInvalid(e,i);if(o)return n(o);this._bookmarkManager.createBookmark(e,t,i,void 0,n)}_isBookmarkDataInvalid(e,t,i){let n=this._config.BOOKMARKS_TYPES[e];return n&&i&&!Array.isArray(n)&&(n=n[i.condition]||n.default),n?(Object.keys(t).length!==n.length||!n.every(e=>"string"==typeof t[e]))&&new o(o.INVALID_PARAMETER,`bookmarks of type ${e} must have the following data keys: ${n.join(", ")}`):new o(o.INVALID_PARAMETER,`unsupported bookmark type: ${e}`)}removeBookmark(e,t){this._bookmarkManager.removeBookmark(e,void 0,t)}findBookmark(e){return this._bookmarkManager.findBookmark(e)}syncBookmarks(e=(()=>{})){this._bookmarkManager.sync().then(()=>e())}addBookmarkChangeListener(e){this._bookmarkManager.addChangeListener(e)}removeBookmarkChangeListener(e){this._bookmarkManager.removeChangeListener(e)}getDefaultLibrary(){return this.libraries.reduce((e,t)=>{const i=!e||(e.created||0)>(t.created||0);return"incoming"!==t.collaboration&&i?t:e},void 0)}getToolkitLibrary(e){const t=this._libraries.filter(t=>t.toolkitId===e);if(!t.length){const t=this.createLibrary(this._localisation.getToolkitName(e));return t.setValue(this._config.TOOLKIT_NAMESPACE,this._config.TOOLKIT_ID_KEY,e),t}return t.sort((e,t)=>e.created-t.created),t[0]}}},function(e,t,i){const n=i(2),o=i(14),r=i(4),s=i(56),a=i(39),c=i(37),l=i(1),h=i(10),d=i(6),_=i(60);e.exports=class extends s{_syncNewLibraries(e){this._loadingHint&&(e=e.slice()).sort((e,t)=>Number(this._loadingHint.includes(t.name))-Number(this._loadingHint.includes(e.name)));const t=(e=e.filter(e=>!this._doesLibraryExist(e.name))).map(e=>new Promise(t=>{this._syncNewLibrary(e.name,void 0,e,(e,i)=>{e&&this._reportSyncError(e),t(i)})}));return Promise.all(t).then(e=>e.some(e=>e))}_syncExistingLibraries(e,t){const i=[];return this._libraries.forEach(n=>{const o=e&&e[n.id];if(o&&(n._setCollaboration(o),n._deletedFromServer&&(n._deletedFromServer=!1,n._notifyChange())),t)return void((t[n.id]||o&&!o.isUnmodified)&&i.push(e=>n._sync(!1,e)));const r=!e||o&&o.isUnmodified;void 0===n.collaboration?i.push(e=>n._sync(r,e)):r?i.push(e=>{this._syncManager.hasCompositeChangedOnServer(n._dcxComposite,t=>{n._sync(!t,e)})}):i.push(e=>n._sync(!1,e))}),Promise.all(i.map(e=>new Promise(t=>{e((e,i)=>{e&&this._reportSyncError(e),t(i)})}))).then(e=>e.some(e=>e))}_handlePendingDeletes(){const e=this._pendingDeletes.map(e=>new Promise(t=>{const i=e._dcxBranch.getLocalData("pendingOperation");let o;if(i&&"remove"===i.operation){const{condition:n}=i,r=this._apiRoot.getLoadedCollections().find(e=>e.cloudId===n.cloudId);if(o=r&&r.getLibraryById(n.libraryId),!o)return e._dcxBranch.setLocalData("pendingOperation"),e._dcxBranch.compositeState="modified",this._libraries.push(e),this._libraryIdMap[e.id]=e,this._removeFromPendingDeletes(e),this._notifyChange(!0),e._commit(!1,!0),void t(!0);if("on_pushed_new"!==n.condition||!o._dcxBranch.isBound)return t(!1)}this._removeFromPendingDeletes(e),this._activeDeletes.push(e),e._deleteFromServer(!1,r=>{const s=i=>(this._reportSyncError(i),this._removeFromActiveDeletes(e),this._pendingDeletes.push(e),t(!1)),a=i=>{if(i)return s(i);e._deletedFromDisk=!0,this._services.fileUtils.deleteLibraryFromDisk(this,e.id,i=>{i&&this._reportSyncError(i),this._removeFromActiveDeletes(e),t(!0)})};if(r&&r.code===n.UPDATE_CONFLICT)return i&&o?void e._pull(t=>{if(t)return s(t);h.recoverReadOnlyEdits(e,o._dcxBranch,t=>{if(t)return s(t);e._deleteFromServer(!0,a)})}):(this._libraries.push(e),this._libraryIdMap[e.id]=e,e._markDeletedLocally(!1),this._removeFromActiveDeletes(e),this._updateSyncState(),this._notifyChange(!0),void t(!0));a(r)})}));return Promise.all(e).then(e=>e.some(e=>e))}_handleExternalPendingDeletes(){return Promise.all(this._apiRoot.getLoadedCollections().map(e=>e!==this&&e._handlePendingDeletes?e._handlePendingDeletes():Promise.resolve(!1))).then(e=>e.some(e=>e))}_removeFromPendingDeletes(e){const t=this._pendingDeletes.indexOf(e);-1!==t&&this._pendingDeletes.splice(t,1)}_removeFromActiveDeletes(e){const t=this._activeDeletes.indexOf(e);-1!==t&&this._activeDeletes.splice(t,1)}_dosync(e,t){this._clearSyncErrors(),this._syncManager.getServerComposites(this,(i,n,o)=>{if(i)return i=d.getSyncError(i,void 0,{403:l.ACCESS_DENIED}),this._reportSyncError(i),void t(null,!1);const r=[];r.push(this._syncNewLibraries(n)),r.push(this._syncExistingLibraries(o,e)),r.push(this._handlePendingDeletes()),Promise.all(r).then(e=>{this._handleExternalPendingDeletes(),t(null,e.some(e=>e))})})}_doRemoveLibrary(e,t=(()=>{})){const i=this._libraries.indexOf(e);if(-1!==i&&(this._libraries.splice(i,1),delete this._libraryIdMap[e.id]),e._removeAllListeners(),this._config.SHARED_LOCAL_STORAGE)this._prepareCompositeForDelete(e._dcxComposite),e._commit(!1,!0),e._markDeletedLocally(!0),t(null);else{this._pendingDeletes.push(e),e._dcxComposite&&e._dcxComposite.getLocalData("pendingOperation")?(this._prepareCompositeForDelete(e._dcxComposite),e._commit(!0,!0),t(null)):this._config.SYNCING_ENABLED?e._deleteFromServer(!0,i=>{e._markDeletedLocally(!0),i?t(null):(this._removeFromPendingDeletes(e),e._deletedFromDisk=!0,this._services.fileUtils.deleteLibraryFromDisk(this,e.id,t))}):(this._prepareCompositeForDelete(e._dcxComposite),e._commit(!0,!0),e._markDeletedLocally(!0),t(null))}this._notifyChange(!0)}_doImportLibrary(e,t,i){if(this._config.SHARED_LOCAL_STORAGE){const i=this._services.uuid();return this._storageInterface.importLibrary(this,e,i,t),this._addOperation(i,"import")}let n;const o=this._addOperation(i||this._services.uuid(),"import",void 0,()=>n&&n());return n=_.importLibrary(this,e,e=>o._updateProgress(e),(e,i)=>{o._updateProgress(100),this._removeOperation(o),t(e,i)}),o}_pushNewLibrary(e){this._libraries.push(e),this._libraryIdMap[e.id]=e,this._notifyChange(!0),e._commit(!1,!0)}get isPublic(){return!1}createLibrary(e){const t=this._services.uuid(),i=this._config.COMPOSITE_TYPE,n=this._getCompositeDir(t),o=this._services.dcx.newEmptyComposite(e,i,n,t);o.current.rootNode.setValue(this._config.VERSION_KEY,this._config.VERSION),this._prepareCompositeForPush(o);const r=new c(this,o);return r._updateCreatedTime(),this._pushNewLibrary(r),this._analytics.reportCreateLibrary(r),r}removeLibrary(e,t){this._doRemoveLibrary(e,t),this._analytics.reportDeleteLibrary(e)}moveLibrary(e,t,i){e?this._libraries.includes(e)?t?this!==t?this.isTeam?i(new l(l.NOT_ALLOWED,"Source collection cannot be a team collection")):t.isWritable?t.isTeam?"incoming"!==e.collaboration?this._config.SHARED_LOCAL_STORAGE?this._storageInterface.moveLibrary(e,t,i):this._syncManager.removeCollaborators(e).then(()=>{this._services.dcx.copyCompositeAndAssetsFrom(e._dcxComposite,void 0,void 0,t._getCompositeDir()+"/"+e.id,e.id,r.getTemplateFromLinks(t.links,o.CREATE),(n,o)=>{if(n)return i(n);t._prepareCompositeForPush(o);const r=new c(t,o);e._dcxBranch.setLocalData("pendingOperation",{operation:"remove",condition:{condition:"on_pushed_new",cloudId:t.cloudId,libraryId:r.id}}),r._renditionCache.copyFullCache(e).then(()=>{this._doRemoveLibrary(e,()=>{t._pushNewLibrary(r),i(null,r)});const n=a.waitForPushNew(r.id);t._bookmarkManager.createBookmark("team",r.id,{team_urn:t.platformDirectoryId,org_id:t._team.orgId},n)})})},i):i(new l(l.NOT_ALLOWED,"moving can only be done to owned libraries")):i(new l(l.NOT_ALLOWED,"moving is currently only supported for team collections")):i(new l(l.NOT_ALLOWED,"you do not have write access to the destination collection")):i(new l(l.INVALID_PARAMETER,"Library is already in the target collection")):i(new l(l.INVALID_PARAMETER,"No destination collection specified")):i(new l(l.INVALID_PARAMETER,"Library not in this collection")):i(new l(l.INVALID_PARAMETER,"No library specified"))}importLibrary(e,t){if("string"==typeof e){if(this._config.SHARED_LOCAL_STORAGE||this._services.hasFileSystem())return this._doImportLibrary(e,(e,i)=>{this._analytics.reportImportLibrary(e,i),t(e,i)});t(new l(l.REQUIRES_FILESYSTEM,"importLibrary only supported when you have a filesystem"))}else t(new l(l.INVALID_PARAMETER,"path must be a string"))}}},function(e,t,i){const n=i(2),o=i(4),r=i(14),s=i(37),a=i(130),c=i(1),l=i(134),h=i(39),d=i(137),_=i(10),p=i(6),u=i(60),m=i(3),g=i(138),f=i(8).promisify;e.exports=class{constructor(e,t,i){this._apiRoot=e,this._userId=t.USER_ID,this._cloudId=t.CLOUD_ID,this._cloudInfo=t.CLOUD_INFO||{},this._bookmarkManager=i?i._bookmarkManager:new h(this),this._fontManager=i?i._fontManager:new d(this),this._syncManager=(i||this)._getSyncManager(t),this._libraries=[],this._syncState="syncing",this._syncProgressMap={},this._externalLinkDownloadProgressMap={},this._initialSyncInProgress=!1,this._syncErrors=[],this._listenerManager=new m(["change","deepchange","sync","operation","commitError"],e=>this._services.log(e)),this._operations=[],g.connect(this),this._libraryIdMap={},this._operationIdMap={},this._removeOperationTimeout={},this._pendingDeletes=[],this._activeDeletes=[],this._loaded=!1,this._syncing=!1,this._lastSyncTime=0,this._pendingSyncs=[],this._backoffTicks=0,this._numBackoffs=0,this._numRetries=0,this._recoveredLibraryCount=0,this._newLibrariesLoading={},this._partialSyncedNewLibraries={}}get _collectionManager(){return this._apiRoot._collectionManager}get _services(){return this._apiRoot._services}get _config(){return this._apiRoot._config}get _analytics(){return this._apiRoot._analytics}get _localisation(){return this._apiRoot._localisation}get _storageInterface(){return this._apiRoot._storageInterface}get _directoryName(){return this._cloudId}_dispose(){g.disconnect(this)}_getSyncManager(e){return this._syncManagers=this._syncManagers||{},this._syncManagers[e.STORAGE_HOSTNAME]||(this._syncManagers[e.STORAGE_HOSTNAME]=new a(this._apiRoot,e)),this._syncManagers[e.STORAGE_HOSTNAME]}_setRootDocument(e){Object.keys(this._syncManagers||{}).forEach(t=>{const i=this._syncManagers[t];i._isACP&&i._storageService.setRootDocument(e)})}get _href(){return this.isPrivate?o.appendPathElements(this._syncManager.getStorageHost(),this._config.STORAGE_ASSETS_PATH,this._config.LIBRARY_SYNC_GROUP):null}_getNewCompositeHref(e){return this.links?o.getTemplateFromLinks(this.links,r.CREATE):o.appendPathElements(this._href,e)}_prepareCompositeForPush(e){e.href=this._getNewCompositeHref(e.id)}_prepareCompositeForDelete(e){e._current.compositeState=this.links?"pendingDiscard":"pendingDelete"}_removeAllListeners(){this._listenerManager.removeAll(),this._libraries.forEach(e=>e._removeAllListeners())}_notifyChange(e){this._listenerManager.notify("deepchange"),e&&this._listenerManager.notify("change")}_cleanLocalData(){const e=this._apiRoot._getPrivateCollection(this.userId);if("ok"!==this.syncState||e&&"ok"!==e.syncState)return Promise.resolve();const t=Object.keys(this._partialSyncedNewLibraries);this._partialSyncedNewLibraries={};return t.length>0&&this._services.log(`Deleting local data for partial library sync: ${t.join(", ")}`),Promise.all(t.map(e=>new Promise(t=>{this._services.fileUtils.deleteLibraryFromDisk(this,e,()=>t())})))}_loadLibrary(e,t){const i=this._getCompositeDir(e),n=i=>{this._services.log(`Load error: ${i}`),this._services.fileUtils.deleteLibraryFromDisk(this,e,()=>t(null))},o=i=>{const n=new s(this,i,this.isPublic&&e);"pendingDelete"===i.current.compositeState?(this._pendingDeletes.push(n),t(null)):(this._libraries.push(n),this._libraryIdMap[n.id]=n,n._renditionCache.load().then(t))};this._services.dcx.newCompositeFromLocalStorage(i,(i,r)=>i||!r?n(`DCX error loading composite for ${e}`):r.current?_.validateLibrary(r)?this.isPublic||r.id===e?void(r.href&&r.current.isBound?r.loadBaseBranch((t,i)=>{t||!i?n(`missing base branch for ${e} (even though bound to server)`):o(r)}):o(r)):n(`library id ${r.id} doesn't match folder on disk ${e}`):n(`failed validation for ${e}`):(this._services.log(`Found incomplete pull of new library: ${e}`),this._partialSyncedNewLibraries[e]=!0,t(null)))}_load(e,t){this._loaded?e(null):(this._loaded=!0,this._services.fileUtils.readLibraryDirectory(this,(i,n)=>{if(i||!n)return void e(null);if(!t&&!this.isPublic&&n.length>=this._config.ELMO_LOCAL_LIBRARY_LIMIT)return void _.recoverFromElmo(this,n,()=>{this._loaded=!1,this._load(e,!0)});const o=[];n.forEach(e=>{if(_.validateLibraryId(e,this.isPublic)){const t=f(this._loadLibrary.bind(this))(e).catch(e=>this._reportCommitError(e));o.push(t)}}),o.push(this._externalLinkCache.load()),this.isPrivate&&o.push(this._bookmarkManager.load()),Promise.all(o).then(()=>{this._services.log("Loaded "+this._libraries.length+" libraries and "+this._pendingDeletes.length+" pending deletes"),e(null)})}))}_getLocalLibraryById(e){return this._libraryIdMap[e]||this._pendingDeletes.find(t=>t.id===e)||this._activeDeletes.find(t=>t.id===e)}_doesLibraryExist(e){return void 0!==this._getLocalLibraryById(e)}_syncNewLibrary(e,t,i,n){const o=t||this._getNewCompositeHref(e),r=this._services.hasFileSystem()&&this._getCompositeDir(e),s=this._services.dcx.newCompositeWithHref(o,r);return this._syncNewLibraryWithComposite(e,s,i,n)}_syncNewLibraryWithComposite(e,t,i,o){delete this._partialSyncedNewLibraries[e],this._libraryIdMap[e]="pending",this._updateSyncState();const r={id:e,_dcxComposite:t,collection:this};this._syncManager.pullLibrary(r,(r,a)=>{if(r||!a)return delete this._libraryIdMap[e],this._updateSyncState(),r=r?r.code===n.NO_COMPOSITE||r.code===n.DELETED_COMPOSITE?null:p.getSyncError(r,e):new c(c.NETWORK_ERROR,"No pulled branch"),void o(r,!0);t.resolvePullWithBranch(a,n=>{if(n||!this.isPublic&&t.id!==e)return delete this._libraryIdMap[e],this._updateSyncState(),n=n?p.getCommitError(n,e):new c(c.CORRUPTED_LIBRARY,"Library id does not match sync group id"),void o(n,!0);const r=new s(this,t,this.isPublic&&e);this._libraries.push(r),this._libraryIdMap[r.id]=r,this._updateSyncState(),r._setCollaboration(i),r._prefetchRenditions(),this._notifyChange(!0),o(null,!0)})})}_reportSyncError(e){e&&(this._services.log("Sync error: "+p.errorToString(e)),this._syncErrors.push(e))}_clearSyncErrors(e){this._syncErrors=e?this._syncErrors.filter(t=>t.libraryId!==e):[]}_reportCommitError(e){this._lastCommitError=e,e&&(this._services.log("Commit error: "+p.errorToString(e)),this._listenerManager.notify("commitError",[e]))}_updateRetryState(){if(!this._retryTimeoutId&&"syncing"!==this._syncState){if("error"===this._syncState){const e=this.getPrimarySyncError();if(e&&e.code===c.RETRYABLE_SERVER_ERROR){if(this._numRetries++,this._numRetries>this._config.ERROR_RETRY_INTERVALS.length)return this._retryTime="never",this._services.log("Retry Failed"),void(this._config.MAX_SYNC_INTERVAL=this._config.RETRY_FAIL_MAX_SYNC_INTERVAL);this._services.log("Retry "+this._numRetries);const t=e.underlyingError&&e.underlyingError.response&&e.underlyingError.response.headers;let i=1e3*this._config.getRetryAfterHeader(t);return i>0?(this._numRetries=this._config.ERROR_RETRY_INTERVALS.length,this._services.log("Got Retry-After header")):i=1e3*this._config.ERROR_RETRY_INTERVALS[this._numRetries-1],this._services.log("Retrying after "+i+"ms"),this._retryTime=Date.now()+i,void(this._retryTimeoutId=setTimeout(()=>{this._retryTimeoutId=void 0,this._retryTime=void 0,this._services.log("Starting retry"),this._syncWithParameters(!1)},i))}if(e&&e.code===c.EXCEEDS_QUOTA)return this._config.MAX_SYNC_INTERVAL=this._config.RETRY_FAIL_MAX_SYNC_INTERVAL,this._numRetries=this._config.ERROR_RETRY_INTERVALS.length+1,void(this._retryTime="never")}this._numRetries=0,this._retryTime=void 0}}_setInitialSyncState(e,t){this._initialSyncInProgress=e,this._loadingHint=t,this._updateSyncState()}_resetPollBackoff(){this._backoffTicks=0,this._numBackoffs=0}_updateSyncState(){let e="syncing";this._initialSyncInProgress||Object.keys(this._libraryIdMap).some(e=>{const t=this._libraryIdMap[e];return"pending"===t||t._isSyncing()})||(this._syncErrors.length>0?(e="error",this._syncManager.clearSyncGroupCache(),this._analytics.reportError(this.getPrimarySyncError())):e="ok",this._syncProgressMap={},this._syncProgress=void 0);const t=this._syncState;this._syncState=e,this._updateRetryState(),t===e&&"error"!==this._syncState||this._listenerManager.notify("sync")}_updateProgress(e,t,i){i?this._syncProgressMap[e]={bytesLoaded:t||0,bytesTotal:i,progress:this._syncProgressMap[e]&&this._syncProgressMap[e].progress}:this._syncProgressMap[e]?(0===this._syncProgressMap[e].bytesTotal&&(this._syncProgressMap[e].bytesTotal=1e4),this._syncProgressMap[e].bytesLoaded=this._syncProgressMap[e].bytesTotal):this._syncProgressMap[e]={bytesLoaded:0,bytesTotal:0};let n=!1;const o=t||0,r=(i||0)>0?Math.max(0,Math.min(100,Math.round(o/i*100))):void 0;this._syncProgressMap[e].progress!==r&&(this._syncProgressMap[e].progress=r,n=!0);let s=0,a=0,c=0,l=0;const h=this._syncProgressMap;Object.keys(h).forEach(e=>{s++,h[e].bytesTotal>0&&a++,c+=h[e].bytesLoaded,l+=h[e].bytesTotal});const d=l>0?c*a/(l*s):0,_=Math.max(0,Math.min(100,Math.round(100*d)));(!this._syncProgress||this._syncProgress<_||100===this._syncProgress&&_<100)&&(this._syncProgress=_,n=!0),n&&this._listenerManager.notify("sync")}_updateExternalLinkDownloadProgress(e,t,i,n){const o=e.element.library.id+"."+e.element.id+"."+e.id;let r;i?(t=t||0,r=Math.max(0,Math.min(100,Math.round(t/i*100)))):n&&(r=-1),r!==this._externalLinkDownloadProgressMap[o]&&(void 0===r?delete this._externalLinkDownloadProgressMap[o]:this._externalLinkDownloadProgressMap[o]=r,this._listenerManager.notify("sync"))}_getExternalLinkDownloadProgress(e){const t=e.element.library.id+"."+e.element.id+"."+e.id;return this._externalLinkDownloadProgressMap[t]}_abortPushOrPull(e=!1){Object.keys(this._libraryIdMap).forEach(e=>{const t=this._libraryIdMap[e];"pending"===t?this._syncManager.abortPushOrPull(e):t._abortPushOrPull()}),this._pendingDeletes.forEach(e=>e._abortPushOrPull());const t=this._pendingSyncs;this._pendingSyncs=[],t.forEach(e=>e(new c(c.TRANSFER_ABORTED,"abort push or pull operation"))),e&&this._syncManager.abortAllDownloads()}_getBaseDir(){const e=this._services.getPathSeparator();return this._services.fileUtils.getUserDir(this._userId)+e+this._directoryName}_getLibraryDir(e,t){const i=this._services.getPathSeparator();let n=this._getBaseDir()+i+e;return t&&(n+=i+t),n}_getCompositeDir(e){return this._getLibraryDir("dcx",e)}_getTempDir(){const e=this._services.getPathSeparator();return this._getBaseDir()+e+".tmp"}_getRenditionCacheDir(e){return this._getLibraryDir("renditions",e)}_addOperation(e,t,i,n){const o=new l(this,e,t,i,n);return this._operations.push(o),this._operationIdMap[o.id]=o,this._notifyOperationChange(),o}_removeOperation(e){const t=this._operations.indexOf(e);-1!==t&&(this._operations.splice(t,1),delete this._operationIdMap[e.id]),this._notifyOperationChange()}_delayedRemoveOperation(e){this._removeOperationTimeout[e.id]||(this._removeOperationTimeout[e.id]=setTimeout(()=>{delete this._removeOperationTimeout[e.id],this._removeOperation(e)},this._config.REMOVE_OPERATION_TIMEOUT))}_updateOperation(e,t,i,n){this._operationIdMap[e]||this._addOperation(e,t,i),this._removeOperationTimeout[e]&&(clearTimeout(this._removeOperationTimeout[e]),delete this._removeOperationTimeout[e]),this._operationIdMap[e]._updateProgress(n)}_notifyOperationChange(){this._listenerManager.notify("operation")}_doExportLibrary(e,t,i,n){if(this._config.SHARED_LOCAL_STORAGE){const n=this._services.uuid();return this._storageInterface.exportLibrary(e,t,n,i),this._addOperation(n,"export",{libraryId:e.id})}let o;n=n||this._services.uuid(),e._setAutoGC("export_"+n,!1);const r=this._addOperation(n,"export",{libraryId:e.id},()=>o&&o());return o=u.exportLibrary(e,t,e=>r._updateProgress(e),t=>{r._updateProgress(100),this._removeOperation(r),e._setAutoGC("export_"+n,!0),i(t)}),r}_syncWithParameters(e,t,i,n){const o=()=>n&&n(null);if(this._config.SHARED_LOCAL_STORAGE)return this._storageInterface.sync(this),void o();if(!this._config.SYNCING_ENABLED||this._retryTimeoutId)return void o();if(e||this._resetPollBackoff(),this._syncing)return void(this.isPolling?o():this._pendingSyncs.push(o));if(Date.now()<this._lastSyncTime+this._config.MAX_SYNC_INTERVAL)return void(t?o():setTimeout(()=>this._syncWithParameters(e,!0,i,o),this._config.MAX_SYNC_INTERVAL));this._services.log("Start Sync: "+this.cloudId+(e?" [polling]":"")),this._syncing=!0,this._lastSyncTime=Date.now();const r=(e,t)=>{if(this._syncing=!1,this._services.log("End Sync: "+this.cloudId),t&&this._resetPollBackoff(),this._pendingSyncs.length>0){const e=this._pendingSyncs;this._pendingSyncs=[],this.sync(()=>e.forEach(e=>e()))}o()};this._dosync(i,(e,t)=>{this._updateSyncState(),this._cleanLocalData().then(()=>r(0,t))})}get libraries(){return this._libraries}get commitError(){return this._lastCommitError}get syncState(){return this._syncState}get syncErrors(){return this._syncErrors}get syncProgress(){return this._syncProgress}get isInitialSyncInProgress(){return this._initialSyncInProgress}get isPolling(){return void 0!==this._pollTimerId}get isPrivate(){return!this.isPublic&&!this.isTeam}get isWritable(){return this.isPrivate}get isLoggedIn(){if(!this._config.SHARED_LOCAL_STORAGE)return this._syncManager.isLoggedIn()}get retryTime(){return"never"!==this._retryTime?this._retryTime:void 0}get userId(){return this._userId}get cloudId(){return this._cloudId}get cloudInfo(){return this._cloudInfo}get operations(){return this._operations}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}addDeepChangeListener(e){this._listenerManager.add("deepchange",e)}removeDeepChangeListener(e){this._listenerManager.remove("deepchange",e)}addOperationChangeListener(e){this._listenerManager.add("operation",e)}removeOperationChangeListener(e){this._listenerManager.remove("operation",e)}addSyncListener(e){this._listenerManager.add("sync",e)}removeSyncListener(e){this._listenerManager.remove("sync",e)}addCommitErrorListener(e){this._listenerManager.add("commitError",e)}removeCommitErrorListener(e){this._listenerManager.remove("commitError",e)}removeDeletedLibraries(e,t=(()=>{})){"function"==typeof e&&(t=e,e=void 0);const i=e&&e.exclude||[],n=e=>{const t=this._libraries.indexOf(e);return-1!==t&&(this._libraries.splice(t,1),delete this._libraryIdMap[e.id]),e._deletedFromDisk=!0,e._markDeletedLocally(!0),f(this._services.fileUtils.deleteLibraryFromDisk.bind(this._services.fileUtils))(this,e.id)},o=this._libraries.filter(e=>e.isDeletedFromServer&&i.every(t=>e!==t)).map(e=>n(e)),r=e=>{o.length>0&&this._notifyChange(!0),t(e)};Promise.all(o).then(()=>r(null),r)}exportLibrary(e,t,i){if(-1!==this._libraries.indexOf(e))if("string"==typeof t)if(0===t.length||t[t.length-1].match(/\\|\//))i(new c(c.INVALID_PARAMETER,"path must end in a filename"));else{if(t.substring(t.length-this._config.EXPORT_EXTENSION.length)!==this._config.EXPORT_EXTENSION&&(t+=this._config.EXPORT_EXTENSION),this._config.SHARED_LOCAL_STORAGE||this._services.hasFileSystem())return this._doExportLibrary(e,t,t=>{this._analytics.reportExportLibrary(t,e),i(t)});i(new c(c.REQUIRES_FILESYSTEM,"exportLibrary only supported when you have a filesystem"))}else i(new c(c.INVALID_PARAMETER,"path must be a string"));else i(new c(c.INVALID_PARAMETER,"library not in this collection"))}sync(e){this._syncWithParameters(!1,!1,void 0,e)}syncChanges(e,t){const i={};(e=e||[]).forEach(e=>i[e]=!0),this._syncWithParameters(!1,!1,i,t)}syncFull(e){this._syncManager.clearSyncGroupCache(),this._syncWithParameters(!1,!1,void 0,e)}getPrimarySyncError(){let e=this._syncErrors[0];return this._syncErrors.forEach(t=>{const i=p.getErrorPriority(t),n=p.getErrorPriority(e);i>n?e=t:i===n&&e.code===t.code&&e.libraryId!==t.libraryId&&(e=new c(e.code,"multiple errors (see libraryCollection.syncErrors)",void 0))}),e}getNewLibrarySyncProgress(){return this._newLibraryProgress?this._newLibraryProgress:Object.keys(this._libraryIdMap).filter(e=>"pending"===this._libraryIdMap[e]).map(e=>({id:e,progress:this._syncProgressMap[e]&&this._syncProgressMap[e].progress}))}get _pollInterval(){return 6e4*this._config.POLL_INTERVAL}startPolling(){if(this._config.SHARED_LOCAL_STORAGE)throw new c(c.NOT_SUPPORTED,"startPolling() not supported with shared local storage");this.isPolling||(this._pollTimerId=setInterval(()=>{"never"!==this._retryTime&&(this._backoffTicks>0?this._backoffTicks--:(0===this._backoffTicks&&(this._numBackoffs++,this._backoffTicks=this._config.getBackoffTicks(this._numBackoffs)),this._syncWithParameters(!0)))},this._pollInterval))}stopPolling(){if(this._config.SHARED_LOCAL_STORAGE)throw new c(c.NOT_SUPPORTED,"stopPolling() not supported with shared local storage");this.isPolling&&(clearInterval(this._pollTimerId),delete this._pollTimerId),this._retryTimeoutId&&(clearTimeout(this._retryTimeoutId),delete this._retryTimeoutId)}getLibraryById(e){const t=this._libraryIdMap[e];if(t instanceof s)return t}updateAccessToken(e){if(this._config.SHARED_LOCAL_STORAGE)throw new c(c.NOT_SUPPORTED,"updateAccessToken() not supported with shared local storage");this._syncManager.updateAccessToken(e),this._services.log("defined")}getTempDir(e){if(!this._services.hasFileSystem())return void e(new c(c.REQUIRES_FILESYSTEM,"getTempDir only supported when you have a filesystem"));const t=this._getTempDir();this._services.fileUtils.ensurePathExists(t,i=>e(i,t))}copyFileToTempDir(e,t){this.getTempDir((i,n)=>{if(i)return void t(i);const o=this._services.fileUtils.getFileExtension(e),r=n+this._services.getPathSeparator()+this._services.uuid()+(o?"."+o:"");this._services.fileUtils.copyFile(e,r,e=>{e?this._services.fileUtils.deleteFile(r,()=>t(e)):t(null,r)})})}_loadLibraryFromBookmark(e,t,i){const{id:n}=e,o=this.getLibraryById(n);if(o)return void i(null,o);if(e&&!this.canLoadLibrary(e))return void i(new c(c.INVALID_PARAMETER,"Invalid library location"));const r=this._newLibrariesLoading[n];if(r)return void r.push(i);this._newLibrariesLoading[n]=[i];const s=(e,t)=>{const i=this._newLibrariesLoading[n];delete this._newLibrariesLoading[n],i.forEach(i=>i(e,t))};if(this._config.SHARED_LOCAL_STORAGE)return t(this,e,s);this._syncNewLibrary(n,e.url||e.urn,void 0,e=>{if(e)return void s(e);const t=this.getLibraryById(n);s(null,t)}),e._onRemove=()=>{this._newLibrariesLoading[n]&&(this._newLibrariesLoading[n].push(()=>{this._services.fileUtils.deleteLibraryFromDisk(this,n,i)}),this._syncManager.abortPushOrPull(n))}}_unloadLibrary(e,t){const i=this._libraries.indexOf(e);-1!==i?(this._libraries.splice(i,1),delete this._libraryIdMap[e.id],e._abortPushOrPull(),e._markDeletedLocally(!0),this._config.SHARED_LOCAL_STORAGE?this.isTeam?this._storageInterface.unloadTeamLibrary(e,t):this._storageInterface.unloadPublicLibrary(e,t):(e._deletedFromDisk=!0,this._services.fileUtils.deleteLibraryFromDisk(this,e.id,t)),this._listenerManager.notify("change")):t(null)}_getLibrariesToUnload(){return[]}}},function(e,t){var i={},n={"application/x-indesign":!0,"application/postscript":!0,"application/illustrator":!0,"application/pdf":!0,"application/vnd.adobe.psremix":!0,"application/vnd.adobe.pstouch":!0,"application/vnd.adobe.ideas":!0,"application/vnd.adobe.ase":!0,"image/jpeg":!0,"image/jpg":!0,"image/pjpeg":!0,"image/tiff":!0,"image/gif":!0,"image/bmp":!0,"image/x-ms-bmp":!0,"image/svg+xml":!0,"image/png":!0,"image/x-png":!0,"image/jp2":!0,"image/psd":!0,"image/vnd.adobe.photoshop":!0,"image/heic":!0,"application/photoshop":!0,"application/x-photoshop":!0,"image/raw":!0,"image/dng":!0,"image/x-adobe-dng":!0,"video/mp4":!0,"video/mpeg":!0,"video/x-ms-wmv":!0,"video/3gpp":!0,"video/3gpp2":!0,"video/quicktime":!0,"video/x-msvideo":!0,"video/x-flv":!0,"video/x-ms-asf":!0,"video/x-m4v":!0,"video/mp2t":!0,"application/mxf":!0,"application/x-shockwave-flash":!0,"application/vnd.adobe.brushes.brush+ucf":!0,"application/vnd.adobe.collage":!0,"application/vnd.adobe.proto":!0,"application/msword":!0,"application/msexcel":!0,"application/mspowerpoint":!0,"application/vnd.ms-publisher":!0,"application/vnd.openxmlformats-officedocument.wordprocessingml.document":!0,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":!0,"application/vnd.openxmlformats-officedocument.presentationml.presentation":!0,"text/plain":!0,"text/rtf":!0};i.canComputeRenditionFromMimeType=function(e){return!!n[e]},i.canComputeRendition=function(e){return!(void 0===e._dcxComponent||!i.canComputeRenditionFromMimeType(e.type))},Object.seal(i),e.exports=i},function(e,t,i){const n=i(128),o=i(129),r=i(17),s=i(6);e.exports=class{constructor(e,t){this._apiRoot=e,this._rootDir=t,this._cache={},this._pendingCacheItems={},this._lock=new r,this._fs=n(this._services.fs,this._services.fileUtils),this._path=o(this._services.getPathSeparator())}get _config(){return this._apiRoot._config}get _services(){return this._apiRoot._services}get _storageInterface(){return this._apiRoot._storageInterface}load(){return this._loadingPromise||(this._loadingPromise=this._doTransaction(()=>this._load(),!1)),this._loadingPromise}save(){return this._doTransaction(()=>this._save())}_doTransaction(e,t=!0){const i=()=>this._lock.release();let n=new Promise(e=>this._lock.obtain(e)).then(e);return t&&(n=n.then(e=>this._save().then(()=>e))),n.then(i,i),n}_load(){return!this._services.hasFileSystem()||this._config.SHARED_LOCAL_STORAGE?Promise.resolve():this._services.fileUtils.readJSONData(this._path.join(this._rootDir,this._config.RENDITION_CACHE_FILE)).catch(()=>{}).then(e=>{this._cache=e||{}})}_save(){return!this._services.hasFileSystem()||this._config.SHARED_LOCAL_STORAGE?Promise.resolve():this._services.fileUtils.writeJSONData(this._rootDir,this._config.RENDITION_CACHE_FILE,this._cache).then(()=>this._gcUnreferencedFiles())}_waitForCommit(e){if(!this._lock.isLocked())return e();this._doTransaction(e,!1)}_getCache(e){let t=this._cache;for(let i=0;t&&i<e.length;i++)t=t[e[i]];return t}_isErrorCode(e){return e&&s.isErrorCode(e)}_isPath(e){return e&&e!==this._config.RENDITION_CACHE_PLACEHOLDER&&!this._isErrorCode(e)}_getFilePath(e,t){if(!e)return;if(t&&!this._isPath(e))return e;const i=this._path.join(this._rootDir,e);return this._config.SHARED_LOCAL_STORAGE||this._fs.statSync(i)?i:void 0}_setCacheEntry(e,t){let i=this._cache;for(let t=0;t<e.length-1;t++){const n=e[t];i=i[n]=i[n]||{}}const n=e[e.length-1];return void 0===t?delete i[n]:i[n]=t,t}_setCache(e,t,i){const n=this._services.fileUtils.getFileExtension(t)||"png",o=`${this._services.uuid()}.${n}`;return this._fs.ensureDir(this._rootDir).then(()=>{this._pendingCacheItems[o]=!0;const e=i?"rename":"copy";return this._fs[e](t,this._path.join(this._rootDir,o))}).then(()=>(delete this._pendingCacheItems[o],this._setCacheEntry(e,o),this._path.join(this._rootDir,o))).catch(e=>(delete this._pendingCacheItems[o],Promise.reject(s.getCommitError(e,void 0,"unable to save cache to disk"))))}_iterate(e,t=this._cache,i=[]){Object.keys(t).forEach(n=>{"object"==typeof t[n]?this._iterate(e,t[n],i.concat(n)):e(i,t[n])})}_gcUnreferencedFiles(){const e={};return this._iterate((t,i)=>{e[i]=!0,delete this._pendingCacheItems[i]}),this._fs.readdir(this._rootDir).then(t=>{const i=[];return t.forEach(t=>{const n=this._services.fileUtils.normaliseTempFileName(t);t===this._config.RENDITION_CACHE_FILE||e[t]||this._pendingCacheItems[n]||i.push(this._fs.remove(this._path.join(this._rootDir,t)))}),Promise.all(i)})}}},function(e,t){e.exports=class{constructor(e,t){this._type=e,this._id=t}toJSON(e){return{type:this._type,id:this._id,...e}}get id(){return this._id}get type(){return this._type}isReferenceTo(){return!1}}},function(e,t,i){const n=i(51),o=i(6),r=i(1),s={},a=/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\.[^/\\]+$/i;s.importLibrary=(e,t,i,a)=>{const c=e._services.fileUtils;let l,h;const d=(t,i)=>{if(h&&(t=new r(r.OPERATION_CANCELLED,"import cancelled")),t)return void a(t);l=void 0;const n=i.libraryId,s=i.extractPath,d=e._getCompositeDir(n),_=e=>{c.recursiveDeleteDirectory(s),c.recursiveDeleteDirectory(d),a(e)};c.rename(s,d,t=>{if(t)return _(o.getFileSystemError(t,"unable to move extracted zip after import"));e._loadLibrary(n,t=>{if(t)return _(t);const i=e.getLibraryById(n);if(!i)return _(new r(r.INVALID_DATA,"could not load library after import"));e._notifyChange(!0),i._push(),a(null,i)})})};return n.isSnapshot(t,(r,a)=>{if(r||h)return void d(r&&o.getSnapshotError(r,void 0,"error opening library archive"));const c=e._getTempDir();if(a){const r=t=>e._getNewCompositeHref(t);l=n.importSnapshot(t,c,r,!1,i,(e,t)=>{!e&&t?d(null,{libraryId:t.id,extractPath:t.path}):d(o.getSnapshotError(e,void 0,"cannot import the snapshot file"))})}else l=s._importNonSnapshotLibrary(e,t,c,i,d)}),()=>{h||(h=!0,l&&l())}},s._importNonSnapshotLibrary=(e,t,i,n,s)=>{const c=e._services.fileUtils,l=e._services.getPathSeparator(),h=e._services.fs,d=e._services.yauzl;if(!d)return void s(new r(r.NOT_SUPPORTED,"yauzl (unzip) module not present"));const _=e._services.uuid(),p=i+e._services.getPathSeparator()+_,u=e._getNewCompositeHref(_);let m,g=!1,f=-1,E=0,y=0;let v=!1;const A=e=>{v||(v=!0,e&&c.recursiveDeleteDirectory(p),s(e,e?void 0:{libraryId:_,extractPath:p}))},C=p+l+"components";return c.ensurePathExists(C,i=>{i?A(o.getFileSystemError(i,"unable to create temp dir")):d.open(t,{lazyEntries:!0},(t,i)=>{t?-1!==["EPERM","EACCES","ENOENT"].indexOf(t.code)?A(o.getFileSystemError(t,"error opening library archive")):A(new r(r.INVALID_DATA,"error opening library archive: "+t)):(m=i,m.on("entry",t=>{f++,E=0,y=0,(e=>"data"===e.fileName||e.fileName.match(a))(t)?"data"!==t.fileName?(E=t.uncompressedSize,m.openReadStream(t,(e,i)=>{e?A(o.getFileSystemError(e,"error extracting zip file")):(i.on("end",()=>{m.readEntry()}),i.on("data",e=>{y+=e.length,(()=>{if(!g){let e=f/m.entryCount;E&&(e+=y/(E*m.entryCount)),n(Math.round(100*e))}})()}).on("error",e=>{A(o.getFileSystemError(e,"error extracting zip file"))}).pipe(h.createWriteStream(C+l+t.fileName)))})):m.openReadStream(t,(t,i)=>{if(t)return void A(o.getFileSystemError(t,"error reading zip file entry"));const n=[];i.on("data",e=>{n.push(e)}),i.on("error",e=>{A(o.getFileSystemError(e,"error extracting zip file"))}),i.on("end",()=>{const t=((e,t,i,n)=>{let o;try{o=JSON.parse(e)}catch(e){return null}if(!o||o.version!==n)return null;const r=o.manifest,s=o.componentMap;return"object"!=typeof s||Object.keys(s).some(e=>"string"!=typeof s[e])?null:(r.id=t,r.local={version:2,change:1,compositeHref:i,"copyOnWrite#storageIds":o.componentMap},{json:o,manifest:r})})(Buffer.concat(n).toString(),_,u,e._config.EXPORT_VERSION);t&&t.manifest?h.writeFile(p+l+"manifest",JSON.stringify(t.manifest,void 0,2),e=>{e?A(o.getFileSystemError(e,"unable to write manifest file")):m.readEntry()}):A(new r(r.INVALID_DATA,"unable to parse export data"))})}):m.readEntry()}).on("error",e=>{A(o.getFileSystemError(e,"error extracting zip file"))}).on("close",()=>{g?A(new r(r.OPERATION_CANCELLED,"import cancelled")):A()}),m.readEntry())})}),()=>{g||(g=!0,m&&m.close())}},s.exportLibrary=(e,t,i,s)=>{let a;const c=n.exportSnapshot(e._dcxComposite,t,t=>(delete t[`${e._config.TOOLKIT_NAMESPACE}#${e._config.TOOLKIT_ID_KEY}`],t.children=t.children.filter(t=>t.name!==e._config.REMOVED_ELEMENTS_NAME),t),i,t=>{s(a?new r(r.OPERATION_CANCELLED,"export cancelled"):t&&o.getSnapshotError(t,e.id,"cannot export a snapshot file"))});return()=>{a||(a=!0,c())}},Object.seal(s),e.exports=s},function(e,t,i){const n=i(55),o=i(39),r=i(4),s=i(14),a=i(1);e.exports=class extends n{constructor(e,t,i){super(e,t,i),this._team=t.TEAM}get _directoryName(){return this._team.directory}_dosync(e,t){this._clearSyncErrors();const i=this._libraries.map(e=>{const t=t=>new Promise(i=>{e._sync(!t,(e,t)=>{e&&this._reportSyncError(e),i(t)})});return e.isPushedToServer?Promise.all([new Promise(t=>this._syncManager.hasCompositeChangedOnServer(e._dcxComposite,t)),this._getLibraryLinks(e)]).then(([i,n])=>(e._dcxComposite.links=n,e._commit(!0,!0),e._notifyChange(),t(i)),e=>this._reportSyncError(e)):t(!1)});i.push(this._handlePendingDeletes().then(()=>!1)),Promise.all(i).then(e=>{this._handleExternalPendingDeletes(),t(null,e.some(e=>e))})}get isTeam(){return!0}get platformDirectoryId(){return this._team.id}get name(){return this._team.name}get links(){return this._team.links}get isWritable(){return this._team.permissions&&this._team.permissions.includes("write")}get _pollInterval(){return 6e4*this._config.TEAM_POLL_INTERVAL}createLibrary(e){const t=super.createLibrary(e),i=o.waitForPushNew(t.id);return this._bookmarkManager.createBookmark("team",t.id,{team_urn:this.platformDirectoryId,org_id:this._team.orgId},i),t}removeLibrary(e,t){super.removeLibrary(e,t);const i=this._bookmarkManager.findBookmark(e);if(i){const t=o.waitForDelete(e.id);this._bookmarkManager.removeBookmark(i,t)}}canLoadLibrary(e){return e.teamUrn===this.platformDirectoryId}loadLibrary(e,t){return this._loadLibraryFromBookmark(e,(...e)=>this._storageInterface.loadTeamLibrary(...e),t)}_syncNewLibrary(e,t,i,n){if(!t)return n(new a(a.INVALID_PARAMETER));this._syncManager._storageService.getLinksFromUrn(t,(o,a)=>{if(o)return n(o);if(!r.getUrlFromLinks(a,s.DISCARD))return n();const c=r.getUrlFromLinks(a,s.PRIMARY),l=this._services.hasFileSystem()&&this._getCompositeDir(e),h=this._services.dcx.newCompositeWithHref(c,l);h.links=a,h.assetId=t,this._syncNewLibraryWithComposite(e,h,i,n)})}unloadLibrary(e,t){return this._unloadLibrary(e,t)}_getLibrariesToUnload(){return this.libraries.filter(e=>!this._bookmarkManager.findBookmark(e)||e.isPushedToServer&&!r.getUrlFromLinks(e._dcxComposite.links,s.DISCARD))}_onLibraryPush(e,t){const i=()=>{!t&&this.libraries.includes(e)||this._bookmarkManager.sync()};t?this._handleExternalPendingDeletes().then(i):i()}_getLibraryLinks(e){return new Promise((t,i)=>this._syncManager._storageService.getLinksFromUrn(e._dcxComposite.assetId,(e,n)=>e?i(e):t(n)))}}},function(e,t,i){const n=i(56);e.exports=class extends n{constructor(e,t,i){t.IS_PUBLIC=!0,t.USER_ID=t.USER_ID||e._config.PUBLIC_USER_ID,super(e,t,i)}_dosync(e,t){this._clearSyncErrors();const i=this._libraries.map(e=>new Promise(t=>{this._syncManager.hasCompositeChangedOnServer(e._dcxComposite,i=>{e._sync(!i,(e,i)=>{e&&this._reportSyncError(e),t(i)})})}));Promise.all(i).then(e=>t(null,e.some(e=>e)))}get isPublic(){return!0}canLoadLibrary({url:e}){return new RegExp(`${this._syncManager.getStorageHost()}/(.+)`).test(e)}loadLibrary(e,t){return this._loadLibraryFromBookmark(e,(...e)=>this._storageInterface.loadPublicLibrary(...e),t)}unloadLibrary(e,t){return this._unloadLibrary(e,t)}_getLibrariesToUnload(){return this.libraries.filter(e=>!this._bookmarkManager.findBookmark(e))}}},function(e,t,i){const n=i(3),o=e=>`${e}_req`,r=e=>`${e}_res`,s=(e,t,i)=>`${e}#${t}#${i}`;e.exports=class{constructor(e,t,i){this._apiRoot=e,this._socket=t,this._version=i,this._listenerManager=new n(void 0,e=>this._services.log(e)),this._socketListenerManager=new n(void 0,e=>this._services.log(e)),this._pendingWriteState={},this._pendingWriteDependencyMap={},this._stringMap={},this._addSocketListener("message",e=>this._onMessage(e))}get _services(){return this._apiRoot._services}_onMessage(e){if(this._pendingStringId)return this._log(`RECEIVE STRING ${this._pendingStringId}`),this._stringMap[this._pendingStringId]=e,void delete this._pendingStringId;if(":"===e[0])return void(this._pendingStringId=e);const t=JSON.parse(e,(e,t)=>{if("manifest"===e&&this._stringMap[t]){const e=this._stringMap[t];return delete this._stringMap[t],e}return t});this._log(`RECEIVE ${this._getLogMessage(t.type,t.data)}`),this._listenerManager.notify(t.type,[t.data])}_addSocketListener(e,t){this._socketListenerManager.add(e,t),this._socket.addListener(e,t)}_removeSocketListeners(){this._socketListenerManager.forEach((e,t)=>this._socket.removeListener(e,t)),this._socketListenerManager.removeAll()}_log(e){this._logCallback&&this._logCallback(e)}_getLogMessage(e,t){let i=e;return"syncstate"===e&&(i+=` ${t.cloudId}: ${t.state}`),i}get version(){return this._version}setPendingWriteState(e,t,i){const n=s(e,t,i);this._pendingWriteState[n]=!0}setPendingWriteDependency(e,t,i,n,o,r){const a=s(e,t,i),c=s(n,o,r);a!==c&&(this._pendingWriteDependencyMap[a]=this._pendingWriteDependencyMap[a]||{},this._pendingWriteDependencyMap[a][c]={userId:n,cloudId:o,id:r})}clearPendingWriteState(e,t,i){var n=s(e,t,i),o=[];return Object.keys(this._pendingWriteDependencyMap[n]||{}).forEach(e=>{o.push(this._pendingWriteDependencyMap[n][e])}),delete this._pendingWriteState[n],delete this._pendingWriteDependencyMap[n],o}getPendingWriteState(e,t,i,n){const o=s(e,t,i);let r=!1;return!n&&this._pendingWriteState[o]&&(r=this._pendingWriteState[o]),Object.keys(this._pendingWriteDependencyMap).forEach(e=>{this._pendingWriteDependencyMap[e][o]&&(r=this._pendingWriteState[e]||r)}),r}setLogCallback(e){this._logCallback=e}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}send(e,t){try{this._log(`SEND ${this._getLogMessage(e,t)}`);const i=JSON.stringify({type:e,data:t},(e,t)=>{if("manifest"===e&&"function"==typeof t&&(t=t(this._version<21)),"manifest"===e&&this._version>=16){const e=":"+this._services.uuid();return this._log(`SEND STRING ${e}`),this._socket.send(e),this._socket.send(t),e}return t});this._socket.send(i)}catch(e){this._log(`ERROR ${e}`),this._socketListenerManager.notify("error",[e])}}addCallListener(e,t){this.addListener(o(e),i=>{const n=i.id;t(i.data,t=>{this.send(r(e),{id:n,data:t})})})}removeCallListener(e,t){this.removeListener(o(e),t)}call(e,t,i){const n=this._services.uuid(),s=t=>{t.id===n&&(this.removeListener(r(e),s),i(t.data))};this.addListener(r(e),s),this.send(o(e),{id:n,data:t})}onOpen(e){this._addSocketListener("open",e)}onClose(e){this._addSocketListener("close",e)}onError(e){this._addSocketListener("error",e)}shutdown(){this._addSocketListener("close",()=>{this._removeSocketListeners(),this._listenerManager.removeAll()});try{this._socket.close()}catch(e){}}}},function(e,t,i){(function(e){const t=i(65).Module,n=t._nodeModulePaths.bind(t);t._nodeModulePaths=e=>n(e).filter(e=>e.startsWith(__dirname)),global.LOCALE_ROOT=__dirname+"/locale/",Error.stackTraceLimit=1/0;const o=i(0),r=i(15);let s=!1;if(process.argv.forEach(e=>{"--test"===e&&(console.log("Testing CCLibrary Process..."),s=!0)}),!o.isInSafeMode()){if(!o.validateAndLogStartupTimes()){const t=r.fork(e,process.argv.slice(2)),i=Date.now();return void t.on("exit",(e,t)=>{console.log(`CC Library Process exited with exit code ${e}, signal ${t}`);const n=e||t,r=Date.now()-i;n&&r<o.getValue("CRASH_RECOVERY_THRESHOLD")&&setInterval(()=>{},1e6)})}}const a=i(66);a.clearTempFiles(o.getValue("ROOT_DIR")),a.obtainProcessLock("lockfile",e=>{if(!e&&!s)return void process.exit(1);const t=new(i(69));if(s)return console.log("Testing OK"),void process.exit(0);t.start()})}).call(this,"/index.js")},function(e,t){e.exports=require("module")},function(e,t,i){var n=i(16),o=i(67),r=i(0);const s=i(68);var a=i(5),c={};c.obtainProcessLock=function(e,t){var i=r.getValue("ROOT_DIR");!function(e,t){n.ensureDir(e,i=>{if(i)return t(i);if("win32"!==process.platform)return t(void 0,!0);s.hasAppXPermissions(e).then(t=>t?(a.log("UWP_PERMISSIONS","present"),!0):(a.log("UWP_PERMISSIONS","trying to set"),!!t||s.setAppXPermissions(e))).then(e=>{if(e)return a.log("UWP_PERMISSIONS","permissions set"),t(void 0,!0);throw new Error("unknown error")}).catch(e=>{a.log("UWP_PERMISSIONS","ERROR: Failed to set up the proper permissions for UWP apps",e),t(void 0,!0)})})}(i,(function(r){if(r)return console.error("Error: Could not create root directory: "+i),void t(!1);var s=n.openSync(i+"."+e,"w");o.flock(s,"exnb",(function(e){if(e)return console.error("Error: CCLibrary process is already running."),void t(!1);t(!0)}))}))},c.clearTempFiles=function(e){try{var t=n.readdirSync(e);t&&t.forEach(t=>{if(-1!==t.indexOf(".TEMP_"))try{n.unlinkSync(e+"/"+t)}catch(e){}})}catch(e){}},e.exports=c},function(e,t){e.exports=require("fs-ext")},function(e,t){e.exports=require("fs-xtra")},function(e,t,i){const n=i(30),o=i(20),r=i(7),s=i(0),a=i(5),c=i(40),l=i(41),h=i(42),d=i(13),_=i(32),p=i(33),u=i(70),m=i(71),g=i(73),f=i(75),E=i(78),y=i(80),v=i(81),A=i(82),C=i(83),I=i(84),S=i(86),L=i(89),T=i(90),R=i(91),O=i(92),b=i(93),N=i(94),D=i(105),P=i(107),w=i(118),x=i(12),k=i(170),M=i(6),U=i(1),F=i(38);Error.stackTraceLimit=1/0;e.exports=class{constructor(e){this._isTesting=e,this._hasLoadedCollections=!1,this._loadedCollections=[],this._lastSyncState={},this._libraryListeners={},this._refreshCallbacks=[],this._initCCLibraries()}_start(){this._cdnCache.start(),this._initInterfaces(),this._createServers(),process.on("uncaughtException",this._handleUncaughtException.bind(this)),this._thorInterface.getProxyCredentials((e,t)=>{this._setProxyCredentials(e,t),this._loadCollections(),setTimeout(()=>this._startService(),100)}),this._localThumbnails.test(e=>a.log("LOCAL_THUMBNAIL_GENERATOR",e?"Test Successful":"Test Failure"))}start(){this._proxy.start().then(()=>this._start())}shutdown(){this._wss&&this._wss.forEach(e=>e.close()),this._apiServer&&this._apiServer.shutdown(),this._thorInterface.removeAllListeners(),this._coreSyncInterface.removeAllListeners(),this._ansInterface.removeAllListeners(),this._systemFonts.removeAllListeners(),this._cdnCache.removeAllListeners(),this._endpoint.removeAllListeners(),this._proxy.removeAllListeners(),this._authentication.removeAllListeners(),this._ccLibraries.removeLoadedCollectionsListener(this._loadedCollectionsListener),this._ccLibraries._storageInterface.removeOnAcceptPushedBranchListeners(),this._unloadCollections()}_initCCLibraries(){const e="CCLibrary/"+l.getCodeVersion()+" "+o.platform()+"/"+o.arch()+"/"+o.release();this._vulcan=new m,this._proxy=new S,this._endpoint=new C(this._vulcan),this._osToastNotifications=new T(this._vulcan),this._service=new f(this._vulcan,this._proxy),this._authentication=new E,this._analytics=new I(null,this._authentication,this._proxy),this._localThumbnails=new R(this._analytics),this._thorInterface=new y(this._analytics,this._vulcan,this._proxy),this._ansInterface=new A(this._analytics,this._vulcan,this._proxy),this._systemFonts=new O(void 0,this._analytics);const t={log:a.log,getNodeTunnelOptions:this._proxy.getNodeTunnelOptionsForURL.bind(this._proxy),refreshTeams:this.refreshTeams.bind(this),analytics:this._analytics,renditionGenerator:this._localThumbnails.generate.bind(this._localThumbnails)},i={ROOT_DIR:s.getValue("ROOT_DIR"),STORAGE_API_KEY:s.getEnvironment().CLIENT_ID,DEVICE_ID:this._authentication.getDeviceId(),DEVICE_DESCRIPTION:l.getDeviceDescription(),APP_DESCRIPTION:"LIBS-"+l.getCodeVersion(!0),USER_AGENT_HEADER:e,SHARED_LOCAL_STORAGE:!1,LOCAL_SETTINGS:s.getValue("LOCAL_SETTINGS")||{},RENDITION_SIZES:s.getValue("RENDITION_SIZES")||{},FULL_RENDITION_CONFIG:s.getValue("FULL_RENDITION_CONFIG")||{},EXTERNAL_LINK_PREFETCH:s.getValue("EXTERNAL_LINK_PREFETCH")||{},LOCALE:this._proxy.getOSLocale()};a.log("Service",`locale: ${i.LOCALE}`);const n=s.getValue("WHITELISTED_DOMAINS");n&&(i.WHITELISTED_DOMAINS=n),this._ccLibraries=new w(t,i),this._loadedCollectionsListener=this._loadedCollectionsListener.bind(this),this._ccLibraries.addLoadedCollectionsListener(this._loadedCollectionsListener),this._analytics._ccLibraries=this._ccLibraries,this._productBridge=new g(this._ccLibraries,this._authentication,this._vulcan),this._coreSyncInterface=new v(this._ccLibraries,this._vulcan),this._cdnCache=new b(this._ccLibraries,this._proxy),this._productLauncher=new L(this._ccLibraries,this._analytics,this._vulcan),this._productLauncher.updateInstallationMap(),!1===s.getValue("SYNCING_ENABLED")&&(a.log("Service","Syncing disabled"),this._ccLibraries.disableSyncing())}_checkEnvironment(){const e=s.isEnvironmentCorrect();return e||this._logAndWait("Environment changed - quitting.").then(()=>process.exit()),e}_initInterfaces(){const e=()=>{this._productLauncher.updateInstallationMap(),this._broadcast("environmentinfo",l.getEnvironmentData(this._ccLibraries))};this._thorInterface.addListener("installApplication",e),this._thorInterface.addListener("uninstallApplication",e),this._thorInterface.addListener("updateApplication",()=>{this._productLauncher.updateInstallationMap(!0),e()}),this._authentication.addChangeListener(()=>{this._authentication.getUserId()?this._checkEnvironment()&&this._loadCollections():this._unloadCollections()}),this._thorInterface.addListener("proxySettingsChanged",(e,t)=>{this._setProxyCredentials(e,t,!0)}),this._thorInterface.addListener("analyticsStateChanged",e=>{this._checkEnvironment();const t=this._authentication.getUserId();t&&(s.setValue(`ANALYTICS_ENABLED_${t}`,e),this._setAnalyticsState(e))}),this._coreSyncInterface.addListener("libraryChange",this._onLibraryChange.bind(this)),this._coreSyncInterface.addListener("bookmarkChange",this._syncLibraryBookmarks.bind(this)),this._coreSyncInterface.addListener("fileSyncState",this._updateSyncState.bind(this)),this._ansInterface.addListener("stock.open.request",this._onStockOpenInRequest.bind(this)),this._ansInterface.addListener("sharing.collaboration.updaterole",()=>{this._ccLibraries.getLoadedCollections().forEach(e=>{!e.isPublic&&this._syncLibraryCollection(e,!0)})}),this._osToastNotifications.addListener("clickNotification",e=>{"LAUNCH_CC"===e&&this._productLauncher.launchCCD(null,e=>e?a.log("Service","Open Stock - Launch CC failed "+e):a.log("Service","Open Stock - Successfully launched CC from user click"))}),this._proxy.addListener("change",e=>{e&&this._thorInterface.getProxyCredentials((e,t)=>{this._setProxyCredentials(e,t,!0)})}),this._proxy.addListener("error",e=>this._analytics.reportError("ProxyResolverError",e)),this._endpoint.addListener("cloudChange",this._onCloudChange.bind(this));const t=e=>{this._ccLibraries.getLoadedCollections().forEach(t=>{t.isPrivate&&(e&&t.fontManager._clearCache(),this._broadcast("fontcachechanged",{isPublic:t.isPublic,userId:t.userId,cloudId:t.cloudId}))})};this._systemFonts.addChangeListener(()=>t(!1)),this._ansInterface.addListener("com.adobe.system.inform.typekit.generic.entitlementschanged",()=>t(!0)),this._cdnCache.addChangeListener(()=>this._broadcast("environmentinfo",l.getEnvironmentData(this._ccLibraries)))}_createServers(){this._wss=[new n.Server({port:0,host:"127.0.0.1",verifyClient:(e,t)=>{const i="file://"===e.origin||e.origin.match(/http:\/\/localhost:[0-9]+$/);i||(a.log("Service","Rejected attempt to connect to websocket server from: "+e.origin),this._analytics.reportEvent("rejectedClientOrigin",{origin:e.origin})),t(i)},maxPayload:s.getValue("MAX_WS_PAYLOAD")}),new D(this._ccLibraries,this._authentication)],this._apiServer=new N(this._ccLibraries,this._authentication,this._vulcan),this._apiServer.initialize()}_startService(){this._channelManager=new k(this._ccLibraries),this._webSocketServers=this._wss.map(e=>new P(e,this._channelManager,this)),this._ccLibraries._storageInterface.onAcceptPushedBranch(e=>{const t=-1!==this._ccLibraries.getLoadedCollections().indexOf(e.collection),i=e.collection.getLibraryById(e.id)===e;t&&i&&this._notifyLibraryChange(e)}),this._ccLibraries._storageInterface.onDownloadRendition(e=>{this._broadcast("renditioncachechange",l.getElementRenditionCacheData(e)),this._productBridge.renditionChanged(e)}),s.setValue("SERVICE_PORT",this._getPort()),s.setValue("SERVICE_TOKEN",this._uuid()),a.log("Service",`Version: ${l.getCodeVersion(!0)} (protocol version = ${l.getAPIVersion(this._ccLibraries)}) (safe mode = ${s.isInSafeMode()})`),a.log("Service",`Environment: ${s.getEnvironment().LABEL}`),a.log("Service",`Root: ${s.getValue("ROOT_DIR")}`),a.log("Service",`Listening on port: ${s.getValue("SERVICE_PORT")}`),this._service.sendStartupMessage(),this._analytics.reportEvent("processStarted",{apiVersion:l.getAPIVersion(this._ccLibraries),environment:s.getEnvironment().LABEL,osType:o.type(),osPlatform:o.platform(),osArch:o.arch(),osRelease:o.release(),osTotalMem:o.totalmem(),osFreeMem:o.freemem()})}_broadcast(e,t,i){this._channelManager&&this._channelManager.broadcast(e,t,i)}_uuid(){return r()}_logAndWait(e){return new Promise(t=>{const i=()=>{a.removeLogWriteListener(i),t()};a.addLogWriteListener(i),a.log("Service",e)})}_handleUncaughtException(e){const t=this._logAndWait(`Uncaught exception: ${e}\n${e.stack}`),i=new Promise(t=>{this._ccLibraries&&this._ccLibraries._config.ANALYTICS_ENABLED?this._analytics.reportError("Uncaught",`${e}\n${e.stack}`,!0,t):t()});Promise.all([t,i]).then(()=>process.exit())}_getPort(){return this._wss[0]._server.address().port}waitForWSSInitialization(){return this._wss[1].waitForInitialization()}_notifyLibraryChange(e){_.isLocked(e.id)||(this._broadcast("librarychange",l.getLibraryData(e)),this._productBridge.libraryChanged(e,!1))}_notifyCollectionAdded(e){const t=t=>this._ccLibraries._config.isCollectionSupported(t.version,e);this._broadcast("collectionadded",l.getCollectionData(e),t),this._broadcast("syncstate",l.getSyncStateData(e),t)}_notifyCollectionRemoved(e){this._broadcast("collectionremoved",e)}_validateBookmarks(){this._validatingBookmarks?this._pendingValidateBookmarks=!0:this._validatingBookmarks=c.validateBookmarks(this._ccLibraries).then(()=>{delete this._validatingBookmarks,this._pendingValidateBookmarks&&(this._pendingValidateBookmarks=!1,this._validateBookmarks())})}_onBookmarksChanged(){this._validateBookmarks(),c.sendBookmarksChanged(this._ccLibraries,this._channelManager)}_syncLibraryCollection(e,t,i){const n=()=>{const n=()=>this._validateBookmarks();i?e.syncChanges(i,n):t?e.syncFull(n):e.sync(n)};e.isPublic||e.isLoggedIn?n():this._authentication.getAccessToken((t,i)=>{!t&&i&&(e.updateAccessToken(i),n())})}_syncLibraryChanges(e){this._ccLibraries.getLoadedCollections().forEach(t=>{e?t.isPublic||this._syncLibraryCollection(t,!1,e):this._syncLibraryCollection(t,!1)})}_onLibraryChange(e){this._debounceTimeout?this._doSyncOnDebounce=!0:(this._syncLibraryChanges(e),this._debounceTimeout=setTimeout(()=>{this._doSyncOnDebounce&&this._syncLibraryChanges(),this._debounceTimeout=null,this._doSyncOnDebounce=!1},s.getValue("CORE_SYNC_NOTIFICATION_DEBOUNCE")))}_syncLibraryBookmarks(){this._ccLibraries.getLoadedCollections().forEach(e=>e.isPrivate&&e.syncBookmarks())}_syncCollectionsIfError(){this._ccLibraries.getLoadedCollections().forEach(e=>"error"===e.syncState&&this._syncLibraryCollection(e))}_updateSyncState(e,t){if(this._syncState!==e){if(clearTimeout(this._reportSyncStateTimeout),"normal"!==e){const i=s.getValue("CORE_SYNC_ANALYTICS_WAIT");this._reportSyncStateTimeout=setTimeout(()=>{this._analytics.reportEvent("fileSyncState",{state:e,isNotification:!!t,reportingDelay:i})},i)}this._syncState=e,this._ccLibraries.isSyncingEnabled()&&"turned_off"===e?(a.log("Service","Syncing disabled"),s.setValue("SYNCING_ENABLED",!1),this._ccLibraries.disableSyncing(),this._broadcast("environmentinfo",l.getEnvironmentData(this._ccLibraries))):this._ccLibraries.isSyncingEnabled()||"turned_off"===e||(a.log("Service","Syncing enabled"),s.setValue("SYNCING_ENABLED",!0),this._ccLibraries.enableSyncing(),this._broadcast("environmentinfo",l.getEnvironmentData(this._ccLibraries)),this._syncLibraryChanges())}}_broadcastSyncState(e){const t=e.userId+"/"+e.cloudId;if(this._lastSyncState[t]=this._lastSyncState[t]||{lastBroadcast:0},this._lastSyncState[t].pendingBroadcast)return;const i=s.getValue("SYNC_STATE_BROADCAST_THROTTLE"),n=Date.now();if(n-this._lastSyncState[t].lastBroadcast<i)return void(this._lastSyncState[t].pendingBroadcast=setTimeout(()=>{delete this._lastSyncState[t].pendingBroadcast,this._broadcastSyncState(e)},i));this._lastSyncState[t].lastBroadcast=n;const o=l.getSyncStateData(e);if(this._broadcast("syncstate",o),"error"===e.syncState){const t=e.getPrimarySyncError();this._analytics.reportError("SyncError",M.errorToString(t))}}_broadcastOperations(e){const t=l.getOperationsData(e);this._broadcast("operationschanged",t)}_loadedCollectionsListener(){const e=[],t={};this._loadedCollections.forEach(i=>{h.getLibraryCollection(this._ccLibraries,i.isTeam,i.isPublic,i.userId,i.cloudId,i.platformDirectoryId)?(e.push(i),t[i.userId+"/"+i.cloudId]=!0):this._notifyCollectionRemoved(i)}),this._ccLibraries.getLoadedCollections().forEach(i=>{const n=i.isPublic?x.PUBLIC_USER_ID:i.userId;t[n+"/"+i.cloudId]||(e.push({isTeam:i.isTeam,isPublic:i.isPublic,userId:n,cloudId:i.cloudId,platformDirectoryId:i.platformDirectoryId}),this._notifyCollectionAdded(i))}),this._loadedCollections=e}_ensureLibraryListeners(e){const t=(e.isPublic?"":e.userId)+"/"+e.cloudId;this._libraryListeners[t]=this._libraryListeners[t]||{};const i=this._libraryListeners[t];e.libraries.forEach(e=>{i[e.id]||(i[e.id]=()=>this._notifyLibraryChange(e),e.addChangeListener(i[e.id]),this._notifyLibraryChange(e))}),Object.keys(i).forEach(t=>{e.getLibraryById(t)||(this._broadcast("librarydeleted",l.getDeletedLibraryData(e,t)),this._productBridge.libraryDeleted(t),delete i[t])})}_onCloudChange(e,t,i){const n=t?t.id:x.DEFAULT_CLOUD_ID;this._ccLibraries.getLoadedCollections().some(e=>e.cloudId===n)?a.log("Service","Active cloud the same as already loaded"):(a.log("Service","Active cloud changed"),this._unloadCollections(),this._loadCollections(!0,e,t,i),this._analytics.reportEvent("cloudChange",{cloudId:n,numClouds:i}))}_setProxyCredentials(e,t,i){this._proxy.setProxyCredentials(e,t),i&&this._authentication.hasEntitlement("cce_private",e=>{void 0===e?(this._unloadCollections(),this._loadCollections()):this._syncCollectionsIfError()})}_setAnalyticsState(e){this._ccLibraries._config.ANALYTICS_ENABLED!==e&&(this._ccLibraries._config.ANALYTICS_ENABLED=e,this._analytics.setEnabled(e),this._broadcast("environmentinfo",l.getEnvironmentData(this._ccLibraries)))}_sendOpenInToast(e,t,i,n){this._osToastNotifications.sendToast({title:this._ccLibraries._localisation.translate("LIBS_OPEN_IN_TITLE"),message:this._ccLibraries._localisation.translate(e),key:t,data:i,overridable:n})}_sendOpenInAnalytics(e,t){const i={"ui.search_keyword":t.launchInfo.search_keyword,"event.context_guid":t.launchInfo.context_guid,"event.type":e,"event.category":"STOCK","event.subcategory":"Open-In","env.com.name":"stock_openin","consumer.name":t.launchInfo.appCode,"consumer.version":t.productInfo?t.productInfo.version:t.launchInfo.minVersion,"consumer.platform":o.platform(),"consumer.os_version":o.release(),"openin.element_id":t.launchInfo.elementRef,"openin.element_type":t.launchInfo.elementType,"openin.app_launch_status":t.productInfo?t.productInfo.isAlreadyRunning?"Running":"Launched":"Unknown"};t.error&&(i["event.error_desc"]=t.error),t.element&&(i["event.cloud_id"]=t.element.library.collection.cloudId,i["content.id"]=p.getElementStockId(t.element),i["content.status"]=p.getElementStockLicense(t.element),i["content.type"]=t.element.getPrimaryRepresentation().type),this._analytics.reportEvent("Library-Process-Open-In",i)}_launchOpenInProduct(e,t){a.log("Service","Open Stock -  launch product "+e.elementRef),this._productLauncher.launch({appCode:e.appCode,minVersion:e.appVersion||"0",element:t,action:"openStock"},(i,n)=>{if(i)return a.log("Service","Open Stock - Error opening product "+i),this._sendOpenInToast("LIBS_OPEN_IN_PRODUCT_LAUNCH_FAILED_"+e.appCode),void this._sendOpenInAnalytics("error",{launchInfo:e,error:"Launch product failed",productInfo:n,element:t});a.log("Service","Open Stock - Open request success"),this._sendOpenInAnalytics("useElement",{launchInfo:e,productInfo:n,element:t})})}_onStockOpenInRequest(e){if(a.log("Service","Open Stock - Recieved open request via ANS "+JSON.stringify(e)),e.state&&"new"!==e.state.toLowerCase())return void a.log("Service","Open Stock - Message state not new. Returning");this._ansInterface.setState({id:e.id,state:"received"});const t=e.payload;if(this._sendOpenInAnalytics("response",{launchInfo:t}),!t.protocolVersion||!t.elementRef||!t.appCode)return a.log("Service","Open Stock - ANS request corrupt "+JSON.stringify(e)),this._sendOpenInToast("LIBS_OPEN_IN_DOWNLOAD_ERROR"),void this._sendOpenInAnalytics("error",{launchInfo:t,error:"ANS request corrupt"});if("1"!==t.protocolVersion.split(".")[0])return a.log("Service","Open Stock - Unsupported protocol version from ans message "+t.protocolVersion),this._sendOpenInToast("LIBS_OPEN_IN_UNSUPPORTED_PROTOCOL","LAUNCH_CC"),void this._sendOpenInAnalytics("error",{launchInfo:t,error:"Unsupported protocol version from ans message"});if(!this._ccLibraries.isSyncingEnabled())return a.log("Service","Open Stock - Sync Disabled."),this._sendOpenInToast("LIBS_OPEN_IN_SYNC_DISABLED"),void this._sendOpenInAnalytics("error",{launchInfo:t,error:"Sync Disabled"});const i=this._productLauncher.appStatus({appCode:t.appCode,minVersion:t.appVersion||"0"});return"APP_NOT_INSTALLED"===i?(this._sendOpenInToast("LIBS_OPEN_IN_NOT_INSTALLED_"+t.appCode,"LAUNCH_CC"),void this._sendOpenInAnalytics("notify",{launchInfo:t})):"NO_COMPATIBLE_VERSION"===i?(this._sendOpenInToast("LIBS_OPEN_IN_NO_COMPATIBLE_VERSION_"+t.appCode,"LAUNCH_CC"),void this._sendOpenInAnalytics("notify",{launchInfo:t})):(this._sendOpenInToast("LIBS_OPEN_IN_START_DOWNLOAD",null,null,!0),void h.findElement(this._ccLibraries,t.elementRef,(e,i)=>{if(e){a.log("Service","Open Stock - Error from find element "+e);const i="COLLECTION_NOT_FOUND"===e?"LIBS_OPEN_IN_COLLECTION_NOT_FOUND":"LIBS_OPEN_IN_DOWNLOAD_ERROR";return this._sendOpenInToast(i),void this._sendOpenInAnalytics("error",{launchInfo:t,error:i})}a.log("Service","Open Stock -  downloading element "+t.elementRef),i.library.sync(e=>{if(e)return a.log("Service","Open Stock - Error downloading element "+e),this._sendOpenInToast("LIBS_OPEN_IN_DOWNLOAD_ERROR"),void this._sendOpenInAnalytics("error",{launchInfo:t,error:"Download Failed"});i._prefetchRenditions(e=>{if(e)return a.log("Service","Open Stock - Error downloading element "+e),this._sendOpenInToast("LIBS_OPEN_IN_DOWNLOAD_ERROR"),void this._sendOpenInAnalytics("error",{launchInfo:t,error:"Download Failed"});if(this._productBridge.libraryChanged(i.library,!1),!this._productBridge.isSyncing())return void this._launchOpenInProduct(t,i);a.log("Service","Open Stock -  waiting for product bridge to update "+t.elementRef);const n=()=>{this._productBridge.isSyncing()||(this._productBridge.removeListener("syncEnd",n),this._launchOpenInProduct(t,i))};this._productBridge.addListener("syncEnd",n)})})}))}_startCollectionListener(e){e.addSyncListener(()=>this._broadcastSyncState(e)),e.addOperationChangeListener(()=>this._broadcastOperations(e)),e.addChangeListener(()=>this._ensureLibraryListeners(e)),this._ensureLibraryListeners(e)}_loadPublicCollectionWithOptions(e,t){a.log("Service","Load public collection: "+JSON.stringify(e)),this._ccLibraries.loadPublicLibraryCollection(e,(e,i)=>{if(e)return a.log("Service","Error loading public libraries: "+e),void this._handleUncaughtException(e);i.startPolling(),this._startCollectionListener(i),t()})}_loadTeamCollectionWithOptions(e,t){a.log("Service","Load team collection: "+JSON.stringify(e)),this._ccLibraries.loadTeamLibraryCollection(e,(e,i)=>{if(e)return a.log("Service","Error loading team libraries: "+e),t(e);i.startPolling(),this._startCollectionListener(i),t()})}_loadPublicCollections(e,t){const i=s.getEnvironment().PUBLIC_HOSTS.map(t=>new Promise(i=>{const n={getAccessToken:this._authentication.getAccessToken.bind(this._authentication),USER_ID:e.USER_ID,CC_IMAGE_HOSTNAME:e.CC_IMAGE_HOSTNAME,CC_IMAGE_X_HOSTNAME:e.CC_IMAGE_X_HOSTNAME,STORAGE_HOSTNAME:t.host};t.community_platform?(n.CLOUD_ID=x.CP_CLOUD_ID+"_"+t.host,n.REQUIRES_COMMUNITY_SESSION=!0):n.CLOUD_ID=t.host,this._loadPublicCollectionWithOptions(n,i)}));Promise.all(i).then(t)}refreshTeams(e=!1,t=(()=>{})){if(this._refreshCallbacks.push(t),e||!this._inRefreshQuietPeriod){const e=()=>{const e=this._refreshCallbacks;this._refreshCallbacks=[],e.forEach(e=>e())};this._inRefreshQuietPeriod=!0;const t=this._getLoadOptions();setTimeout(()=>{this._inRefreshQuietPeriod=!1,this._refreshCallbacks.length>0&&this._refreshTeamCollections(t,e)},s.TEAM_REFRESH_INTERVAL),this._refreshTeamCollections(t,e)}}_addLocalTeamDirectories(e,t){const i=`TEAM_DIRECTORY_LOOKUP_${e}`,n=s.getValue(i)||{_cursor:0,teams:{}};t.forEach(e=>{n.teams[e.id]||(n.teams[e.id]=`team${n._cursor}`,n._cursor+=1),e.directory=n.teams[e.id]}),s.setValue(i,n)}_loadTeamsAsCollections(e,t,i=(()=>{})){const n=this._ccLibraries.getLoadedCollections().filter(e=>{if(!e.isTeam)return!1;const i=t.find(t=>t.id===e.platformDirectoryId);if(!i)return!0;const n=e._team.permissions||[],o=i.permissions||[];return!(n.length===o.length&&!n.some(e=>!o.includes(e)))&&(a.log(`Permissions have changed for loaded team: ${i.id}`),!0)});n.forEach(e=>this._ccLibraries.unloadLibraryCollection(e));const o=t.filter(e=>!this._ccLibraries.getLoadedCollections().find(t=>t.platformDirectoryId===e.id)),r=n.length>0||o.length>0;return Promise.all(o.map(t=>new Promise((i,n)=>{const o=s.getEnvironment(),r={PLATFORM_ROOT_DOCUMENT:e.PLATFORM_ROOT_DOCUMENT,getAccessToken:this._authentication.getAccessToken.bind(this._authentication),USER_ID:e.USER_ID,CC_IMAGE_HOSTNAME:e.CC_IMAGE_HOSTNAME,CC_IMAGE_X_HOSTNAME:e.CC_IMAGE_X_HOSTNAME,STORAGE_HOSTNAME:o.ACP_CS_HOST,STORAGE_HOSTNAME_REGEX:o.ACP_CS_HOST_REGEX,TEAM:t,CLOUD_ID:F.getCloudIdFromUrn(t.id)};this._loadTeamCollectionWithOptions(r,e=>e?n(e):i())}))).then(()=>i(null,r),i)}_getAccessToken(){return new Promise((e,t)=>{this._authentication.getAccessToken((i,n)=>{i||!n?t(new U(U.INVALID_DATA,"Failed to get access token.",i)):e(n)})})}_getPlatformSessionAndDocument(){const e=e=>u.getRootDocument(e).then(t=>(this._platformSessionAndDocument={session:e,document:t},this._ccLibraries.getLoadedCollections().forEach(e=>e._setRootDocument(t)),this._platformSessionAndDocument));return this._platformSessionAndDocument&&this._platformSessionAndDocument.session?e(this._platformSessionAndDocument.session):this._getAccessToken().then(t=>{const i=this._ccLibraries._services.dcx.createHTTPService();i.setAuthToken(t),i.setApiKey(s.getEnvironment().CLIENT_ID);const n=this._ccLibraries._services.dcx.createPlatformSession(i,`https://${s.getEnvironment().ACP_CS_HOST}`,s.getEnvironment().ACP_CS_HOST_REGEX);return e(n)})}_loadTeamCollections(e,t){e.PLATFORM_ROOT_DOCUMENT=u.getCachedRootDocument(!0);const i=s.getValue(`TEAM_COLLECTIONS_${e.USER_ID}`)||[];this._loadTeamsAsCollections(e,i,t),this._refreshTeamCollections(e)}_refreshTeamCollections(e,t=(()=>{})){const i=this._authentication.getUserProfile();if(!i||"type1"===i.accountType)return t();this._getPlatformSessionAndDocument().then(({session:i,document:n})=>{u.getRepository(i).then(o=>{if(!o)return a.log("Service","Error: User doesn't have a repository"),t(new U(U.INVALID_DATA,"A type-2 user should always have an organization."));const r=o["repo:repositoryId"],c=o["repo:owner"].id;this._proxy.fetch(`http://${s.getEnvironment().ORG_BETA_HOST}/${c}`).then(e=>e.json()).then(o=>{if(!o||!o.beta)return a.log("Service","User is not part of the team libraries beta"),t();this._getTeamFolders(i,e.USER_ID,r,(i,o)=>{if(i)return t(i);this._loadTeamsAsCollections({...e,PLATFORM_ROOT_DOCUMENT:n},o,(e,i)=>{!e&&i&&this._productBridge.collectionsLoaded(),t(e)})})},t)},t)},t)}_getTeamFolders(e,t,i,n){const o=i=>{const n=i.map(t=>new Promise((i,n)=>{e.getEffectiveACFromLinks(t.links,(e,o)=>e?n(e):i({...t,permissions:o}))}));return Promise.all(n).then(e=>{this._addLocalTeamDirectories(t,e),s.setValue(`TEAM_COLLECTIONS_${t}`,e);const i=e&&e.map(e=>e.name);return a.log("Service",`Fetched ${e&&e.length} teams: ${i.join(", ")}`),e})};e.getAssets((t,r)=>{if(t||!r||!r.children)return n(new U("INDEX_ERROR","Bad response from ACP discovery API",t));let s,c;try{s=u.getTeamsFromAssetsResponse(i,r),c=u.getRootLinksFromAssetsResponse(i,r)}catch(t){return a.log("Service",`Could not parse platform assets response: ${i}`),n(t)}if(!c)return o(s).then(e=>n(null,e),n);e.getEffectiveACFromLinks(c,(t,r)=>t?n(t):r.includes("write")?void u.navigateToRepoPath(e,i,u.TOP_LEVEL_FOLDER_PATH).then(e=>{const t=[];e.children.forEach(e=>{u.isVisibleFolder(e)&&t.push({id:e["repo:assetId"]||e["repo:id"],orgId:i,name:e["repo:name"],links:e._links})}),o(t).then(e=>n(null,e),n)},n):o(s).then(e=>n(null,e),n))})}_loadCollectionWithOptions(e){a.log("Service","Load library collection: "+JSON.stringify(e)),this._ccLibraries.loadLibraryCollection(e,(t,i)=>{if(t)return a.log("Service","Error loading libraries: "+t),void this._handleUncaughtException(t);this._startCollectionListener(i);const n=[new Promise(t=>this._loadPublicCollections(e,t)),new Promise(t=>this._loadTeamCollections(e,t))];Promise.all(n).then(()=>{this._productBridge.collectionsLoaded(),this._onBookmarksChanged(),i.isPrivate&&i.addBookmarkChangeListener(()=>{i.bookmarks.some(e=>"team"===e.type&&!this._ccLibraries.getLoadedTeamCollectionById(e.teamUrn))?this.refreshTeams(!0,()=>this._onBookmarksChanged()):this._onBookmarksChanged()}),h.fixRenditions(this._ccLibraries.getLoadedCollections())})})}_getLoadOptions(){const e=s.getEnvironment();return{getAccessToken:this._authentication.getAccessToken.bind(this._authentication),USER_ID:this._authentication.getUserId(),STORAGE_HOSTNAME:s.getValue("STORAGE_HOST")||e.STORAGE_HOST,PLATFORM_HOSTNAME:s.getValue("ACP_CS_HOST")||e.ACP_CS_HOST,INVITATIONS_HOSTNAME:s.getValue("INVITATIONS_HOST")||e.INVITATIONS_HOST,CC_IMAGE_HOSTNAME:s.getValue("CC_IMAGE_HOST")||e.CC_IMAGE_HOST,CC_IMAGE_X_HOSTNAME:s.getValue("CC_IMAGE_X_HOST")||e.CC_IMAGE_X_HOST,TYPEKIT_HOSTNAME:s.getValue("TYPEKIT_HOST")||e.TYPEKIT_HOST,CC_LIBRARY_SERVICE_HOSTNAME:s.getValue("CC_LIBRARY_SERVICE_HOST")||e.CC_LIBRARY_SERVICE_HOST}}_loadCollectionsFromCloud(e,t,i){a.log("Service","Loading collection for active cloud: "+JSON.stringify(t));const n=this._getLoadOptions(),o=n.USER_ID;if(e)return void a.log("Service","Error parsing cloud data: "+e);if(s.setValue("CLOUD_DATA_"+o,{activeCloud:t,numClouds:i}),!t)return n.CLOUD_INFO={switchingEnabled:i>1},void this._loadCollectionWithOptions(n);const r=t.features&&t.features.libraries,c=t.features&&t.features.files&&t.features.files.sync&&t.features.files.sync.uri,l=r&&r.storage&&r.storage.uri,h=r&&r.service&&r.service.uri,_=r&&r.view&&r.view.uri;return l?h?(n.CLOUD_ID=t.id,n.STORAGE_HOSTNAME=d.stripProtocolPrefix(l),n.CC_LIBRARY_SERVICE_HOSTNAME=d.stripProtocolPrefix(h),n.CLOUD_INFO={name:t.name,parameters:t.parameters,switchingEnabled:i>1,viewURI:d.stripProtocolPrefix(_),syncURI:c,useJumpToken:!1},void this._loadCollectionWithOptions(n)):(a.log("Service","Unexpected cloud data: expected features.libraries.service.uri to be defined"),void this._analytics.reportError("UnexpectedCloudData","expected features.libraries.service.uri to be defined")):(a.log("Service","Unexpected cloud data: expected features.libraries.storage.uri to be defined"),void this._analytics.reportError("UnexpectedCloudData","expected features.libraries.storage.uri to be defined"))}_loadCollections(e,t,i,n){if(this._hasLoadedCollections)return;const o=this._authentication.getUserId();o&&(this._hasLoadedCollections=!0,this._setAnalyticsState(!!s.getValue(`ANALYTICS_ENABLED_${o}`)),this._thorInterface.getAnalyticsState(),e?this._loadCollectionsFromCloud(t,i,n):this._authentication.hasEntitlement("cce_private",e=>{if(a.log("Service","cc_private entitlement: "+e),!0===e)this._endpoint.getActiveCloud((e,t,i)=>{this._loadCollectionsFromCloud(e,t,i),this._analytics.reportEvent("getActiveCloud",{error:String(e),cloudId:t&&t.id,numClouds:i,cce_private:!0})});else if(!1===e)this._loadCollectionsFromCloud(null),this._endpoint.getActiveCloud((e,t,i)=>{this._analytics.reportEvent("getActiveCloud",{error:String(e),cloudId:t&&t.id,numClouds:i,cce_private:!1})});else{const e=s.getValue("CLOUD_DATA_"+o);this._loadCollectionsFromCloud(null,e&&e.activeCloud,e&&e.numClouds),this._analytics.reportEvent("getActiveCloud",{error:"UnknownEntitlement: could not determine cce_private entitlement",cloudId:e&&e.activeCloud&&e.activeCloud.id,numClouds:e&&e.numClouds})}}))}_unloadCollections(){this._ccLibraries.getLoadedCollections().forEach(e=>this._ccLibraries.unloadLibraryCollection(e)),this._libraryListeners={},this._hasLoadedCollections=!1,delete this._platformSessionAndDocument,this._setAnalyticsState(!1),this._productBridge.collectionsUnloaded()}}},function(e,t,i){const n=i(4),o=i(14),r=i(1),s=i(0),a=i(5),c=/^\/content\/assets\/[^/]+$/,l=e=>{const t="application/vnd.adobecloud.directory+json"===e["dc:format"],i="ACTIVE"===e["repo:state"],n=e["repo:name"];return t&&i&&!s.getValue("TEAM_HIDDEN_FOLDERS").includes(n)},h=e=>{const t=s.getValue("PLATFORM_ROOT_DOCUMENT_VERSION"),i=s.getValue(`PLATFORM_ROOT_DOCUMENT_${s.getEnvironment().LABEL}`),n=s.getValue(`PLATFORM_ROOT_DOCUMENT_VERSION_${s.getEnvironment().LABEL}`),o=s.getValue(`PLATFORM_ROOT_DOCUMENT_EXPIRES_AT_${s.getEnvironment().LABEL}`),r=!e&&o&&Date.now()>=o;if(i&&i._links&&n===t&&!r)return i},d=e=>new Promise((t,i)=>{const n=h();if(n)return e.setRootDocument(n),t(n);e.getRootDocument((e,n)=>{if(e)return i(e);(e=>{const t=s.getValue("PLATFORM_ROOT_DOCUMENT_VERSION");s.setValue(`PLATFORM_ROOT_DOCUMENT_${s.getEnvironment().LABEL}`,e),s.setValue(`PLATFORM_ROOT_DOCUMENT_VERSION_${s.getEnvironment().LABEL}`,t),s.setValue(`PLATFORM_ROOT_DOCUMENT_EXPIRES_AT_${s.getEnvironment().LABEL}`,Date.now()+s.getValue("PLATFORM_ROOT_DOCUMENT_TTL"))})(n),t(n)})}),_={getTeamsFromAssetsResponse(e,t){const i=[];return t.children.forEach(t=>{const n=t._embedded&&t._embedded[o.METADATA],s=t._embedded&&t._embedded[o.REPOSITORY];if(!n||!s)throw new r(r.INVALID_DATA,`Malformed ACP-CS index entry: ${e}`);const h=l(n),d=c.test(n["repo:path"]),_="org"===s["repo:owner"].type&&s["repo:owner"].id===e,p=[];h||p.push(`Not visible: repo:state=${n["repo:state"]} dc:format=${n["dc:format"]}`),d||p.push(`Not top level: repo:path=${n["repo:path"]}`),_||p.push(`Not in org: repo:owner(type)=${s["repo:owner"].type} repo:owner(id)= ${s["repo:owner"].id}`),0===p.length?i.push({id:n["repo:assetId"]||n["repo:id"],orgId:s["repo:owner"].id,name:n["repo:name"],links:n._links}):a.log(`Omitting ${n["repo:name"]} from team list: ${p.join(", ")}`)}),i},getRootLinksFromAssetsResponse(e,t){const i=t.children.find(t=>{const i=t._embedded&&t._embedded[o.METADATA],n=t._embedded&&t._embedded[o.REPOSITORY];return!(!i||!n)&&("/"===i["repo:path"]&&n["repo:owner"]&&"org"===n["repo:owner"].type&&n["repo:owner"].id===e)});return i&&i._embedded[o.METADATA]._links},getRepository:e=>new Promise((t,i)=>{e.getRepositories((e,n)=>{if(e)return i(e);const o=n&&n["repo:home"];if(!o)return i(new r(r.INVALID_DATA,"Repository not returned in response."));o["repo:repositoryId"]=o["repo:owner"].id,t(o)})})};e.exports={getCachedRootDocument:h,getRootDocument:d,getTeamsFromAssetsResponse:_.getTeamsFromAssetsResponse,getRootLinksFromAssetsResponse:_.getRootLinksFromAssetsResponse,getRepository:_.getRepository,navigateToRepoPath:(e,t,i)=>new Promise((r,s)=>{e.getLinksFromPath(t,i,(t,i)=>{if(t)return s(t);const a=n.getUrlFromLinks(i,o.ID);e.getCollection(a,void 0,(e,t)=>e?s(e):r(t))})}),isVisibleFolder:l,TOP_LEVEL_FOLDER_PATH:"/content/assets",_postBetaUtils:{getRootDocument:d,getTeamsFromAssetsResponse:(e,t)=>{const i=[];return t.children.forEach(t=>{l(t)&&c.test(t["repo:path"])&&t["repo:repositoryId"]===e&&i.push({id:t["repo:assetId"],orgId:t["repo:repositoryId"],name:t["repo:name"],links:t._links})}),i},getRootLinksFromAssetsResponse:(e,t)=>{const i=t.children.find(t=>"/"===t["repo:path"]&&t["repo:repositoryId"]===e);return i&&i._links},getRepository:e=>new Promise((t,i)=>{e.getRepositories((e,n)=>{if(e)return i(e);t(n&&n.children&&n.children.find(e=>"org"===e["repo:owner"].type))})})}}},function(e,t,i){const n=i(5),o=i(3),r=i(12);e.exports=class{constructor(){this._listenerManager=new o(void 0,e=>n.log("Vulcan",e)),n.log("Vulcan","Loading Vulcan Library...");const e=i(72);this._vulcan=new e.VulcanAdapter("LIBS","1.0.0"),this._vulcanControl=new e.VulcanControlAdapter,n.log("Vulcan","Vulcan Library Successfully Loaded"),this._vulcan.addMessageListener((e,t,i,o)=>{e=e.replace(r.VULCAN_PREFIX,""),this._listenerManager.hasListeners(e)&&(n.log("Vulcan","<- "+i+" "+o+": "+e),this._listenerManager.notify(e,[t,i,o]))}),this.isAppInstalled=this._vulcanControl.isAppInstalled.bind(this._vulcanControl),this.getSpecifiers=this._vulcanControl.getSpecifiers.bind(this._vulcanControl),this.getAppPath=this._vulcanControl.getAppPath.bind(this._vulcanControl),this.isAppRunning=this._vulcanControl.isAppRunning.bind(this._vulcanControl),this.getAppVersion=this._vulcanControl.getAppVersion.bind(this._vulcanControl),this.launchApp=this._vulcanControl.launchApp.bind(this._vulcanControl)}sendMessage(e,t,i,o){const r=i?i+" "+(o||"*"):"BROADCAST";n.log("Vulcan","-> "+r+": "+e),this._vulcan.sendMessage(e,t||"",i||"",o||"")}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}call(e,t){let i,o,r=!1;const s=(n,s)=>{r||!1!==t(n,s)&&(r=!0,clearTimeout(i),this._listenerManager.remove(e.responseType,o))},a=()=>{n.log("Vulcan","Timed out on "+e.responseType),s("timeout")};o=e=>s(null,e),this._listenerManager.add(e.responseType,o),e.timeout&&(i=setTimeout(a,e.timeout)),this.sendMessage(e.requestType,e.payload,e.targetId,e.targetVersion)}}},function(e,t){e.exports=require("node-vulcanjs")},function(e,t,i){const n=i(0),o=i(5),r=i(32),s=i(33),a=i(74),c=i(12),l=i(3);e.exports=class{constructor(e,t,i){this._ccLibraries=e,this._authentication=t,this._vulcan=i,this._listenerManager=new l(["syncBegin","syncEnd"],e=>o.log("ProductBridge",e)),this._pendingChangeDiffs={},this._lookupFilePath=n.getValue("ROOT_DIR")+"librarylookupfile"}_clearReleaseTimer(){this._releaseTimer&&(clearTimeout(this._releaseTimer),this._releaseTimer=null)}_setReleaseTimer(){this._clearReleaseTimer(),this._releaseTimer=setTimeout(()=>{this._releaseTimer=null,this._librariesLookupMap=null,o.log("ProductBridge","Released lookup file")},n.getValue("PRODUCT_BRIDGE_INMEMORY_LIFETIME"))}_obtainLock(e){r.isLocked("ProductBridgeLock")||this._listenerManager.notify("syncBegin",[]),r.obtainLock("ProductBridgeLock",e)}_releaseLock(){r.releaseLock("ProductBridgeLock"),r.isLocked("ProductBridgeLock")||this._listenerManager.notify("syncEnd",[])}_hasPendingRequest(){return r.hasPendingRequest("ProductBridgeLock")}_flushPendingChangeDiffs(){if(0!==Object.keys(this._pendingChangeDiffs).length){const e=this._isPendingChangeLocal?c.VULCAN_LIBRARY_CHANGED_LOCAL_TYPE:c.VULCAN_LIBRARY_CHANGED_REMOTE_TYPE,t=JSON.stringify(this._pendingChangeDiffs);this._vulcan.sendMessage(e,t),this._pendingChangeDiffs={},this._isPendingChangeLocal=null}}_ignorePendingChangeDiffs(){this._pendingChangeDiffs={},this._isPendingChangeLocal=null}_addPendingChangeDiff(e,t,i){0!==Object.keys(this._pendingChangeDiffs).length&&(this._pendingChangeDiffs[e]||this._isPendingChangeLocal!==i)&&this._flushPendingChangeDiffs(),this._pendingChangeDiffs[e]=t,this._isPendingChangeLocal=i}_clearLookupMap(e){this._clearReleaseTimer(),o.log("ProductBridge","Deleting lookup file"),a.deleteLookupMap(this._lookupFilePath,t=>{t&&o.log("ProductBridge",t.toString()),this._librariesLookupMap=null,o.log("ProductBridge","Lookup file deleted"),e()})}_setLookupMap(e,t,i){this._clearReleaseTimer(),o.log("ProductBridge","Saving lookup file"),e.userId=this._authentication.getUserId(),a.saveLookupMap(this._lookupFilePath,e,n=>{if(n)return o.log("ProductBridge",n.toString()),this._librariesLookupMap=null,void i();this._librariesLookupMap=e,this._setReleaseTimer(),t?this._vulcan.sendMessage(c.VULCAN_COLLECTIONS_LOADED_TYPE):this._hasPendingRequest()||this._flushPendingChangeDiffs(),o.log("ProductBridge","Lookup file saved"),o.log("ProductBridge","Lookup library count: "+Object.keys(this._librariesLookupMap.libraries).length),i()})}_getLookupMap(e){if(this._librariesLookupMap)return e(this._librariesLookupMap);o.log("ProductBridge","Reading lookup file"),a.readLookupMap(this._lookupFilePath,(t,i)=>{if(t)return o.log("ProductBridge",t),void e(null);o.log("ProductBridge","Lookup file read"),this._librariesLookupMap=i,e(this._librariesLookupMap)})}_updateReceived(e,t,i){o.log("ProductBridge","Update Callback Received"),this._obtainLock(()=>this._getLookupMap(n=>{if(!n)return this._releaseLock(),void this.collectionsLoaded();const o=e&&e.library,r=o&&n.libraries[o.id],s=r&&r.elements[e.id];if(s&&a.updateElementLookupData(s,t)){s.mod=a.getElementModifiedTime(e);const t={name:o.name,domain:o._collection._syncManager.getElementRefDomain(),path:o._collection._syncManager.getElementRefPath(),elements:{}};return t.elements[e.id]=s,this._addPendingChangeDiff(o.id,t,i),void this._setLookupMap(n,!1,()=>this._releaseLock())}this._hasPendingRequest()||this._flushPendingChangeDiffs(),this._releaseLock()}))}collectionsLoaded(){o.log("ProductBridge","Collections Loaded"),this._obtainLock(()=>{this._ignorePendingChangeDiffs();const e=this._ccLibraries.getLoadedCollections(),t={elementTypes:n.getValue("PRODUCT_BRIDGE_ELEMENT_TYPES")||[],libraries:{}};e&&e.forEach(e=>{e.libraries.forEach(e=>{t.libraries[e.id]=a.buildLibraryLookupData(e,this._updateReceived.bind(this))})}),this._collectionsLoaded=!0,this._setLookupMap(t,!0,()=>this._releaseLock())})}collectionsUnloaded(){o.log("ProductBridge","Collections Unloaded"),this._obtainLock(()=>this._clearLookupMap(()=>{this._collectionsLoaded=!1,this._vulcan.sendMessage(c.VULCAN_COLLECTIONS_UNLOADED_TYPE),this._releaseLock()}))}libraryChanged(e,t){this._collectionsLoaded&&(o.log("ProductBridge","Library Changed - "+(t?"Local":"Remote")+": "+e.id),this._obtainLock(()=>this._getLookupMap(i=>{if(!i)return this._releaseLock(),void this.collectionsLoaded();const n=i.libraries[e.id],o=(e,i)=>this._updateReceived(e,i,t);let r,c=!1;if(n){r={elements:{}},n.name!==e.name&&(n.name=e.name,c=!0);const t=e.elements.filter(e=>a.shouldIncludeInLookupData(e)).map(e=>{const t=n.elements[e.id];let i,l=!t||t.mod!==a.getElementModifiedTime(e)||t.stockLicense!==s.getElementStockLicense(e);if(!l){const n=t.reps.filter(e=>!e.path).map(e=>e.id);n.length>0&&(i=a.buildElementLookupData(e,o),l=i.reps.some(e=>e.path&&n.includes(e.id)))}return l&&(i=i||a.buildElementLookupData(e,o),r.elements[e.id]=i,n.elements[e.id]=i,c=!0),e.id});Object.keys(n.elements).forEach(e=>{t.includes(e)||(r.elements[e]=null,delete n.elements[e],c=!0)})}else{const t=a.buildLibraryLookupData(e,o);r=t,i.libraries[e.id]=t,c=!0}if(!c)return this._hasPendingRequest()||this._flushPendingChangeDiffs(),void this._releaseLock();r.name=e.name,r.domain=e._collection._syncManager.getElementRefDomain(),r.path=e._collection._syncManager.getElementRefPath(),this._addPendingChangeDiff(e.id,r,t),this._setLookupMap(i,!1,()=>this._releaseLock())})))}libraryDeleted(e){this._collectionsLoaded&&(o.log("ProductBridge","Library Deleted: "+e),this._obtainLock(()=>{this._flushPendingChangeDiffs(),this._getLookupMap(t=>{if(!t)return this._releaseLock(),void this.collectionsLoaded();delete t.libraries[e],this._setLookupMap(t,!1,()=>{this._releaseLock(),this._vulcan.sendMessage(c.VULCAN_LIBRARY_DELETED_TYPE,e)})})}))}renditionChanged(e){if(!this._collectionsLoaded)return;const t=this._librariesLookupMap,i=t&&t.libraries[e.library.id],n=i&&i.elements[e.id];if(n&&n.hasManualLink){const t=a.buildElementLookupData(e);this._updateReceived(e,t,!0)}}isSyncing(){return this._hasPendingRequest()||r.isLocked("ProductBridgeLock")}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}}},function(e,t,i){const n=i(19),o=i(7),r=i(0),s=i(33),a={_uuid:()=>o(),normalizePath:function(e){return r.isPlatformWindows()&&e?e.replace(/\//g,"\\"):e},getElementModifiedTime:function(e){let t=!1;return e._forEachRepresentation((function(e){!e.isExternalLink||e.getCachedContentPath()||e.getCachedExternalLinkError()||(t=!0)})),t?e.modified-1:e.modified},updateElementLookupData:function(e,t){let i=!1;return Array.isArray(t.reps)&&t.reps.forEach(t=>{i=e.reps.some((function(i,n){if(i.id===t.id&&i.path!==t.path)return e.reps[n]=t,!0}))||i}),void 0!==t.stockLicense&&t.stockLicense!==e.stockLicense&&(i=!0,e.stockLicense=t.stockLicense,null===e.stockLicense&&delete e.stockLicense),i},buildElementLookupData:function(e,t){const i=e.modified,n={name:e.name,type:r.getValue("PRODUCT_BRIDGE_ELEMENT_TYPES").indexOf(e.type),mod:a.getElementModifiedTime(e),reps:[]},o=s.getElementStockId(e),c=s.getElementStockLicense(e);if(o&&(n.stockId=o),c&&(n.stockLicense=c),e.wasModifiedLocally&&(n.local=!0),e.representations.forEach(o=>{if(!o.isCompatibleType(o.type))return;const r={id:o.id};"primary"===o.relationship?n.reps.unshift(r):n.reps.push(r);const c=o.getCachedContentPath(),l=o.isExternalLink&&o.getCachedExternalLinkError();return c||l?(r.type=o.type,void(c&&(r.path=a.normalizePath(c)))):o.isExternalLink&&!e._config.shouldPrefetchExternalLink(o)?(n.hasManualLink=!0,void(t&&o.testExternalLink(()=>{if(s.getElementStockLicense(e)!==n.stockLicense){const i=s.getElementStockLicense(e)||null;t(e,{stockLicense:i})}}))):void o.getContentPath((r,c)=>{if(c){const n={reps:[{id:o.id,type:o.type,path:a.normalizePath(c)}]},r=s.getElementStockLicense(e);r&&(n.stockLicense=r),i===e.modified&&t&&t(e,n)}else o.isExternalLink&&s.getElementStockLicense(e)!==n.stockLicense&&t&&t(e,{stockLicense:s.getElementStockLicense(e)||null})})}),e._config.shouldPrefetchFullRendition(e)){n.reps.push({id:"FULL_RENDITION"});let o=!0;e.getThumbnailPath(void 0,(function(r,s){if(s){const r={id:"FULL_RENDITION",type:"image/png",path:a.normalizePath(s)};o?a.updateElementLookupData(n,{reps:[r]}):i===e.modified&&t(e,{reps:[r]})}})),o=!1}return n},buildLibraryLookupData:function(e,t){const i={name:e.name,domain:e._collection._syncManager.getElementRefDomain(),path:e._collection._syncManager.getElementRefPath(),elements:{}};return e.elements.forEach(e=>{a.shouldIncludeInLookupData(e)&&(i.elements[e.id]=a.buildElementLookupData(e,t))}),i},saveLookupMap:function(e,t,i){const o=e+".TEMP_"+a._uuid();n.writeFile(o,JSON.stringify(t),(function(t){t?i(t):n.rename(o,e,(function(e){i(e)}))}))},readLookupMap:function(e,t){n.exists(e,(function(i){i?n.readFile(e,"utf8",(function(e,i){try{i=i&&JSON.parse(i)}catch(t){i=void 0,e=t}t(e,i)})):t(null)}))},deleteLookupMap:function(e,t){n.exists(e,(function(i){i?n.unlink(e,(function(e){t(e)})):t(null)}))},shouldIncludeInLookupData:function(e){return-1!==(r.getValue("PRODUCT_BRIDGE_ELEMENT_TYPES")||[]).indexOf(e.type)}};e.exports=a},function(e,t,i){var n=i(0),o=i(76),r=i(12);e.exports=class{constructor(e,t){this._vulcan=e,this._proxy=t,this._diagnose=new o(t),this._vulcan.addListener(r.VULCAN_SHUTDOWN_REQUEST,this._onShutdown.bind(this)),this._vulcan.addListener(r.VULCAN_QUERY_REQUEST,this._onPortQuery.bind(this)),this._vulcan.addListener(r.VULCAN_PROXY_QUERY_REQUEST,this._onProxyQuery.bind(this));t.addListener("change",()=>{this._vulcan.sendMessage(r.VULCAN_PROXY_CHANGE_MESSAGE,"","","")})}_onShutdown(){this._shutdownListener?this._shutdownListener():process.exit(0)}_onPortQuery(e,t,i){this._diagnose.perform(e=>{var o={port:n.getValue("SERVICE_PORT"),token:n.getValue("SERVICE_TOKEN")};e&&(o.portdiagnosis=e),n.setValue("SERVICE_LAST_QUERY_TIME",Date.now()),this._vulcan.sendMessage(r.VULCAN_QUERY_RESPONSE,JSON.stringify(o),t,i)})}_onProxyQuery(e,t,i){var n={};try{n=JSON.parse(e)}catch(e){}var o={requestId:n.requestId};if(!n.url||"string"!=typeof n.url)return o.err="url parameter must be specified, and must be a string",void this._vulcan.sendMessage(r.VULCAN_PROXY_QUERY_RESPONSE,JSON.stringify(o),t,i);this._proxy.getProxyForURL(n.url,(e,n)=>{if(e)o.err=e;else{var s=this._proxy.getProxyCredentials();o.proxyHost=n.hostname,o.proxyPort=n.port,o.proxyUser=s.user,o.proxyPassword=s.password}this._vulcan.sendMessage(r.VULCAN_PROXY_QUERY_RESPONSE,JSON.stringify(o),t,i)})}setShutdownListener(e){this._shutdownListener=e}sendStartupMessage(){this._vulcan.sendMessage(r.VULCAN_STARTUP_MESSAGE,"","","")}}},function(e,t,i){const n=i(77),o=i(0),r=i(30),s=i(5),a=i(34),c={WORKING:"WORKING",DNS_RESOLUTION_FAILED:"DNS_RESOLUTION_FAILED",SIMPLE_HOSTNAME_GOING_TO_PROXY:"SIMPLE_HOSTNAME_GOING_TO_PROXY",COULD_NOT_CONNECT_SOCKET:"COULD_NOT_CONNECT_SOCKET"};e.exports=class{constructor(e){this._proxy=e}_doDNSCheck(){return new Promise((function(e,t){n.lookup("localhost",(function(i,n){"127.0.0.1"!==n?(s.log("DIAGNOSTICS","Expected localhost to resolve to 127.0.0.1, but instead it resolved to "+n),t(c.DNS_RESOLUTION_FAILED,i,n)):e()}))}))}_verifySocketConnection(){return new Promise((e,t)=>{const i=a.format({protocol:"ws",host:"localhost:"+o.getValue("SERVICE_PORT")+"/",slashes:!0,query:{diagnostics:!0,token:o.getValue("SERVICE_TOKEN")}}),n=new r(i,{origin:"file://"});n.on("error",e=>t(c.COULD_NOT_CONNECT_SOCKET,e)),n.on("open",()=>{n.close(),e()})})}_checkExcludeLocalhost(){return new Promise((e,t)=>{this._proxy.isLocalhostProxied((i,n)=>!0===n?t(c.SIMPLE_HOSTNAME_GOING_TO_PROXY):e())})}perform(e){this._doDNSCheck().then(()=>this._checkExcludeLocalhost()).then(()=>this._verifySocketConnection()).then(()=>e(c.WORKING)).catch(t=>{s.log("DIAGNOSTICS",t),e(t)})}get RESULTS(){return c}}},function(e,t){e.exports=require("dns")},function(e,t,i){const n=i(1),o=i(3),r=i(0),s=i(5),a=i(7),c=i(31),l=["creative_cloud","cce_private"],h=(e,t)=>{if(t)return t.some(t=>e.includes(t.serviceCode)&&"CLOSED"!==t.serviceStatus)},d=(e,t)=>{e.forEach(e=>{try{e.apply(void 0,t)}catch(e){s.log("NGL","Error in callback: "+e)}})};e.exports=class{constructor(){this._listenerManager=new o(["change"]),this._pendingGetAccessTokenCallbacks=[],this._pendingSAOListCallbacks=[],this._env=r.getEnvironment(),this._log("Loading NGL Library..."),this._NGLLib=i(79),this._deviceId=r.getValue("DEVICE_ID"),this._deviceId||(this._deviceId=a(),r.setValue("DEVICE_ID",this._deviceId)),this._log("NGLLib Successfully Loaded"),this._nglInitializedPromise=new Promise(e=>{this._onNglInitialized=e}),this._initializeProfileUpdates()}get _waitForNglInitialized(){const e=new Promise((e,t)=>setTimeout(()=>t("timeout"),r.getValue("NGL_INITIALIZE_TIMEOUT")));return Promise.race([e,this._nglInitializedPromise])}_log(e){s.log("NGL",e)}_setUserProfile(e){delete this._userProfile;try{this._userProfile=JSON.parse(e)}catch(e){this._log(`Error parsing NGL profile: ${e}`)}const t=this._userProfile&&this._userProfile.UserProfile&&this._userProfile.UserProfile.userId,i=t!==this._userId;i&&(this._clearUserId(),this._log(t?`Default User: ${this._userProfile.UserProfile.email} (${t})`:"No user logged in."),this._userId=t),this._userId&&(this._fetchingSAOList=!0,this.getAccessToken((e,t,i)=>{this._SAOList=i&&i.serviceAccounts,this._fetchingSAOList=!1;const n=this._pendingSAOListCallbacks;this._pendingSAOListCallbacks=[],d(n,[])})),i&&this._listenerManager.notify("change")}_initializeProfileUpdates(){const{userProfile:e}=this._NGLLib.InitializeProfileUpdates(this._getDefaultNglParams(),(e,t)=>{this._onNglInitialized(),this._setUserProfile(t)});this._setUserProfile(e)}_getDefaultNglParams(){const e="Staging"===this._env.LABEL,t=r.getValue("SCOPES"),[i,n]=c.version.split(".");return{clientName:"CCLibrary1",clientId:this._env.CLIENT_ID,clientSecret:this._env.CLIENT_SECRET,clientScope:t,clientVersion:`${i}.${n}`,clientLocale:"en_US",isStage:e}}_getImsAccessToken(e,t){this._waitForNglInitialized.then(()=>this._NGLLib.GetImsAccessToken(e,t),e=>t(e))}_clearUserId(){this._userId=void 0,this._SAOList=void 0,this._accessTokenCache=void 0;const e=this._pendingGetAccessTokenCallbacks;this._pendingGetAccessTokenCallbacks=[];const t=this._pendingSAOListCallbacks;this._pendingSAOListCallbacks=[],d(t,[]),d(e,[null])}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}removeAllListeners(){this._listenerManager.removeAll("change")}getDeviceId(){return this._deviceId}getUserId(){return this._userId}getAccessToken(e,t){if("function"==typeof e&&(t=e,e=void 0),!this._userId)return void t(null,void 0);if(this._accessTokenCache&&Date.now()<this._accessTokenCache.expires){const i=this._accessTokenCache.response.access_token;if(!(e&&i&&e===i))return void t(null,this._accessTokenCache.response.access_token,this._accessTokenCache.response);if(this._badTokenRefetchTime&&Date.now()<this._badTokenRefetchTime)return delete this._accessTokenCache.response.access_token,this._accessTokenCache.expires=this._badTokenRefetchTime,void t(null);this._badTokenRefetchTime=Date.now()+r.getValue("ACCESS_TOKEN_CACHE_DURATION")}if(this._pendingGetAccessTokenCallbacks.push(t),this._pendingGetAccessTokenCallbacks.length>1)return;this._accessTokenCache=void 0;const i=this._userId;this._log("Started NGLLib.GetImsAccessToken"),this._getImsAccessToken(this._getDefaultNglParams(),(e,t)=>{if(this._log("Finished NGLLib.GetImsAccessToken"),this._userId!==i)return void this._log("User logged out during fetch access token - aborting");const o=(e,t,i)=>{const n=this._pendingGetAccessTokenCallbacks;this._pendingGetAccessTokenCallbacks=[],d(n,[e,t,i])};let s;try{s=JSON.parse(t)}catch(e){return this._log("Error parsing Json in getImsAccessToken callback. "+e),void o(null)}if(!e&&!h(l,s.serviceAccounts)||315===e)return this._log("Services not provisioned"),void o(new n(n.ACCESS_DENIED,"services not provisioned"),void 0,s);e?this._log("Unknown Error: "+e):this._log("Successfully obtained access token"),this._accessTokenCache={response:s,expires:Date.now()+r.getValue("ACCESS_TOKEN_CACHE_DURATION")},o(null,s.access_token,s)})}getClientAccessToken(e,t,i,o,r){if(!this._userId||e!==this._userId)return void r(new n(n.ACCESS_DENIED,"user mismatch"));const s=Object.assign({},this._getDefaultNglParams(),{clientId:t,clientSecret:i,clientScope:o});this._log(`Started NGLLib.GetImsAccessToken for ${t}`),this._getImsAccessToken(s,(e,i)=>{if(this._log(`Finished NGLLib.GetImsAccessToken for ${t}`),e)return this._log("Error : "+e),void r(new n(n.ACCESS_DENIED,"error obtaining access token from IMS"));let o;try{const{access_token:e,expires_in:t}=JSON.parse(i);o={access_token:e,expires_in:t}}catch(e){this._log("Error parsing Json in getAccessToken. "+e)}r(null,o)})}hasEntitlement(e,t){const i=()=>{const i=h([e],this._SAOList);t(i)};this._fetchingSAOList?this._pendingSAOListCallbacks.push(i):i()}getUserProfile(){return this._userProfile&&this._userProfile.UserProfile}}},function(e,t){e.exports=require("node-ngl")},function(e,t,i){const n=i(7),o=i(5),r=i(13),s=i(0),a=i(3),c=(e,t)=>{if(e){const i=new RegExp("<"+t+"[^<>]*>([^<>]*)</"+t+">",""),n=e.match(i);return n&&n[1]}return null};e.exports=class{constructor(e,t,i){this._analytics=e,this._vulcan=t,this._proxy=i,this._listenerManager=new a(["proxySettingsChanged","installApplication","uninstallApplication","updateApplication","analyticsStateChanged"],e=>o.log("Thor",e)),this._vulcan.addListener("any.accc.app.ProductDeploymentEvent",this._onProductDeployment.bind(this)),this._vulcan.addListener("any.accc.app.ProxySettingsChanged",this._onProxySettingsChanged.bind(this)),this._vulcan.addListener("any.accc.app.UserContextData",this._onAnalyticsStateChanged.bind(this))}_uuid(){return n()}_constructMessage(e){return e.replace("{{uuid}}",this._uuid())}_getAnalyticsEnabled(e){const t=r.parseXML(e),i=t&&t["feature-response"]&&t["feature-response"]["feature-entry"];if(!i)return o.log("Thor",`Failed to parse user feature XML: ${e}`),!1;const n=i.find(e=>e&&e.$&&"com.adobe.oobe.acc.v1.piip.user.status"===e.$.id),s=n&&n.$&&n.$.state;return o.log("Thor",`Obtained analytics state from Thor: ${s}`),"OptedIn"===s}_onProductDeployment(e){const t={productCode:(i=c(e,"productCode"),"PHSP"===i?"PHXS":i),productVersion:c(e,"productVersion"),productLanguage:c(e,"productLanguage"),countryCode:c(e,"countryCode"),subscriptionStatus:c(e,"subscriptionStatus")};var i;switch(c(e,"eventType")){case"Install":this._listenerManager.notify("installApplication",[t]);break;case"Uninstall":this._listenerManager.notify("uninstallApplication",[t]);break;case"Update":this._listenerManager.notify("updateApplication",[t])}}_onProxySettingsChanged(e){const t=c(e,"proxyuser"),i=c(e,"proxypassword");null!==t&&null!==i&&this._listenerManager.notify("proxySettingsChanged",[t,i])}_onAnalyticsStateChanged(e){const t=this._getAnalyticsEnabled(e);this._listenerManager.notify("analyticsStateChanged",[t])}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}removeAllListeners(e){this._listenerManager.removeAll(e)}getProxyCredentials(e){this._proxy.getProxyForURL("https://adobe.com",(t,i)=>{if(!i||!i.hostname)return void e(null,null);const n={requestType:"accc.app.ProxySettingsRequest",responseType:"accc.app.ProxySettingsResponse",payload:this._constructMessage('<?xml version="1.0" encoding="utf-8"?><request><type>accc.app.ProxySettingsRequest</type><request_id>{{uuid}}</request_id></request>'),targetId:"ADCS",targetVersion:"",timeout:s.getValue("PROXY_REQUEST_TIMEOUT")};this._vulcan.call(n,(t,i)=>{if(t)return this._analytics.reportError("GetProxySettingsError","timed out getting proxy settings from Thor"),void e(null,null);const n=c(i,"proxyuser"),o=c(i,"proxypassword");this._analytics.reportEvent("getProxySettings",{isAuthenticatingProxy:!!n}),e(n,o)})})}configureFileSyncing(e,t=(()=>{})){const i=()=>{const i=e?'<?xml version="1.0" encoding="utf-8"?><request><sync>on</sync><request-id>{{uuid}}</request-id></request>':'<?xml version="1.0" encoding="utf-8"?><request><sync>off</sync><request-id>{{uuid}}</request-id></request>',n={requestType:"accc.files.setFilesSyncStatusRequest",responseType:"adbproduct.files.setFilesSyncStatusResponse",payload:this._constructMessage(i),targetId:"ADCS",targetVersion:"",timeout:s.getValue("CONFIGURE_SYNC_TIMEOUT")};this._vulcan.call(n,e=>{e&&this._analytics.reportError("ConfigureFileSyncError","timed out turning on/off file sync via Thor"),t(e)})};this._vulcan.isAppRunning("creativecloud")?i():this._vulcan.launchApp("creativecloud",!1,"--showwindow=false",()=>{setTimeout(i,s.getValue("THOR_LAUNCH_WAIT"))})}getAnalyticsState(e=(()=>{}),t=0){const i={requestType:"accc.app.UserContextDataRequest",responseType:"adbproduct.app.UserContextDataResponse",payload:this._constructMessage('<?xml version="1.0" encoding="utf-8"?><request><request-id>{{uuid}}</request-id></request>'),targetId:"ADCS",targetVersion:"",timeout:s.getValue("ANALYTICS_STATE_REQUEST_TIMEOUT")};this._vulcan.call(i,(i,n)=>{if(i)return o.log("Thor","Error getting analytics opt-in state from Thor"),void(t<s.getValue("ANALYTICS_STATE_REQUEST_MAX_RETRIES")?setTimeout(()=>this.getAnalyticsState(e,t+1),s.getValue("ANALYTICS_STATE_REQUEST_RETRY_INTERVAL")):e(!1));const a=r.parseXML(n),c=a&&a.response;if(!c)return o.log("Thor",`Invalid analytics opt-in state response from Thor: ${n}`),void e(!1);const l=c.error&&c.error[0];if(l)return l&&l.$&&"SignInPending"===l.$.id?o.log("Thor","User sign in pending. Analytics flag not received yet."):o.log("Thor",`Error fetching analytics opt-in state: ${JSON.stringify(l)}`),void e(!1);const h=this._getAnalyticsEnabled(c.UserfeatureXML&&c.UserfeatureXML[0]);this._listenerManager.notify("analyticsStateChanged",[h]),e(h)})}}},function(e,t,i){const n=i(5),o=i(13),r=i(0),s=i(3),a=i(12),c={job:"files"},l={filterjob:"files",observe:{attrs:'type="sync.out.notify.job.status"'}},h={changemonitor:"cclibraries"},d={changemonitor:"cclibraries",pathprefix:[a.STORAGE_ASSETS_PATH+a.LIBRARY_SYNC_GROUP,...a.BOOKMARKS_MONITOR_PATHS]},_={filterchangemonitor:"cclibraries"},p=new RegExp(".*/([^/]+)/manifest$"),u=new RegExp(".*/([^/]+)$"),m=e=>e.userId+"/"+e.cloudId,g=e=>{let t="";return Object.keys(e).forEach(i=>{const n=e[i];n.attrs?t+="<"+i+" "+n.attrs+" />":Array.isArray(n)?n.forEach(e=>{t+="<"+i+">"+e+"</"+i+">"}):t+="<"+i+">"+n+"</"+i+">"}),'<?xml version="1.0" encoding="utf-8"?><message>'+t+"</message>"},f=e=>{const t=o.parseXML(e,e=>n.log("CoreSyncNotifications",e)),i=t&&t.message||{};Object.keys(i).forEach(e=>{i[e]=i[e][0]});const r=i.events&&i.events.event;r&&(i.events=[],r.forEach(e=>{i.events.push(e.$)}));const s=i.errors&&i.errors.error;return s&&(delete i.errors,i.numErrors=s.length,i.firstError=s[0]&&s[0].$),i};e.exports=class{constructor(e,t){this._ccLibraries=e,this._vulcan=t,this._listenerManager=new s(["libraryChange","bookmarkChange","fileSyncState"],e=>n.log("CoreSyncNotifications",e)),this._changeMonitors={},this._pendingConfigureCallbacks=[],this._isCoreSyncRunning=!0,this._ccLibraries.addLoadedCollectionsListener(()=>this._configureMonitoredCollections()),this._vulcan.addListener("sync.out.broadcast.app.startedup",this._onStartedUp.bind(this)),this._vulcan.addListener("sync.out.broadcast.app.shuttingdown",this._onShuttingDown.bind(this)),this._vulcan.addListener("sync.out.notify.job.status",this._onJobStatus.bind(this)),this._vulcan.addListener("sync.out.notify.changemonitor.status",this._onChangeMonitorStatus.bind(this)),this._vulcan.addListener("sync.out.notify.changemonitor.pathevent",this._onChangeMonitorPathEvent.bind(this))}_callCoreSync(e,t,i,o,s){s=s||0;const c=this._ccLibraries._services.uuid(),l="sync.in.request."+t,h="sync.out.response."+t,d=JSON.parse(JSON.stringify(i));var _;e&&(d.userid=e.userId,d.cloudid=(_=e.cloudId)===a.DEFAULT_CLOUD_ID?a.DEFAULT_CORESYNC_CLOUD_ID:_),d.requestid=c,d.type=l;const p={requestType:l,responseType:h,payload:g(d),targetId:"CORS",targetVersion:"",timeout:r.getValue("CORE_SYNC_REQUEST_TIMEOUT")};this._vulcan.call(p,(a,l)=>{if(a)return void(s<r.getValue("CORE_SYNC_NUM_RETRIES")?this._callCoreSync(e,t,i,o,s+1):o(a));const h=f(l);if(!h||h.requestid!==c)return!1;n.log("CoreSyncNotifications",t+":\n"+JSON.stringify(h,void 0,2)),o(null,h)})}_clearMonitors(){this._fileSyncState=void 0,this._syncJobObserverId=void 0,this._changeMonitors={}}_configureMonitoredCollections(e=(()=>{}),t=0){if(this._pendingConfigureCallbacks.push(e),this._pendingConfigureCallbacks.length>1)return;const i=e=>{const i=this._pendingConfigureCallbacks;this._pendingConfigureCallbacks=[],i.forEach(t=>t(e)),e?e&&!this._scheduledConfigure&&t<r.getValue("CORE_SYNC_NUM_RETRIES")&&(this._scheduledConfigure=setTimeout(()=>this._configureMonitoredCollections(void 0,t+1),r.getValue("CORE_SYNC_REQUEST_TIMEOUT"))):clearTimeout(this._scheduledConfigure)};if(!this._isCoreSyncRunning)return this._clearMonitors(),void i(null);const n=[];if(Object.keys(this._changeMonitors).forEach(e=>{const t=this._changeMonitors[e];this._ccLibraries.getLoadedCollectionById(t.userId,t.cloudId)||(delete this._changeMonitors[e],n.push(e=>this._stopCollectionMonitor(t,e)))}),this._ccLibraries.getLoadedCollections().forEach(e=>{if(!e.isPrivate)return;const t=m(e);if(this._changeMonitors[t])this._changeMonitors[t].isEnabled?"stopped"===this._changeMonitors[t].state&&"normal"===this._fileSyncState&&n.push(e=>this._startCollectionMonitor(this._changeMonitors[t],e)):n.push(e=>this._startCollectionMonitor(this._changeMonitors[t],e));else{const i={userId:e.userId,cloudId:e.cloudId,syncurl:e.cloudInfo&&e.cloudInfo.syncURI};n.push(e=>{this._startCollectionMonitor(i,n=>{n||(this._changeMonitors[t]=i),e(n)})})}}),!this._syncJobObserverId){n.push(e=>{this._createObserver(l,(t,i)=>{t?e(t):(this._syncJobObserverId=i,e(null))})});const e=this._ccLibraries.getLoadedCollections()[0];e&&n.push(t=>this._queryFileSyncState(e,t))}Promise.all(n.map(e=>new Promise((t,i)=>e(e=>e?i(e):t())))).then(()=>i(null),i)}_handleFileSyncStateMessage(e,t){const i=!!t&&void 0===t.status;e||!t?this._fileSyncState=String(e):"disabled"===t.majorstate||"does_not_exist"===t.status?this._fileSyncState="turned_off":"syncing"===t.majorstate||"idle"===t.majorstate?this._fileSyncState="normal":this._fileSyncState="error_"+(t.status||t.majorstate),this._listenerManager.notify("fileSyncState",[this._fileSyncState,i])}_queryFileSyncState(e,t){this._callCoreSync(e,"job.getstatus",c,(e,i)=>{this._handleFileSyncStateMessage(e,i),t(e)})}_enableChangeMonitor(e,t){this._callCoreSync(e,"changemonitor.enable",h,(e,i)=>{if(e)return void t(e);const o=i&&i.status;"success"===o?t(null):(n.log("CoreSyncNotifications","Error enabling changemonitor: "+o),t("enable_error"))})}_createChangeMonitor(e,t){this._callCoreSync(e,"changemonitor.getstatus",h,(i,o)=>{if(i)return void t(i);const r=o&&o.status;if("does_not_exist"===r){const i=Object.assign({},d);e.cloudId!==a.DEFAULT_CLOUD_ID&&(i.syncurl=e.syncurl),this._callCoreSync(e,"changemonitor.create",i,(i,o)=>{if(i)return void t(i);const r=o&&o.status;"success"===r?this._enableChangeMonitor(e,t):(n.log("CoreSyncNotifications","Error creating changemonitor: "+r),t("create_error"))})}else"success"===r?"active"===o.majorstate?t(null):this._enableChangeMonitor(e,t):(n.log("CoreSyncNotifications","Unexpected changemonitor status: "+r),t("status_error"))})}_destroyChangeMonitor(e,t){this._callCoreSync(e,"changemonitor.destroy",h,(e,i)=>{if(e)return void t(e);const o=i&&i.status;"success"===o?t(null):(n.log("CoreSyncNotifications","Error destroying changemonitor: "+o),t("destroy_error"))})}_createObserver(e,t){this._callCoreSync(void 0,"observer.create",e,(e,i)=>{if(e)return void t(e);const o=i&&i.status;"success"===o?t(null,i.observerid):(n.log("CoreSyncNotifications","Error creating observer: "+o),t("create_error"))})}_destroyObserver(e,t){const i={observerid:e};this._callCoreSync(void 0,"observer.destroy",i,(e,i)=>{if(e)return void t(e);const o=i&&i.status;"success"===o?t(null):(n.log("CoreSyncNotifications","Error destroying observer: "+o),t("destroy_error"))})}_startCollectionMonitor(e,t){this._createChangeMonitor(e,i=>{i?t(i):(e.isEnabled=!0,e.observerId?t(null):this._createObserver(_,(i,n)=>{i?t(i):(e.observerId=n,t(null))}))})}_stopCollectionMonitor(e,t){this._destroyObserver(e.observerId,()=>{delete e.observerId,this._destroyChangeMonitor(e,t)})}_onStartedUp(){this._clearMonitors(),this._isCoreSyncRunning=!0,this._configureMonitoredCollections()}_onShuttingDown(){this._listenerManager.notify("fileSyncState",["shutdown",!0]),this._isCoreSyncRunning=!1,this._configureMonitoredCollections()}_onJobStatus(e){const t=f(e);n.log("CoreSyncNotifications","sync.out.notify.job.status:\n"+JSON.stringify(t,void 0,2)),this._handleFileSyncStateMessage(null,t),this._configureMonitoredCollections()}_onChangeMonitorStatus(e){const t=f(e);n.log("CoreSyncNotifications","sync.out.notify.changemonitor.status:\n"+JSON.stringify(t,void 0,2));const i=m({userId:t.userid,cloudId:(o=t.cloudid,o===a.DEFAULT_CORESYNC_CLOUD_ID?a.DEFAULT_CLOUD_ID:o)});var o;this._changeMonitors[i]&&(this._changeMonitors[i].state=t.majorstate,"disabled"===t.majorstate&&(n.log("CoreSyncNotifications","Change monitor was disabled - need to re-enable"),this._changeMonitors[i].isEnabled=!1,this._configureMonitoredCollections()))}_onChangeMonitorPathEvent(e){const t=f(e),i={};let o=!1;const r=t.events||[],s={};r.forEach(e=>{e&&(s[e.type]=s[e.type]||0,s[e.type]++)});const c=Object.keys(s).map(e=>`${e}: ${s[e]}`).join(", ");n.log("CoreSyncNotifications",`sync.out.notify.changemonitor.pathevent: ${c||"no events"}`),r.forEach(e=>{if(!e)return;if(a.BOOKMARKS_MONITOR_PATHS.includes(e.path))return void(o=!0);const t=e.path&&e.path.match(p);if(t)return void(i[t[1]]=!0);const n=e.path&&e.path.match(u);"deleted"===e.type&&"folder"===e.file_type&&n&&(i[n[1]]=!0)});const l=Object.keys(i);l.length>0&&(n.log("CoreSyncNotifications","Report library change"),this._listenerManager.notify("libraryChange",[l])),o&&(n.log("CoreSyncNotifications","Report bookmark change"),this._listenerManager.notify("bookmarkChange",[]))}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}removeAllListeners(e){this._listenerManager.removeAll(e)}ping(e){this._configureMonitoredCollections(e)}}},function(e,t,i){const n=i(7),o=i(0),r=i(5),s=i(13),a=i(3),c=i(8),l={"com.adobe.designlibrary.v1":["sharing.invite","sharing.invite.accept.self","sharing.invite.accept.other","sharing.collaboration.updaterole","stock.open.request"],"com.adobe.system.inform.typekit.generic":["com.adobe.system.inform.typekit.generic.entitlementschanged"]},h=Object.keys(l).reduce((e,t)=>e.concat(l[t]),[]),d=(e,t)=>e&&e[t]&&e[t][0],_=(e,t)=>e&&e[t]||[];e.exports=class{constructor(e,t){this._analytics=e,this._vulcan=t,this._listenerManager=new a(h,e=>r.log("ANS",e)),t.addListener("cclibraries.notification.ans",this._onNotification.bind(this))}_uuid(){return n()}_parseXML(e){return s.parseXML(e,t=>{r.log("ANS",t),this._analytics.reportError("ANS","Failed to parse ANS message: "+e)})}_getNotificationDataByIDs(e,t){const i=this._uuid(),n={NOTIFICATION_IDS:e.map(e=>"<notification-id>"+e+"</notification-id>").join(""),REQUEST_ID:i,REQUEST_NAMESPACE:"cclibraries.notification.ans.byID.data"},s={requestType:"accc.notifications",responseType:"cclibraries.notification.ans.byID.data",payload:c.constructStringFromTemplate('<?xml version="1.0" encoding="utf-8"?><NEMessage action="GetDataByID"><notification-ids>{{NOTIFICATION_IDS}}</notification-ids><request-context>{{REQUEST_ID}}</request-context><requestor-namespace>{{REQUEST_NAMESPACE}}</requestor-namespace></NEMessage>',n),targetId:"ADCS",targetVersion:"",timeout:o.getValue("GET_NOTIFICATION_TIMEOUT")};this._vulcan.call(s,(e,n)=>{if(e)return"timeout"===e&&(r.log("ANS","Timed out getting notification data from Thor"),this._analytics.reportError("ANS","Timed out getting notification data from Thor")),void t(e);if(!n)return void t(null,[]);const o=this._parseXML(n),s=o&&o.notifications;if(d(s,"request-context")!==i)return!1;const a=_(s,"notification").map(e=>{const t=d(e,"notification-id");let i=d(e,"payload");try{i=i&&JSON.parse(i)}catch(t){r.log("ANS","Failed to parse ANS payload: "+e.payload),this._analytics.reportError("ANS","Failed to parse ANS payload: "+e.payload)}return{id:t,payload:i,state:d(e,"state"),created:parseInt(d(e,"timestamp"),10),modified:parseInt(d(e,"modifiedTimeStamp"),10)}});t(null,a)})}_onNotification(e){const t=this._parseXML(e),i=t&&t["notifications-signal"],n=i&&i["notification-signal"];n&&n.forEach(e=>{const t=e.$&&e.$["sub-type"];if(r.log("ANS","Received notification: "+t),-1!==h.indexOf(t)){const i=_(e,"notification-info").reduce((e,t)=>{const i=d(t,"notification-ids");return e.concat(_(i,"notification-id"))},[]);this._getNotificationDataByIDs(i,(e,i)=>{e||i.forEach(e=>this._listenerManager.notify(t,[e]))})}})}_registerANSNotifications(e){const t={NOTIFICATION_TYPE:Object.keys(l).find(t=>l[t].includes(e)),NOTIFICATION_SUB_TYPE:e,OBSERVER_NAMESPACE:"cclibraries.notification.ans"};this._vulcan.sendMessage("accc.notifications",c.constructStringFromTemplate('<?xml version="1.0" encoding="utf-8"?><NEMessage action="RegisterObserver"><type>{{NOTIFICATION_TYPE}}</type><sub-type>{{NOTIFICATION_SUB_TYPE}}</sub-type><observer-namespace>{{OBSERVER_NAMESPACE}}</observer-namespace></NEMessage>',t),"ADCS","")}get EVENTS(){return l}addListener(e,t){this._listenerManager.hasListeners(e)||this._registerANSNotifications(e),this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}removeAllListeners(e){this._listenerManager.removeAll(e)}setState(e){const t={NOTIFICATION_ID:e.id,STATE:e.state};this._vulcan.sendMessage("accc.notifications",c.constructStringFromTemplate('<?xml version="1.0" encoding="utf-8"?><NEMessage action="UpdateServerNotification"><notification><notification-id>{{NOTIFICATION_ID}}</notification-id><state>{{STATE}}</state></notification></NEMessage>',t),"ADCS","")}}},function(e,t,i){const n=i(7),o=i(29),r=i(0),s=i(3),a={GetActiveCloudRequest:"accc.app.GetActiveCloudRequest",GetActiveCloudResponse:"any.app.GetActiveCloudResponse",UpdateActiveCloud:"any.accc.app.UpdateActiveCloud",SuiteMessage:"vulcan.SuiteMessage."},c=(e,t)=>{o.parseString(e,(e,i)=>{if(e)return void t("Error parsing XML response: "+e);let n=i&&i.response&&i.response.clouds&&i.response.clouds[0];n=n||i&&i.message&&i.message.clouds&&i.message.clouds[0];const o=n&&n.$&&n.$.activeCloud,r=n&&n.$&&n.$.trueCloudCount&&parseInt(n.$.trueCloudCount,10),s=n&&n._;if(!o)return void t("Invalid response from any.app.GetActiveCloudResponse");let a=[];if(s)try{const e=Buffer.from(s,"base64");a=JSON.parse(e.toString())}catch(e){}t(null,a,o,r)})};e.exports=class{constructor(e){this._vulcan=e,this._listenerManager=new s(["cloudChange"]),this._vulcan.addListener(a.UpdateActiveCloud,this._onUpdateActiveCloud.bind(this))}_uuid(){return n()}_buildGetActiveCloudPayload(){return"<request><type>"+a.GetActiveCloudRequest+"</type><requestid>"+this._uuid()+"</requestid></request>"}_onUpdateActiveCloud(e){c(e,(e,t,i,n)=>{if(e)return void this._listenerManager.notify("cloudChange",[e]);const o=t.find(e=>e.id===i);this._listenerManager.notify("cloudChange",[e,o,n])})}getClouds(e){let t;const i=setTimeout(()=>{this._vulcan.removeListener(a.GetActiveCloudResponse,t),e("GetActiveCloud timed out after "+r.getValue("GET_ACTIVE_CLOUD_TIMEOUT")+"ms")},r.getValue("GET_ACTIVE_CLOUD_TIMEOUT"));t=n=>{clearTimeout(i),c(n,e),this._vulcan.removeListener(a.GetActiveCloudResponse,t)},this._vulcan.addListener(a.GetActiveCloudResponse,t),this._vulcan.sendMessage(a.GetActiveCloudRequest,this._buildGetActiveCloudPayload(),"ADCS","1.9.0")}getActiveCloud(e){this.getClouds((t,i,n,o)=>{if(t)return void e(t);const r=i.find(e=>e.id===n);e(null,r,o)})}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}removeAllListeners(e){this._listenerManager.removeAll(e)}}},function(e,t,i){const n=i(20),o=i(7),r=i(85),s=i(0),a=i(5),c=i(31);e.exports=class{constructor(e,t,i){this._ccLibraries=e,this._authentication=t,this._proxy=i,this._previousErrors=[]}get _ingest(){if(!this._ingestInstance){const e={ENVIRONMENT:"Staging"===s.getEnvironment().LABEL?"stage":"prod",ANALYTICS_API_KEY:s.getEnvironment().CLIENT_ID,ANALYTICS_X_PRODUCT:"CCLibraryProcess/"+c.version,ANALYTICS_PROJECT:s.getValue("ANALYTICS_PROJECT"),ANALYTICS_INGEST_TYPE:s.getValue("ANALYTICS_INGEST_TYPE"),ANALYTICS_MAX_QUEUED_EVENTS:s.getValue("MAX_QUEUED_ANALYTICS"),ANALYTICS_DEBOUNCE:s.getValue("ANALYTICS_DEBOUNCE"),ANALYTICS_USER_REGION:"US"},t={getAccessToken:e=>this._authentication.getAccessToken(e),getAgent:(e,t)=>{const i=this._proxy.getNodeTunnelOptionsForURL(e);t(null,i&&i.agent)},log:e=>a.log("Analytics",e)};this._ingestInstance=new r(t,e),this._ingestInstance.enable(this._ccLibraries.getOption("ANALYTICS_ENABLED"))}return this._ingestInstance}_isNewError(e){return-1===this._previousErrors.indexOf(e)&&(this._previousErrors.length===s.getValue("ANALYTICS_ERROR_HISTORY")&&this._previousErrors.shift(),this._previousErrors.push(e),!0)}_updateDefaults(e){const t=this._ccLibraries.getLoadedCollections(),i={"event.guid":o(),"event.user_guid":this._authentication.getUserId(),"event.category":"Library-Process","event.type":"info","event.dts_end":(new Date).toISOString(),"event.cloud_id":t&&t.length>0?t[0].cloudId:"","source.client_id":s.getEnvironment().CLIENT_ID,"source.version":c.version,"source.platform":n.platform()};return Object.keys(e).forEach(t=>{-1===t.indexOf(".")?i["ccxlp."+t]=e[t]:i[t]=e[t]}),i}_postEvent(e,t,i){this._ingest.postEvent(e,i),t&&this._ingest.flush(!0)}reportEvent(e,t,i,n){t=Object.assign({"event.type":"info","event.subtype":e},t||{}),t=this._updateDefaults(t),this._postEvent(t,i,n)}reportError(e,t,i,n){const o=e+": "+(t||"");if(this._isNewError(o)){const t=this._updateDefaults({"event.type":"error","event.error_type":e,"event.error_desc":o});this._postEvent(t,i,n)}else n&&n(null,0)}setEnabled(e){this._ingest.enable(e)}}},function(e,t,i){"use strict";function n(e,t){var i=e.toString();if(i.length<t){var n=[];n.length=t-i.length+1,i=n.join("0")+i}return i}function o(e,t){return Object.getOwnPropertyNames(t).forEach((function(i){if("object"==typeof t[i])"object"!=typeof e[i]&&(e[i]={}),o(e[i],t[i]);else{var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n)}})),e}function r(e,t,i){e.forEach((function(e){setTimeout((function(){e(t,i)}))}))}var s={prod:"cc-api-data.adobe.io",stage:"cc-api-data-stage.adobe.io",dev:"cc-api-data-dev.adobe.io"},a={ENVIRONMENT:"prod",ALLOW_NO_TOKEN:!1,ANALYTICS_INGEST_TYPE:"dunamis",ANALYTICS_MAX_QUEUED_EVENTS:50,ANALYTICS_DEBOUNCE:1e4,ANALYTICS_API_KEY:null,ANALYTICS_X_PRODUCT:null,ANALYTICS_X_PRODUCT_LOCATION:void 0,ANALYTICS_PROJECT:null,ANALYTICS_USER_REGION:"UNKNOWN",TIMESTAMP_PROPERTY_NAME:"event.dts_end"},c=["ANALYTICS_API_KEY","ANALYTICS_X_PRODUCT","ANALYTICS_PROJECT"];function l(e,t){var i=this;e=e||{},t=t||{};var n=function(e){throw i._log(e),new Error("ERROR: "+e)};this._queuedEvents=[],this._queuedCallbacks=[],this._lastSendTime=0,this._isEnabled=!1,this._dependencies=o({},e),e.getAccessToken&&"function"==typeof e.getAccessToken||n("Missing dependency: getAccessToken"),this._options={},Object.keys(a).forEach((function(e){this._options[e]=t[e]||a[e]}),this),c.forEach((function(e){this._options[e]||n("Missing option: "+e)}),this)}l.prototype._log=function(e){var t=this._dependencies.log;t&&t("Ingest :: "+e)},l.prototype._getAgent=function(e,t){this._dependencies.getAgent?this._dependencies.getAgent(e,t):t(null,{})},l.prototype._getAccessToken=function(e){this._dependencies.getAccessToken(e)},l.prototype._clearAccessToken=function(){this._dependencies.clearAccessToken&&this._dependencies.clearAccessToken()},l.prototype._getEnvironment=function(){return s[this._options.ENVIRONMENT]?this._options.ENVIRONMENT:"prod"},l.prototype._getAnalyticsHost=function(){return s[this._getEnvironment()]},l.prototype._formatTimestamp=function(e){var t=e.getFullYear(),i=n(e.getMonth()+1,2),o=n(e.getDate(),2),r=n(e.getHours(),2),s=n(e.getMinutes(),2),a=n(e.getSeconds(),2),c=n(e.getMilliseconds(),3),l=e.getTimezoneOffset(),h=l<0?"+":"-",d=Math.floor(Math.abs(l)/60),_=Math.abs(l)%60;return t+"-"+i+"-"+o+"T"+r+":"+s+":"+a+"."+c+(h+n(d,2)+n(_,2))},l.prototype._updateDebounce=function(e){var t=e&&(e["retry-after"]||e["Retry-After"]),i=0;if(t){var n;try{n=parseInt(t,10)}catch(e){}if(n)i=Math.max(0,n);else{var o=Date.parse(t);if(o){var r=(new Date).valueOf();i=Math.max(0,o-r)/1e3+Math.floor(10*Math.random())}}}this._options.ANALYTICS_DEBOUNCE=Math.max(1e3*i,this._options.ANALYTICS_DEBOUNCE)},l.prototype._queueEvent=function(e){this._queuedEvents.length>=this._options.ANALYTICS_MAX_QUEUED_EVENTS&&this._queuedEvents.shift(),this._queuedEvents.push(e)},l.prototype._requeueEvents=function(e){this._queuedEvents=e.concat(this._queuedEvents),this._queuedEvents=function(e,t){var i=e;if(e&&e.length>t&&t>0){var n=e.length-t;i=e.slice(n,e.length)}return i}(this._queuedEvents,this._options.ANALYTICS_MAX_QUEUED_EVENTS)},l.prototype._sendAnalytics=function(e,t,n){var s=this;if(n=n||0,t&&this._queuedCallbacks.push(t),!this._isEnabled||0===this._queuedEvents.length){var a=this._queuedCallbacks;return this._queuedCallbacks=[],void(this._isEnabled?r(a,null,0):r(a,new Error("Analytics Disabled")))}var c=this._options.ANALYTICS_DEBOUNCE;if(e&&(c=0,clearTimeout(this._pendingSendAnalyticsTimeout),this._pendingSendAnalyticsTimeout=void 0),this._sendingEvents||this._pendingSendAnalyticsTimeout)this._log("Queued "+this._queuedEvents.length+" events to be sent.");else{var l=(new Date).valueOf();if(l-this._lastSendTime<c)this._pendingSendAnalyticsTimeout=setTimeout((function(){s._pendingSendAnalyticsTimeout=void 0,s._sendAnalytics()}),c);else{this._lastSendTime=l,this._sendingEvents=this._queuedEvents,this._sendingCallbacks=this._queuedCallbacks,this._queuedEvents=[],this._queuedCallbacks=[];var h,d=(h=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)})()+h()+"-"+h()+"-"+h()+"-"+h()+"-"+h()+h()+h(),_="["+d+"] ",p={events:this._sendingEvents},u=function(e){var t=s._queuedEvents?s._queuedEvents.length:0;if(s._sendingEvents){var i=s._sendingEvents.length;e?(s._requeueEvents(s._sendingEvents),s._log(_+"Error sending "+i+" events: "+e)):s._log(_+"Success sending "+i+" events: "+JSON.stringify(s._sendingEvents)),delete s._sendingEvents;var n=s._sendingCallbacks;delete s._sendingCallbacks,e?r(n,e):r(n,null,i)}t>0&&s._sendAnalytics()},m=function(e,t){if(s._updateDebounce(t),401===e&&0===n)return s._clearAccessToken(),s._requeueEvents(s._sendingEvents),delete s._sendingEvents,s._queuedCallbacks=s._sendingCallbacks.concat(s._queuedCallbacks),delete s._sendingCallbacks,s._log(_+"Access token is expired. Retry one more time."),void s._sendAnalytics(!0,void 0,n+1);200===e?u():u(new Error("Unexpected Response: "+e))};this._getAccessToken((function(e,t){if(!e||s._options.ALLOW_NO_TOKEN)if(t&&0!==t.length||s._options.ALLOW_NO_TOKEN){var n,r,a="https://"+s._getAnalyticsHost();if(s._log(_+"Sending analytics to "+a+"/ingest"),"undefined"!=typeof global&&global.Buffer){var c={"x-api-key":s._options.ANALYTICS_API_KEY,"X-Product":s._options.ANALYTICS_X_PRODUCT,"X-Request-Id":d,"Content-Type":"application/json"};t&&(c.Authorization="Bearer "+t);var l={hostname:s._getAnalyticsHost(),port:443,path:"/ingest",method:"POST",headers:c};s._options.ANALYTICS_X_PRODUCT_LOCATION&&(l.headers["X-Product-Location"]=s._options.ANALYTICS_X_PRODUCT_LOCATION),s._getAgent(a,(function(e,t){t&&t.agent?l.agent=t&&t.agent:o(l,t||{});var n=i(24).request(l,(function(e){var t,i;e&&(i=function(){},(t=e).on("data",i),t.on("end",i));var n=e&&e.statusCode,o=e&&e.headers;m(n,o)}));n.once("error",(function(e){u(e)})),n.end(JSON.stringify(p))}))}else{var h=JSON.stringify(p);n=h,(r=new XMLHttpRequest).onreadystatechange=function(){if(4===this.readyState){var e=r.getAllResponseHeaders();m(this.status,e)}},r.onerror=function(e){u(new Error(e))},r.open("POST",a+"/ingest",!0),r.setRequestHeader("x-api-key",s._options.ANALYTICS_API_KEY),r.setRequestHeader("x-user-region",s._options.ANALYTICS_USER_REGION),r.setRequestHeader("Content-Type","application/json"),t&&r.setRequestHeader("Authorization","Bearer "+t),r.setRequestHeader("X-Product",s._options.ANALYTICS_X_PRODUCT),r.setRequestHeader("X-Product-Location",s._options.ANALYTICS_X_PRODUCT_LOCATION),r.setRequestHeader("X-Request-Id",d),r.send(n)}}else u(new Error("No access token"));else u(e)}))}}},l.prototype.enable=function(e){this._isEnabled=e,e&&this._sendAnalytics(!0)},l.prototype.postEvent=function(e,t,i){var n=i||{},o="event.dts_start",s="event.coll_dts",a=n.TIMESTAMP_PROPERTY_NAME||this._options.TIMESTAMP_PROPERTY_NAME,c=n.ANALYTICS_PROJECT||this._options.ANALYTICS_PROJECT,l=n.ANALYTICS_INGEST_TYPE||this._options.ANALYTICS_INGEST_TYPE;e[s]&&e[s]instanceof Date&&(e[s]=this._formatTimestamp(e[s])),e[o]&&e[o]instanceof Date&&(e[o]=this._formatTimestamp(e[o])),e[a]||(e[a]=this._formatTimestamp(new Date)),e[a]instanceof Date&&(e[a]=this._formatTimestamp(e[a]));var h={time:e[a],project:c,environment:this._getEnvironment(),ingesttype:l,data:e};e.simulate?(this._log("event sim:"+JSON.stringify(h)),t&&r([t],null,0)):(this._queueEvent(h),this._sendAnalytics(!1,t))},l.prototype.flush=function(e,t){this._sendAnalytics(e,t)},e.exports=l},function(e,t,i){const n=i(5),o=i(3),r=i(87);e.exports=class{constructor(){this._nodeTunnelOptionsCache={},this._listenerManager=new o(["change","error"],e=>n.log("Proxy",e)),this._lastCredentials={},this._proxyResolver=i(88)((e,t)=>{0===e&&this._listenerManager.notify("error",[t]),n.log("Proxy",t)}),this._proxyResolver.on("change",this._onProxySettingsChange.bind(this)),this._proxyResolver.setAuthenticationCallback(this._onProxyAuthentication.bind(this))}_onProxySettingsChange(){n.log("Proxy","System proxy settings changed"),this._updateAllNodeTunnelOptions(),this._listenerManager.notify("change",[!0])}_onProxyAuthentication(e,t){const i=this._lastCredentials[e.proxy.host+e.proxy.port]||{};i.username===this._proxyUser&&i.password===this._proxyPassword?t("No new credentials"):this._proxyUser?(i.username=this._proxyUser,i.password=this._proxyPassword,t(null,i),this._lastCredentials[e.proxy.host+e.proxy.port]=i):t("No credentials present")}_updateNodeTunnelOptions(e,t){this._resolveProxyURL(e,(i,o)=>{delete t.agent,t.agent=o&&o.agent,t.agent?(n.log("Proxy","Setting proxy for "+e+": "+o.hostname+":"+o.port+(this._proxyUser?" with":" without")+" authentication"),this._cachedCAs&&this._cachedCAs.length>0&&(t.agent.options=t.agent.options||{},t.agent.options.ca=this._cachedCAs)):n.log("Proxy","No proxy (direct connection) for "+e)})}_updateAllNodeTunnelOptions(){Object.keys(this._nodeTunnelOptionsCache).forEach(e=>{this._updateNodeTunnelOptions(e,this._nodeTunnelOptionsCache[e])})}_resolveProxyURL(e,t){this._proxyResolver.resolve(e,(e,i)=>{e?t(e):t(null,i&&i[0])})}isLocalhostProxied(e){this._proxyResolver.isLocalhostProxiedUnderHttp(e)}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}removeAllListeners(e){this._listenerManager.removeAll(e)}getProxyForURL(e,t){this._resolveProxyURL(e,t)}getNodeTunnelOptionsForURL(e){if(!this._nodeTunnelOptionsCache[e]){const t={};this._nodeTunnelOptionsCache[e]=t,this._updateNodeTunnelOptions(e,t)}return this._nodeTunnelOptionsCache[e]}fetch(e,t={}){const i=Object.assign({},t,this.getNodeTunnelOptionsForURL(e));return r(e,i)}setProxyCredentials(e,t){this._proxyUser===e&&this._proxyPassword===t||(n.log("Proxy","Setting proxy username and password"),this._proxyUser=e,this._proxyPassword=t,this._updateAllNodeTunnelOptions(),this._listenerManager.notify("change",[!1]))}getProxyCredentials(){return{user:this._proxyUser,password:this._proxyPassword}}getRootCA(e){this._proxyResolver.getRootCA(e)}getOSLocale(){return this._proxyResolver.getOSLocale()}start(){return new Promise(e=>{this._proxyResolver.getRootCA((t,i)=>{t&&n.log("Proxy",`Error fetching system certificates: ${t}`),this._cachedCAs=i||[],e()})})}}},function(e,t){e.exports=require("node-fetch")},function(e,t){e.exports=require("node-ProxyResolver")},function(e,t,i){const n=i(7),o=i(0),r=i(5),s=i(13),a=i(12),c=i(8),l=i(9);e.exports=class{constructor(e,t,i){this._ccLibraries=e,this._analytics=t,this._vulcan=i,this._launchCallbacks={},this._productMap=o.getValue("PRODUCT_LAUNCHER_SUPPORTED_PRODUCTS")}_sendRequest(e,t,i,n,s,a){if(this._vulcan.sendMessage(t,i,e.code,e.version),!n)return void a(null);let c;const l=(t,i,o)=>{r.log("ProductLauncher",`Received accept from : ${i}, ${o}: ${t}`),s(t)?(clearTimeout(c),this._vulcan.removeListener(n,l,e.code,e.version),a(null)):r.log("ProductLauncher","Response didn't match request")};r.log("ProductLauncher",`Sending open request: ${i}`),this._vulcan.addListener(n,l),c=setTimeout(()=>{this._vulcan.removeListener(n,l,e.code,e.version),a("APP_SEND_ACTION_FAILED")},o.getValue("SEND_ACTION_TIMEOUT"))}_sendAction(e,t){const i=e.specifierInfo;if(!e.element)return void t(null,i);if(!e.action)return void t("NO_ACTION_SPECIFIED");if(!e.element._getActions(e.action).some(t=>t.appCode===e.specifierInfo.code)){const t=e.element.getPrimaryRepresentation(),n=e.element.type+":"+(t&&t.type),o="Unexpectedly trying to ["+e.action+"] "+n+" in "+i.code;r.log("ProductLauncher","Error: "+o),this._analytics.reportError("ElementActionConfigMismatch",o)}const o={elementRef:e.element.getReference(),requestID:n(),appCode:i.code,path:i.path,action:e.action},s=a.VULCAN_APP_SEND_ACTION_MESSAGE,c=a.VULCAN_APP_ACTION_ACCEPTED_MESSAGE;this._sendRequest(i,s,JSON.stringify(o),c,e=>e===o.requestID,e=>{e?t(e):t(null,i)})}_getAppStatus(e){return e?e.isUnsupported?(r.log("ProductLauncher","Unsupported version "+e.version),"NO_COMPATIBLE_VERSION"):"USABLE":(r.log("ProductLauncher","App not installed "+e),"APP_NOT_INSTALLED")}_launchApp(e,t){let i=e.specifier;if(i.startsWith("adobedesktopservice")){const t=this.getAppDetails({appCode:"ACCC"});t&&e.isAlreadyRunning&&t.isAlreadyRunning&&(i=t.specifier)}this._vulcan.launchApp(i,!0,"",t)}_doLaunch(e,t,i,n){const s=e.specifier;if(e.isAlreadyRunning)return r.log("ProductLauncher","Switching focus to app: "+s),void this._launchApp(e,n);if(this._launchCallbacks[s]=this._launchCallbacks[s]||[],this._launchCallbacks[s].push(n),this._launchCallbacks[s].length>1)return;const a=e=>{const t=this._launchCallbacks[s];delete this._launchCallbacks[s],t.forEach(t=>t(e))};let c;const l=(e,n,o)=>{i(e,n,o)&&(clearInterval(c),this._vulcan.removeListener(t,l),a())};this._vulcan.addListener(t,l);const h=(e,i)=>{clearInterval(c),this._vulcan.removeListener(t,l),r.log("ProductLauncher",i),a(e)},d=Date.now();c=setInterval(()=>{Date.now()-d>o.getValue("LAUNCH_APP_TIMEOUT")?h("APP_LAUNCH_TIMEOUT","Launch app timed out: "+s):this._vulcan.isAppRunning(s)||h("APP_LAUNCH_FAILED","App was killed before it finished launching: "+s)},o.getValue("LAUNCH_APP_POLL_INTERVAL")),r.log("ProductLauncher","Launching app: "+s),this._launchApp(e,(e,t)=>{(e||!0!==t)&&h("APP_LAUNCH_FAILED","Vulcan could not launch app: "+s+" "+e)})}getAppDetails(e){const t=[];return this._ccLibraries._config.ELEMENT_ACTION_PRODUCT_MAP.installedApps.forEach(i=>{if(i.code!==e.appCode)return;const n={};Object.assign(n,i),-1===c.compareVersions(e.minVersion||0,n.version)?n.isUnsupported=!0:n.isAlreadyRunning=this._vulcan.isAppRunning(n.specifier),t.push(n)}),t.sort((t,i)=>{if(!1!==e.prioritizeRunning){if(t.isAlreadyRunning&&!i.isAlreadyRunning)return-1;if(i.isAlreadyRunning&&!t.isAlreadyRunning)return 1}return c.compareVersions(t.version,i.version)}),r.log("ProductLauncher","Installed app details: "+JSON.stringify(t)),t[0]}appStatus(e){return this._getAppStatus(this.getAppDetails(e))}launch(e,t=(()=>{})){const i=this.getAppDetails(e),n=this._getAppStatus(i);if(e.specifierInfo=i,"USABLE"!==n)return void t(n);this._doLaunch(i,a.VULCAN_APP_READY_MESSAGE,(e,t,n)=>{let o={};try{o=JSON.parse(e)}catch(i){return r.log("ProductLauncher","Unparsable payload received from "+t+" "+n,e),!1}return l.normalize(o.path)===l.normalize(i.path)||(r.log("ProductLauncher","Received unknown app ready: "+e+" from "+t+" "+n+", specifier - "+JSON.stringify(i)),!1)},i=>i?t(i):this._sendAction(e,t))}launchCCD(e,t=(()=>{})){const i=this.getAppDetails({appCode:"ADCS"});this._doLaunch(i,"any.adcs.app.StartedUp",()=>!0,o=>{if(o||!e)return void t(o);const r=n(),a=`<data><workflow>routeToPath</workflow><requestID>${r}</requestID><path>${e}</path></data>`;this._sendRequest(i,"accc.app.deepLink.request",a,"accc.app.deepLink.response",e=>{const t=s.parseXML(e),i=t&&t.data&&t.data.originalPayload,n=i&&i[0]&&i[0].data&&i[0].data[0],o=n&&n.requestID&&n.requestID[0];return r===o},t)})}updateInstallationMap(e){const t=this._vulcan.getSpecifiers();r.log("ProductLauncher","Received the list of installed apps: "+t.join(", "));const i=this._ccLibraries._config.ELEMENT_ACTION_PRODUCT_MAP.installedApps||[],n={};i.forEach(e=>{n[e.specifier]=e});const o=[];return t.forEach(t=>{if(n[t]&&!e)return void o.push(n[t]);const i=t.split("-");if(2===i.length){const e=this._productMap[i[0]];if(!e)return;const n=this._vulcan.getAppPath(t);if(!n)return void r.log("ProductLauncher","No application path for specifier: "+t);const s=this._vulcan.getAppVersion(t);if(!s)return void r.log("ProductLauncher","No application version for specifier: "+t+" at "+n+" ("+s+")");o.push({specifier:t,code:e,version:s,path:l.normalize(n)})}else r.log("ProductLauncher","Unexpected app specifier structure: "+t)}),this._ccLibraries._config.ELEMENT_ACTION_PRODUCT_MAP.installedApps=o,r.log("ProductLauncher","Updated installation map: ",JSON.stringify(o)),o}}},function(e,t,i){const n=i(7),o=i(5),r=i(13),s=i(0),a=i(3),c=i(8);e.exports=class{constructor(e){this._vulcan=e,this._handlers={},this._messageQueue=[],this._listenerManager=new a(["clickNotification"],e=>o.log("Toast",e)),this._vulcan.addListener("cclibrary.app.ShowNotificationResponse",this._onToastNotificationResponse.bind(this))}_onToastNotificationResponse(e){const t=r.parseXML(e);let i,n,s,a;try{s=t.response.requestid[0],a=t.response.context[0],n=JSON.parse(a),i=n.type}catch(t){o.log("Toast","Failed to parse, notification response "+e)}this._listenerManager.hasListeners("clickNotification")&&this._listenerManager.notify("clickNotification",[i,s,n.data])}_processMessageQueue(e){if(this._pendingProcessMessageQueue)return;if(e)return void(this._pendingProcessMessageQueue=setTimeout(()=>{this._pendingProcessMessageQueue=void 0,this._processMessageQueue()},e));if(0===this._messageQueue.length)return;const t=this._messageQueue.shift(),i=c.constructStringFromTemplate('<?xml version="1.0" encoding="utf-8"?><request><requestid>{{REQUEST_ID}}</requestid><context>{{CONTEXT}}</context><ackNamespace>cclibrary.app.ShowNotificationResponse</ackNamespace><title>{{TITLE}}</title><message>{{MESSAGE}}</message></request>',t);this._vulcan.sendMessage("accc.app.ShowNotificationRequest",i,"ADCS",""),this._processMessageQueue(s.getValue("OS_TOAST_NOTIFICATIONS_BACKOFF"))}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}sendToast(e){const t={REQUEST_ID:n(),CONTEXT:JSON.stringify({type:e.type,data:e.data}),TITLE:e.title,MESSAGE:e.message,overridable:e.overridable};this._messageQueue.length>0&&this._messageQueue[this._messageQueue.length-1].overridable?this._messageQueue[this._messageQueue.length-1]=t:this._messageQueue.push(t);const i=e.overridable?s.getValue("OS_TOAST_NOTIFICATIONS_DELAY"):0;this._processMessageQueue(i)}}},function(e,t,i){var n=i(15),o=i(0),r=i(9),s=i(16),a=i(5);e.exports=class{constructor(e){this._analytics=e,this._isEnabled=!0,this._scriptPath=r.join(__dirname,"localThumbnailsProcess.js"),this._nextRequestId=0,this._requestMap={},this._handleResponse=this._handleResponse.bind(this),this._handleExit=this._handleExit.bind(this)}_startChildProcess(){this._child||(a.log("LocalThumbnails","Starting child process"),this._child=n.fork(this._scriptPath),process.on("exit",this._stopChildProcess),this._child.on("message",this._handleResponse),this._child.on("exit",this._handleExit))}_stopChildProcess(e){this._child&&(a.log("LocalThumbnails","Stopping child process"),this._child.removeListener("message",this._handleResponse),this._child.removeListener("exit",this._handleExit),process.removeListener("exit",this._stopChildProcess),e||this._child.send({exit:!0}),this._child=void 0)}_handleResponse(e){var t=this._requestMap[e.id];if(delete this._requestMap[e.id],t){0===Object.keys(this._requestMap).length&&(this._pendingShutdownTimeout&&clearTimeout(this._pendingShutdownTimeout),this._pendingShutdownTimeout=setTimeout(()=>{0===Object.keys(this._requestMap).length&&this._stopChildProcess(),this._pendingShutdownTimeout=null},o.getValue("LOCAL_THUMBNAILS_SHUTDOWN_DELAY")));var i=" ("+(Date.now()-t.startTime)+"ms)";"__test__"===t.source?(a.log("LocalThumbnails","Testing: Success"+i),t.callback(e.err)):e.err?(a.log("LocalThumbnails","["+t.id+"] Error received: "+e.err+i),this._analytics.reportError("ThumbnailGeneratorError",e.err),t.callback(e.err)):(a.log("LocalThumbnails","["+t.id+"] Success"+i),t.callback(null,t.destination))}}_handleExit(e,t){this._stopChildProcess(!0);var i=Object.keys(this._requestMap);if(0!==i.length){var n="Unexpected exit: "+(null!==e?e:t);this._analytics.reportError("ThumbnailGeneratorError",n),i.forEach(e=>{var t=this._requestMap[e];"__test__"===t.source?a.log("LocalThumbnails","Testing: Failed - "+n):a.log("LocalThumbnails","["+e+"] "+n),t.callback("unexpected_exit")}),this._requestMap={}}}generate(e,t,i,n){if(this._isEnabled)if(e&&t){this._startChildProcess();var o={id:this._nextRequestId++,startTime:Date.now(),source:e,destination:t,size:i,callback:n};this._requestMap[o.id]=o,"__test__"!==e&&a.log("LocalThumbnails","["+o.id+"] Requesting (size "+i+"): "+e),s.ensureDir(r.dirname(t),()=>{this._child.send({id:o.id,src:r.normalize(e),dest:r.normalize(t),size:i})})}else n("Missing source and/or destination path - source:"+e+"destination:"+t);else n("local_thumbnails_disabled")}test(e){this.generate("__test__","__test__",250,t=>{var i="unexpected_exit"!==t;this._isEnabled=i,e(i)})}}},function(e,t,i){const n=i(19),o=i(9),r=i(15),s=i(3),a=i(0),c=i(5);class l{constructor(e,t){this._scriptPath=e||l._scriptPath,this._analytics=t,this._listenerManager=new s(["change"],e=>c.log("SystemFonts",e)),this._fontWatchers=[],this._changeCount=0,this._fontWatchDebounce=a.getValue("FONT_WATCH_DEBOUNCE"),this._getFonts()}_getAvailableFonts(e){c.log("SystemFonts","Requesting fonts from font manager");let t=!1;const i=(i,n)=>{t||(i?(c.log("SystemFonts",i),this._analytics.reportError("SystemFonts",i),e([])):e(n),t=!0)},n=r.fork(this._scriptPath);n.on("message",e=>i(null,e)),n.on("exit",e=>i("Error, exiting with code: "+e))}_getFonts(e){return e&&delete this._fontCache,this._fontCache?Promise.resolve(this._fontCache):(this._fetchingPromise?e&&(this._pendingRefresh=!0):this._fetchingPromise=new Promise(e=>{const t=setInterval(()=>{if(this._pendingRefresh)return void(this._pendingRefresh=!1);const i=Date.now();clearInterval(t),c.log("SystemFonts","Loading system fonts"),this._getAvailableFonts(t=>{const n=Date.now()-i;if(delete this._fetchingPromise,t&&!this._pendingRefresh)this._fontWatchDebounce=a.getValue("FONT_WATCH_DEBOUNCE"),c.log("SystemFonts",`Loaded ${t.length} fonts (${n}ms)`),this._fontCache=t,this._listenerManager.notify("change"),e(t);else{const i=t?"System fonts changed while loading":"Failed to load system fonts";if(this._pendingRefresh=!1,c.log("SystemFonts",`${i} (${n}ms) - loading again`),!t){const e=a.getValue("FONT_WATCH_ERROR_DEBOUNCE_MIN"),t=a.getValue("FONT_WATCH_ERROR_DEBOUNCE_MAX");this._fontWatchDebounce=Math.max(e,Math.min(t,2*this._fontWatchDebounce))}e(this._getFonts())}})},this._fontWatchDebounce)}),this._fetchingPromise)}_onChange(e){c.log("SystemFonts",`Font directory changed: ${e}`),this._getFonts(!0).then(()=>this._changeCount=0),this._changeCount++,this._changeCount>a.getValue("FONT_WATCH_RESET")&&(c.log("SystemFonts","Resetting font directory watchers"),this._ensureWatchers(!0),this._changeCount=0)}_ensureWatchers(e=!1){const t=this._listenerManager.hasListeners("change");t&&!e||(this._fontWatchers.forEach(e=>e&&e.close()),this._fontWatchers=[]),t&&a.getValue("FONT_DIRS").forEach((e,t)=>{if(this._fontWatchers[t])return;const i=()=>this._onChange(e),o=i=>{c.log("SystemFonts",`Failed to watch font directory (${i&&i.code}): ${e}`),this._fontWatchers[t]=void 0,this._analytics.reportError("SystemFonts",i&&i.code)};try{this._fontWatchers[t]=n.watch(e,{persistent:!1},i),c.log("SystemFonts",`Watching font directory: ${e}`),this._fontWatchers[t].on("error",o)}catch(e){o(e)}})}isFontAvailable(e,t=!1){this._ensureWatchers();const i=t?"family":"postscriptName";return this._getFonts().then(t=>t.some(t=>t[i]===e))}addChangeListener(e){this._listenerManager.add("change",e),this._ensureWatchers()}removeChangeListener(e){this._listenerManager.remove("change",e),this._ensureWatchers()}removeAllListeners(){this._listenerManager.removeAll("change"),this._ensureWatchers()}}l._scriptPath=o.join(__dirname,"systemFontsProcess.js"),e.exports=l},function(e,t,i){const n=i(34),o=i(24),r=i(3),s=i(0),a=i(5);e.exports=class{constructor(e,t){this._ccLibraries=e,this._proxy=t,this._listenerManager=new r(["change"],e=>a.log("CDN Cache",e)),this._ccLibraries._config.SHA_CACHE=s.getValue("SHA_CACHE")||{}}start(){s.getValue("CDN_REFRESH_INTERVAL")&&this._fetch()}get _cacheBaseURL(){return`https://${s.getEnvironment().SHA_CDN_HOST}${s.getValue("CDN_CACHE_ROOT")}`}_fetch(){const e=this._cacheBaseURL+s.getValue("CDN_CACHE_FILE");a.log("CDN Cache",`Fetching SHA Cache from CDN: ${e}`);const t=Object.assign({},n.parse(e),this._proxy.getNodeTunnelOptionsForURL(e));o.get(t,e=>{const t=e&&e.statusCode;if(200!==t)return void this._onFetchError(`status code: ${t}`);let i="";e.on("data",e=>i+=e),e.on("end",()=>{let e;try{e=JSON.parse(i)}catch(e){return void this._onFetchError(e)}this._onFetchSuccess(e||{})})}).once("error",e=>this._onFetchError(e))}_onFetchSuccess(e){const t=this._cacheBaseURL;Object.keys(e).forEach(i=>{e[i]=`${t}${e[i]}`}),this._ccLibraries._config.SHA_CACHE=e,s.setValue("SHA_CACHE",e),this._listenerManager.notify("change"),setTimeout(()=>this._fetch(),s.getValue("CDN_REFRESH_INTERVAL"))}_onFetchError(e){a.log("CDN Cache",`Error fetching SHA Cache: ${e}`),setTimeout(()=>this._fetch(),s.getValue("CDN_RETRY_INTERVAL"))}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}removeAllListeners(){this._listenerManager.removeAll("change")}}},function(e,t,i){const n=i(7),o=i(95),r=i(0),s=i(5),a=i(13),c=i(96),l=i(98),h=i(99),d=i(100),_=i(101);e.exports=class{constructor(e,t,i){this._ccLibraries=e,this._authentication=t,this._vulcan=i}initialize(e){return this._server?Promise.reject("API is already initialized"):(this._server=o.createServer({name:"CCLibraries REST API"}),this._batchHandlers={},this._server.use(o.plugins.bodyParser()),this._server.use(o.plugins.queryParser({mapParams:!0})),this._server.use((e,t,i)=>{let n=this._logRequest(e,t);if(t.header("x-request-id",n),t.header("x-env",r.getEnvironment().LABEL),t.header("access-control-allow-origin","*"),t.charSet("utf-8"),"OPTIONS"===e.method)return i();if((e.headers.token||e.query.token)!==this._serviceToken)return t.send(401);if(0===this._ccLibraries.getLoadedCollections().length){const e=this._authentication.getUserId();return t.send(403,{userId:e})}i()}),this._optionsRoute=this._server.opts("*",(e,t)=>{t.header("access-control-allow-methods",e.header("access-control-request-method")),t.header("access-control-allow-headers",e.header("access-control-request-headers")),t.send(200)}),this._elementsRoute=new c(this),this._groupsRoute=new l(this),this._librariesRoute=new h(this),this._notificationsRoute=new d(this),this._searchRoute=new _(this),new Promise(t=>{this._server.listen(e||0,"127.0.0.1",()=>{s.log("API",`${this._server.name} listening at ${this._server.url}`),this._serviceHostname=this._server.url,this._serviceToken=n(),this._onConnectionHandler=this._connectionHandler.bind(this),this._vulcan.addListener("cclibraries.api.QueryRequest",this._onConnectionHandler),t()})}))}addBatchHandler(e,t,i,n,o){n=n||(()=>{}),this._batchHandlers[e]=this._batchHandlers[e]||{};const r={params:{},routeInfo:{routeHandler:i,bodyValidator:n,isRemovedElement:o}},s=t.split("/").reduceRight((e,t)=>t.startsWith(":")?i=>(e.params[t.substr(1)]=i,e):{[t]:e},r);Object.assign(this._batchHandlers[e],s)}getBatchHandler(e,t,i,n,o){const[r,s]=t.split("?"),c=s?a.parseQueryString("?"+s,{parseBooleans:!0}):{};c.libraryId=o.id;const l=r.split("/").reduce((e,t)=>"function"==typeof e?e(t):e&&e[t],this._batchHandlers[e]);if(l)return{method:e,path:r,body:i,index:n,headers:[],params:Object.assign(c,l.params),_routeInfo:l.routeInfo}}_logRequest(e,t){const i=Date.now(),o=e.headers["x-request-id"]||n();return s.log("API",`[${o}] ${e.method.toUpperCase()} ${e.headers.host}${e.href()}`),t.on("finish",()=>{s.log("API",`[${o}] ${t.statusCode} (${Date.now()-i}ms)`)}),o}_connectionHandler(e,t,i){let n;s.log("API",`Client connected: ${t} - ${i}`);try{n=e&&JSON.parse(e)}catch(t){s.log("API",`Parse error, client message: ${e}`)}const o=n&&n.apiVersion,a={apiVersion:r.getValue("REST_API_VERSION"),apiMinVersion:r.getValue("REST_API_MIN_VERSION"),apiMaxVersion:r.getValue("REST_API_MAX_VERSION")};!o||o<a.apiMinVersion?a.updateRequired="client":o>a.apiMaxVersion?a.updateRequired="server":(a.serviceHostname=this._serviceHostname,a.serviceToken=this._serviceToken),this._vulcan.sendMessage("cclibraries.api.QueryResponse",JSON.stringify(a),t,i)}shutdown(){this._server&&(this._serviceHostname=void 0,this._serviceToken=void 0,this._elementsRoute.dispose(),this._elementsRoute=void 0,this._groupsRoute.dispose(),this._groupsRoute=void 0,this._librariesRoute.dispose(),this._librariesRoute=void 0,this._notificationsRoute.dispose(),this._notificationsRoute=void 0,this._searchRoute.dispose(),this._searchRoute=void 0,this._server.rm(this._optionsRoute),this._optionsRoute=void 0,this._server.close(),this._server=void 0,this._vulcan.removeListener("cclibraries.api.QueryRequest",this._onConnectionHandler))}}},function(e,t){e.exports=require("restify")},function(e,t,i){const n=i(9),{getElementResponseData:o,updateCustomData:r,parsePlaceholder:s}=i(18),a=i(21),c=i(22);e.exports=class extends c{constructor(e){super(e),this._addRoute("get","/libraries/:libraryId/elements",this.getElements.bind(this)),this._addRoute("post","/libraries/:libraryId/elements",this.createElement.bind(this),!0),this._addRoute("get","/libraries/:libraryId/elements/:elementId",this.getElement.bind(this)),this._addRoute("put","/libraries/:libraryId/elements/:elementId",this.updateElement.bind(this),!0),this._addRoute("del","/libraries/:libraryId/elements/:elementId",this.removeElement.bind(this),!0),this._addRoute("get","/libraries/:libraryId/elements/:elementId/representations/:representationId/path",this.getRepresentationPath.bind(this)),this._addRoute("post","/libraries/:libraryId/elements/:elementId/representations/:representationId/report_usage",this.reportRepresentationUsage.bind(this),!1),this._addRoute("get","/libraries/:libraryId/elements/:elementId/renditions/:size/path",this.getRenditionPath.bind(this)),this._addRoute("get","/libraries/:libraryId/removed_elements",this.getRemovedElements.bind(this)),this._addRoute("get","/libraries/:libraryId/removed_elements/:elementId",this.getElement.bind(this),null,!0),this._addRoute("del","/libraries/:libraryId/removed_elements/:elementId",this.removeElement.bind(this),null,!0),e.addBatchHandler("POST","elements",this.createElementBatch.bind(this),this.validateElementData.bind(this)),e.addBatchHandler("PUT","elements/:elementId",this.updateElement.bind(this),this.validateElementData.bind(this)),e.addBatchHandler("DELETE","elements/:elementId",this.removeElement.bind(this)),e.addBatchHandler("DELETE","removed_elements/:elementId",this.removeElement.bind(this),void 0,!0)}_buildRepresentations(e,t){const i=[];if(e.representations.length>0){const i=t.filter(e=>e.id).map(e=>e.id);e.representations.slice().forEach(t=>{i.includes(t.id)||e.removeRepresentation(t)})}return t.forEach((t,n)=>{if(t.id){const i=e.getRepresentationById(t.id);return void(i&&i._getDCXElement().setValue(this._ccLibraries.getOption("REPRESENTATION_ORDER_KEY"),n))}const o=e.createRepresentation(t.type,t.relationship,n);this._buildRepresentation(o,t,i)}),Promise.all(i)}_buildRepresentation(e,t,i){t.source&&(t.source.path||t.source.url)&&i.push(new Promise((i,n)=>{t.source.path?e.setContentFromPath(t.source.path,t.source.moveFile,e=>{e?n(e):i()}):t.source.url&&e.setContentFromURL(!!t.source.createLink,t.source.url,t.source.headers,e=>{e?n(e):i()})}).then(()=>{void 0!==t.width&&(e.width=t.width),void 0!==t.height&&(e.height=t.height),void 0!==t.content_length&&(e.contentLength=t.content_length),void 0!==t.is_full_size&&(e.isFullSize=t.is_full_size)}));const n=this._parseCustomData(t.custom_data);n?(r(e,n),(t.children||[]).forEach(t=>{const n=e.createChild(t.type);this._buildRepresentation(n,t,i)})):i.push(Promise.reject(a.INVALID_CUSTOM_DATA))}validateElementData(e,t,i,n){if(!e)return a.ELEMENT_DATA_MISSING;const o=e.tags,r=e.representations,s=this._parseCustomData(e.custom_data),c=e.groups;if(!s)return a.INVALID_CUSTOM_DATA;if(i){if(!(0!==s.length||e.name||r||o||c))return a.ELEMENT_BODY_MISSING}else{if(!e.type)return a.ELEMENT_TYPE_MISSING;const i=(e.force&&e.type===this._ccLibraries.getOption("COLOR_ELEMENT_TYPE")?2:1)*this._ccLibraries.getOption("MAX_ELEMENTS");if(t.elements.length>=i)return a.LIBRARY_NOT_ENOUGH_SPACE}if(e.name&&"string"!=typeof e.name)return a.ELEMENT_NAME_INVALID;if(o&&(!Array.isArray(o)||!o.every(e=>"string"==typeof e)))return a.ELEMENT_TAGS_INVALID;if(r||!i){if(!r||!Array.isArray(r)||0===r.length)return a.REPRESENTATION_DATA_MISSING;for(let e of r){let t;if(i&&e.id){if(t=i.getRepresentationById(e.id),!t)return a.REPRESENTATION_ID_NOT_RESOLVED}else{const t=this._validateRepresentationData(e);if(t)return t}}if(r.filter(e=>{const t=i&&i.getRepresentationById(e.id);return"primary"===(t?t.relationship:e.relationship)}).length>1)return a.REPRESENTATION_REL_PRIMARY_FOUND}return c?this._validateGroupsData(c,t,n):void 0}_validateGroupsData(e,t,i){const n=Array.isArray(e);if(!e||n&&0===e.length)return;const o=(e,n=this._ccLibraries.getOption("DEFAULT_GROUP_CLASSIFIER"))=>{for(let o=0;o<e.length;o++){const r=e[o];if(!r.id||"string"!=typeof r.order)return a.INVALID_GROUP_DATA;if(i&&s(r.id)){const e=i("groupId",r.id);if(e)return e}else{const e=t.getGroupById(r.id);if(!e)return a.GROUP_NOT_FOUND;if(e.classifierName!==n)return a.INVALID_GROUP_DATA}}};if(n)return o(e);if("object"!=typeof e)return a.INVALID_GROUP_DATA;let r=Object.keys(e);for(let t=0;t<r.length;t++){const i=r[t],n=o(e[i],i);if(n)return n}}_validateRepresentationData(e,t){if(!e.type)return a.REPRESENTATION_TYPE_MISSING;if(t){if(e.relationship)return a.REPRESENTATION_REL_INVALID}else{if(!e.relationship)return a.REPRESENTATION_REL_MISSING;if(!this._ccLibraries.getOption("VALID_RELATIONS").includes(e.relationship))return a.REPRESENTATION_REL_INVALID}if(e.source&&!e.source.path&&!e.source.url)return a.REPRESENTATION_SOURCE_MISSING;if(void 0!==e.width&&"number"!=typeof e.width||e.width<0)return a.REPRESENTATION_WIDTH_INVALID;if(void 0!==e.height&&"number"!=typeof e.height||e.height<0)return a.REPRESENTATION_HEIGHT_INVALID;if(void 0!==e.content_length){if(!e.source.url||!e.source.createLink)return a.REPRESENTATION_CONTENT_LENGTH_UNEXPECTED;if("number"!=typeof e.content_length||e.content_length<0)return a.REPRESENTATION_CONTENT_LENGTH_INVALID}if(e.children){if(!Array.isArray(e.children))return a.REPRESENTATION_CHILDREN_INVALID;if(e.children.some(e=>this._validateRepresentationData(e,!0)))return a.REPRESENTATION_CHILDREN_INVALID}return void 0!==e.is_full_size&&"boolean"!=typeof e.is_full_size?a.REPRESENTATION_FULL_SIZE_INVALID:void 0}_updateElement(e,t){const i=e.tags,n=e.representations,o=this._parseCustomData(e.custom_data),s=e.groups;if(e.name&&(t.name=e.name),i&&(t.tags=i),r(t,o),s){const e=(e,i=this._ccLibraries.getOption("DEFAULT_GROUP_CLASSIFIER"))=>{const n=t.getGroups(i);n.length>0&&t.setOrderInGroup(n[0],void 0),e.forEach(e=>{const i=t.library.getGroupById(e.id);t.setOrderInGroup(i,e.order,!1)})};if(Array.isArray(s))e(s);else{Object.keys(s).forEach(t=>{e(s[t],t)})}}if(n)return this._buildRepresentations(t,n)}createElement(e,t,i){if(t&&(t.self||t.source))return this.copyOrMoveElements(e,t,i);const n=this.validateElementData(t,i);if(n)return Promise.reject(n);const r=i.createElement(t.name,t.type,t.force);return Promise.resolve(this._updateElement(t,r,!0)).then(()=>(r.endOperation(),o(r))).catch(e=>(r.library.removeElement(r),Promise.reject(a.getResponseError(e))))}createElementBatch(e,t,i){const n=i._config.MAX_ELEMENTS;i._config.MAX_ELEMENTS=Number.MAX_VALUE;const o=this.createElement(e,t,i);return i._config.MAX_ELEMENTS=n,o}updateElement(e,t,i){const n=this.validateElementData(t,i.library,i);return n?Promise.reject(n):(i.beginOperation(),t.representations?Promise.resolve(this._updateElement(t,i)).then(()=>(i.endOperation(),o(i))).catch(e=>(i.endOperation(),Promise.reject(a.getResponseError(e)))):(this._updateElement(t,i),i.endOperation(),o(i)))}copyOrMoveElements(e,t,i){const n=!!t.self,r=t.self||t.source,s=r.id,c=r.elements;if(!s)return Promise.reject(a.LIBRARY_ID_MISSING);if(!c||!Array.isArray(c)||0===c.length)return Promise.reject(a.ELEMENT_IDS_MISSING);const l=this._ccLibraries.getLibraryById(s);if(!l)return Promise.reject(a.LIBRARY_NOT_FOUND);if(n&&!l.isWritable)return Promise.reject(a.LIBRARY_NOT_WRITABLE);if(i.elements.length+c.length>this._ccLibraries.getOption("MAX_ELEMENTS"))return Promise.reject(a.LIBRARY_NOT_ENOUGH_SPACE);const h=c.map(e=>l.getElementById(e));if(h.some(e=>!e))return Promise.reject(a.ELEMENT_NOT_FOUND);i.beginOperation(),n&&l.beginOperation();const d=n?l.moveElement.bind(l):l.copyElement.bind(l),_=()=>{i.endOperation(),n&&l.endOperation()},p=[];return h.forEach(e=>{p.push(new Promise((t,n)=>{d(e,i,(e,i)=>{e?n(a.getResponseError(e)):t(i)})}))}),Promise.all(p).then(e=>(_(),{elements:e.map(o)})).catch(e=>(_(),Promise.reject(e)))}getElement(e,t,i){return o(i)}getElements(e,t,i){return{elements:i.elements.map(o)}}getRemovedElements(e,t,i){return{elements:i.removedElements.map(o)}}getRepresentationPath(e,t,i){return new Promise((e,t)=>{i.getContentPath((i,o)=>i?t(a.getResponseError(i)):o?void e({path:n.normalize(o)}):t(a.REPRESENTATION_PATH_NOT_FOUND))})}getRenditionPath(e,t,i){let r=e.size;if("full"===r)r=void 0;else if("vector"!==r){if(!RegExp(/^\d+$/).test(r)||"0"===r)return a.INVALID_RENDITION_SIZE;r=Number(r)}if("none"!==e.cacheControl){const e=i.getCachedThumbnailPath(r);return e?{path:n.normalize(e)}:a.RENDITION_PATH_NOT_CACHED}return new Promise((e,t)=>{i.getThumbnailPath(r,(r,s)=>r?t(a.getResponseError(r)):s?void e({path:n.normalize(s),element:o(i,!1,!1,!0)}):t(a.RENDITION_PATH_NOT_FOUND))})}removeElement(e,t,i){i.library.removeElement(i,e.permanent||i.removed)}reportRepresentationUsage(e,t,i){const n=e.appName?{appName:e.appName}:{},o=t&&t.opType||"unknown";this._ccLibraries.analyticsUtils.reportUseElement(i,o,n)}}},function(e,t){e.exports=require("restify-errors")},function(e,t,i){const{getGroupResponseData:n}=i(18),o=i(21),r=i(22);e.exports=class extends r{constructor(e){super(e),this._addRoute("get","/libraries/:libraryId/groups",this.getGroups.bind(this)),this._addRoute("post","/libraries/:libraryId/groups",this.createGroup.bind(this),!0),this._addRoute("get","/libraries/:libraryId/groups/:groupId",this.getGroup.bind(this)),this._addRoute("put","/libraries/:libraryId/groups/:groupId",this.updateGroup.bind(this),!0),this._addRoute("del","/libraries/:libraryId/groups/:groupId",this.removeGroup.bind(this),!0),e.addBatchHandler("POST","groups",this.createGroup.bind(this),this.validateCreateGroupBody.bind(this)),e.addBatchHandler("PUT","groups/:groupId",this.updateGroup.bind(this),this.validateUpdateGroupBody.bind(this)),e.addBatchHandler("DELETE","groups/:groupId",this.removeGroup.bind(this))}validateCreateGroupBody(e){const t=e&&e.name,i=e&&e.order;return t?i?void 0:o.GROUP_ORDER_MISSING:o.GROUP_NAME_MISSING}createGroup(e,t,i){const o=t&&t.name,r=t&&t.classifier,s=t&&t.order;let a=this.validateCreateGroupBody(t);if(a)return Promise.reject(a);const c=i.createGroup(o,s,r);return n(c)}removeGroup(e,t,i){i.library.removeGroup(i,e.include_contents)}getGroup(e,t,i){return n(i)}getGroups(e,t,i){const o={groups:[]},r=e.classifier||/.*/;return o.groups=i.getGroups(r).map(e=>n(e)),o}validateUpdateGroupBody(e){const t=e&&e.name,i=e&&e.order;return t||i?t&&"string"!=typeof t||i&&"string"!=typeof i?o.INVALID_GROUP_DATA:void 0:o.GROUP_BODY_MISSING}updateGroup(e,t,i){const o=t&&t.name,r=t&&t.order;let s=this.validateUpdateGroupBody(t);return s?Promise.reject(s):(i.library.beginOperation(),o&&(i.name=o),r&&(i.order=r),i.library.endOperation(),n(i))}}},function(e,t,i){const{getLibraryResponseData:n,updateCustomData:o,parsePlaceholder:r}=i(18),s=i(21),a=i(22),c=i(9),l=(e,t)=>{const i=void 0!==t&&`Issue at request index: ${t}`;return s.getResponseError(e,i)},h={elementId:"elements",groupId:"groups"},d=Object.keys(h);e.exports=class extends a{constructor(e){super(e),this._apiServer=e,this._addRoute("get","/libraries",this.getLibraries.bind(this)),this._addRoute("post","/libraries",this.createLibrary.bind(this)),this._addRoute("get","/libraries/:libraryId",this.getLibrary.bind(this)),this._addRoute("put","/libraries/:libraryId",this.updateLibrary.bind(this),!0),this._addRoute("del","/libraries/:libraryId",this.removeLibrary.bind(this)),this._addRoute("patch","/libraries/:libraryId",this.batchUpdateLibrary.bind(this),!0),this._addRoute("get","/libraries/:libraryId/temp_dir",this.getTempDir.bind(this),!0),e.addBatchHandler("PUT","",this.updateLibrary.bind(this),this.validateUpdateLibraryBody.bind(this)),e.addBatchHandler("GET","",this.getLibrary.bind(this))}createLibrary(e,t){if(t&&t.follow)return this.followLibrary(e,t);const i=this._parseCustomData(t&&t.custom_data);if(!i)return Promise.reject(s.INVALID_CUSTOM_DATA);const r=i.find(e=>"toolkit"===e.namespace&&"id"===e.key),a=r&&this._ccLibraries._localisation.getToolkitName(r.value)||t&&t.name||e&&e.name;if(!a)return Promise.reject(s.LIBRARY_NAME_MISSING);const c=this._ccLibraries.getLoadedCollections().find(e=>e.isPrivate);if(!c)return Promise.reject(s.COLLECTION_NOT_FOUND);const l=c.createLibrary(a);return o(l,i),n(l)}followLibrary(e,t){const i=t&&t.id,n=t&&t.url;if(!i)return Promise.reject(s.LIBRARY_ID_MISSING);if(!n)return Promise.reject(s.LIBRARY_URL_MISSING);const o=this._ccLibraries.getLoadedCollections().find(e=>e.isPrivate);return o?new Promise((e,t)=>{o._bookmarkManager.createBookmark("public",i,{url:n},void 0,i=>{i?t(i):e()})}):Promise.reject(s.COLLECTION_NOT_FOUND)}getLibraries(){const e={libraries:[]};return this._ccLibraries.getLoadedCollections().forEach(t=>{t.libraries.forEach(t=>{t.isDeletedFromServer||e.libraries.push(n(t))})}),e}getLibrary(e,t,i){return n(i,{includeElements:!0})}removeLibrary(e,t,i){i.collection.removeLibrary(i,()=>{})}validateUpdateLibraryBody(e){const t=e&&e.name,i=this._parseCustomData(e&&e.custom_data);return i?0!==i.length||t?void 0:s.INVALID_UPDATE_REQUEST:s.INVALID_CUSTOM_DATA}updateLibrary(e,t,i){t=t||{},e&&e.name&&!t.name&&(t.name=e.name);const r=this.validateUpdateLibraryBody(t);if(r)return Promise.reject(r);const s=t.name;s&&(i.name=s);const a=this._parseCustomData(t&&t.custom_data);return o(i,a),n(i)}validateBatchedRequests(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(!n)return l(s.INVALID_TRANSACTION_REQUEST,i);if(n.response)continue;const o="PUT"===n.method&&n.path.startsWith("elements/")&&n.body&&n.body.representations,a="POST"===n.method&&"elements"===n.path&&n.body&&(n.body.source||n.body.self);if(o||a)return l(s.NOT_IMPLEMENTED,i);const c=(n,o)=>{const{index:a,property:c}=r(o);let l=e[a];if(l=l&&l._originalRequest||l,a>i||"id"!==c||"POST"!==l.method||l.path!==h[n])return s.INVALID_TRANSACTION_PLACEHOLDER;if(l.response){const e={params:{libraryId:t.id,[n]:l.response.id},headers:[]},i=this._getRequestedModels(e,!0,_);if(i.error)return i.error}},{isRemovedElement:_,bodyValidator:p}=n._routeInfo;let u;const m=d.find(e=>n.params[e]&&r(n.params[e]));if(m){const e=c(m,n.params[m]);if(e)return l(e,i);u={}}else{const e=this._getRequestedModels(n,!0,_);if(u=e.element,e.error)return l(e.error,i)}const g=p(n.body,t,u,c);if(g)return l(g,i)}}_callBatchAPI(e){const{routeHandler:t,isRemovedElement:i}=e._routeInfo,{library:n,element:o,group:r,representation:a,error:c}=this._getRequestedModels(e,!0,i);if(c)throw l(c,e.index);try{return t(e.params,e.body,r||a||o||n)}catch(t){throw l(s.getResponseError(t),e.index)}}batchUpdateLibrary(e,t,i){if(!Array.isArray(t)||0===t.length)return Promise.reject(s.INVALID_TRANSACTION_SYNTAX);const n=t.findIndex(e=>"object"!=typeof e||"string"!=typeof e.path||!e.method||e.body&&"object"!=typeof e.body);if(n>-1)return Promise.reject(l(s.INVALID_TRANSACTION_SYNTAX,n));const o=t.map((e,t)=>this._apiServer.getBatchHandler(e.method,e.path,e.body,t,i)),a=this.validateBatchedRequests(o,i);if(a)return Promise.reject(a);let c=i.elements.length,h=c;if(o.forEach(e=>{if("POST"===e.method&&"elements"===e.path){e.body&&e.body.force&&e.body.type===this._ccLibraries._config.COLOR_ELEMENT_TYPE||c++}else"DELETE"===e.method&&e.path.startsWith("elements")&&c--;h=Math.max(h,c)}),h>i.elements.length&&h>this._ccLibraries.getOption("MAX_ELEMENTS"))return Promise.reject(s.LIBRARY_NOT_ENOUGH_SPACE);let _=!1;const p=[],u=e=>i.removeElement(i.getElementById(e),!0);i.beginOperation();const m=o.filter(e=>"POST"===e.method&&"elements"===e.path).map(e=>((e=>{if(!e)return;const t=e=>e.some(e=>r(e.id));return Array.isArray(e)?t(e):Object.keys(e).some(i=>t(e[i]))})(e.body.groups)&&(o[e.index]=this._apiServer.getBatchHandler("PUT",`${e.path}/$${e.index}.id`,{groups:e.body.groups},e.index,i),delete e.body.groups,o[e.index]._originalRequest=e),Promise.resolve().then(()=>this._callBatchAPI(e)).then(t=>{_?u(t.id):(p.push(t.id),e.response=t)})));return Promise.all(m).then(()=>{const e=i.isDeletedFromServer&&s.LIBRARY_NOT_FOUND||!i.isWritable&&s.LIBRARY_NOT_WRITABLE||this.validateBatchedRequests(o,i);if(e)return Promise.reject(e);const t=e=>{const t=r(e),i=t&&o[t.index],n=i&&(i._originalRequest?i._originalRequest.response:i.response);return n?n[t.property]:e},n=e=>e.forEach(e=>e.id=t(e.id));return o.forEach(e=>{if(e.response)return;d.forEach(i=>e.params[i]&&(e.params[i]=t(e.params[i])));const i=e.body&&e.body.groups;i&&(Array.isArray(i)?n(i):Object.keys(i).forEach(e=>n(i[e]))),e.response=this._callBatchAPI(e)}),i.endOperation(),o.map(e=>e.response)}).catch(e=>(_=!0,Promise.all(m.map(e=>e.catch(()=>null))).then(()=>(p.forEach(u),i.endOperation(),Promise.reject(e)))))}getTempDir(e,t,i){return new Promise((e,t)=>{i.collection.getTempDir((i,n)=>{if(i)return t(s.getResponseError(i));e({path:c.normalize(n)})})})}}},function(e,t,i){const{getLibraryResponseData:n}=i(18),o=i(22);e.exports=class extends o{constructor(e){super(e),this._monitoredCollections=[],this._pendingSyncChangeCallbacks=[],this._pendingLibraryChangeCallbacks=[],this._onLibrariesChanged=this._librariesChanged.bind(this),this._onSyncStatusChanged=this._syncStatusChanged.bind(this),this._onCollectionsChanged=this._collectionsChanged.bind(this),this._ccLibraries.addLoadedCollectionsListener(this._onCollectionsChanged),this._ensureCollectionListeners(),this._addPollingRoute("post","/notifications/libraries",this.handleLibraryNotifications.bind(this)),this._addPollingRoute("post","/notifications/libraries/sync",this.handleSyncStatusNotifications.bind(this))}_ensureCollectionListeners(){const e=this._ccLibraries.getLoadedCollections();e.filter(e=>!this._monitoredCollections.includes(e)).forEach(e=>{e.addSyncListener(this._onSyncStatusChanged),e.addDeepChangeListener(this._onLibrariesChanged)}),this._monitoredCollections=e}_collectionsChanged(){this._ensureCollectionListeners(),this._librariesChanged(),this._syncStatusChanged()}_librariesChanged(){if(0===this._pendingLibraryChangeCallbacks.length)return;const e=this._getLibrariesData();this._pendingLibraryChangeCallbacks=this._pendingLibraryChangeCallbacks.filter(t=>!t(e))}_syncStatusChanged(){if(0===this._pendingSyncChangeCallbacks.length)return;const e=this._getSyncStatusData();this._pendingSyncChangeCallbacks=this._pendingSyncChangeCallbacks.filter(t=>!t(e))}_getLibrariesData(){const e={};return this._ccLibraries.getLoadedCollections().forEach(t=>{t.libraries.forEach(t=>{t.isDeletedFromServer||(e[t.id]=t.modified)})}),e}_getSyncStatusData(){let e,t="ok";return this._ccLibraries.getLoadedCollections().some(i=>{if("error"===i.syncState)return t=i.syncState,e=i.getPrimarySyncError(),!0;"syncing"===i.syncState&&(t=i.syncState)}),{state:t,error:e}}_getChangedLibrariesData(e,t){let i=Object.keys(t).length!==Object.keys(e).length;const o={};return Object.keys(t).forEach(r=>{const s=t[r];e[r]!==s?(o[r]=n(this._ccLibraries.getLibraryById(r)),i=!0):o[r]=s}),i?o:void 0}_compareSyncStatusData(e,t){return!e||e.state!==t.state||e.error!==t.error}handleLibraryNotifications(e,t){const i=this._getLibrariesData(),n=this._getChangedLibrariesData(e,i);if(n)return void t(n);const o=i=>{const n=this._getChangedLibrariesData(e,i);if(n)return t(n),!0};return this._pendingLibraryChangeCallbacks.push(o),()=>{this._pendingLibraryChangeCallbacks.includes(o)&&this._pendingLibraryChangeCallbacks.splice(this._pendingLibraryChangeCallbacks.indexOf(o),1)}}handleSyncStatusNotifications(e,t){const i=this._getSyncStatusData();if(this._compareSyncStatusData(e,i))return void t(i);const n=i=>{if(this._compareSyncStatusData(e,i))return t(i)};return this._pendingSyncChangeCallbacks.push(n),()=>{this._pendingSyncChangeCallbacks.includes(n)&&this._pendingSyncChangeCallbacks.splice(this._pendingSyncChangeCallbacks.indexOf(n),1)}}}},function(e,t,i){const{getElementResponseData:n,getLibraryResponseData:o,getPagedResponses:r,getSortOrder:s,parseFilterField:a,parseSortField:c}=i(18),l=i(21),{isSearchQueryEmpty:h,findMatchingElements:d,findMatchingLibraries:_,isValidModifiedFilter:p}=i(102),u=i(104),m=i(22),g=e=>!e.collection.isPublic&&"outgoing"!==e.collaboration;e.exports=class extends m{constructor(e){super(e),this._ownerFilterHandlers={owner:e=>!e.collection.isTeam&&g(e),shared:e=>!e.collection.isTeam&&!g(e),team:e=>e.collection.isTeam},this._addRoute("post","/search",this.searchElements.bind(this)),this._localizedSorter=new u(this._ccLibraries),this._localizedSorter.init()}searchElements(e,t,i){let u=t.q;if(t.filters)for(let e in t.filters)t.filters[e]=a(e,t.filters[e]);if(h(u))return Promise.reject(l.EMPTY_SEARCH);if(t.filters&&0===Object.keys(t.filters).length)return Promise.reject(l.EMPTY_FILTERS);if(t.filters&&t.filters.modified_date&&!p(t.filters.modified_date))return Promise.reject(l.INVALID_MODIFIED_FILTER);if(t.limit<=0)return Promise.reject(l.INCORRECT_LIMIT);const m=t.filters&&t.filters.owner,g=m&&m.split(",")||[],f=g.length&&(e=>g.some(t=>this._ownerFilterHandlers[t]&&this._ownerFilterHandlers[t](e)));let E=[];if(i){if(f&&!f(i))return Promise.reject(l.CONFLICTING_OWNERSHIP);E.push(i)}else this._ccLibraries.getLoadedCollections().forEach(e=>{e.libraries.forEach(e=>{f&&!f(e)||E.push(e)})});const y=d(u,E,t.filters).map(e=>n(e,!0,!i,t.thumbnail_cache)),v=i?[]:_(u,E,t.filters).map(e=>o(e,{includeSize:!0,includeRenditionGrid:!0})),A=y.concat(v),{orderBy:C,isAscending:I}=s(t.order_by);A.length>0&&this._localizedSorter.sortResponses(A,C,I);const S=t.limit&&parseInt(t.limit)||10,L=c(C,t.start),{pagedResults:T,isLastPage:R,nextStartValue:O}=r(A,C,I,S,L,this._localizedSorter),b={},N={count:T.length,order_by:t.order_by};return T.length>0&&(N.start=T[0][C]),R||(N.next=O,b.next={uri:"/search",method:"POST",body:t},b.next.body.start=O,b.next.body.limit=S),Promise.resolve({results:T,_page:N,_links:b,_totalCount:A.length})}}},function(e,t,i){const n=i(103),o={};function r(e){if(!(e=e&&e.trim().toLowerCase()))return[];let t;return t=e.length>2&&'"'===e.charAt(0)&&'"'===e.charAt(e.length-1)?[e.substring(1,e.length-1)]:e.indexOf(" ")>-1?e.split(/[ ]+/):[e],t}function s(e,t){if(!t)return!0;if(t.modified_date){const[i,n]=t.modified_date;if(i&&e.modified<i||n&&e.modified>n)return!1}return!0}function a(e,t){const i={"application/vnd.adobe.element.color+dcx":c,"application/vnd.adobe.element.colortheme+dcx":l,"application/vnd.adobe.element.characterstyle+dcx":h,"application/vnd.adobe.element.paragraphstyle+dcx":h,"application/vnd.adobe.element.text+dcx":d}[e.type];return i&&i(e,t)}function c(e,t){let i=u.getRGBColor(e);return i=i&&u.colorDataToHexString(i).toLowerCase(),i&&i.includes(t)}function l(e,t){const i=_(e,"application/vnd.adobe.colortheme+json"),n=i&&i.getValue("colortheme","data");if(n&&Array.isArray(n.swatches))for(let e=0;e<n.swatches.length;e++){const i=n.swatches[e];if(u.colorDataToHexString(i).toLowerCase().includes(t))return!0}return!1}function h(e,t){const i=_(e,"application/vnd.adobe.characterstyle+json"),n=i&&i.getValue("characterstyle","data"),o=n&&n.fontFamily&&n.fontFamily.toLowerCase(),r=n&&n.adbeFont&&n.adbeFont.style&&n.adbeFont.style.toLowerCase(),s=n&&n.fontSize&&n.fontSize.value&&n.fontSize.value.toString().toLowerCase();return o&&o.includes(t)||r&&r.includes(t)||s&&s.includes(t)}function d(e,t){const i=_(e,"application/vnd.adobe.text+json"),n=i&&i.getValue("text","data");let o=0;for(let e=0;e<n.paragraphs.length&&!(o>=6e3);e++){const i=p(n.paragraphs[e].text,6e3-o).toLowerCase();if(i.includes(t))return!0;o+=i.length}return!1}function _(e,t){return e.representations.find(e=>e.type===t)}function p(e,t,i=!0){const o=i?"...":"";return e.length<=t?e:n.ucs2.encode(n.ucs2.decode(e).slice(0,t))+o}o.isSearchQueryEmpty=e=>!(e=e&&e.trim().toLowerCase()&&function(e){if('"'===e.charAt(0)&&'"'===e.charAt(e.length-1))return e.substring(1,e.length-1);return e}(e)),o.findMatchingElements=(e,t,i)=>{if(!t||!Array.isArray(t)||!e)return[];const n=r(e);if(0===n.length)return[];let o=[];return t.forEach(e=>{e.elements.forEach(e=>{s(e,i)&&function(e,t){const i=e.name.toLowerCase(),n=e.description&&e.description.toLowerCase(),o=e.getGroups()[0],r=o&&o.name.toLowerCase(),s=function(e){let t;if(e.representations.find(e=>{if(t=e.getValue("adobestock","trackingdata"),t)return!0}),t)return String(t.content_id);return null}(e);let c=function(e){let t;return e.representations.some(e=>(t=e.getValue("stock","query"),t)),t}(e);c=c&&c.toLowerCase();for(let o=0;o<t.length;o++){const l=t[o];if(!(i.includes(l)||n&&n.includes(l)||r&&r.includes(l)||s&&s.includes(l)||c&&c.includes(l)||a(e,l)))return!1}return!0}(e,n)&&o.push(e)})}),o},o.findMatchingLibraries=(e,t,i)=>{if(!t||!Array.isArray(t)||!e)return[];const n=r(e);if(0===n.length)return[];let o=[];return t.forEach(e=>{s(e,i)&&function(e,t){const i=e.name.toLowerCase();for(let e=0;e<t.length;e++){const n=t[e];if(!i.includes(n))return!1}return!0}(e,n)&&o.push(e)}),o},o.isValidModifiedFilter=e=>{if(!Array.isArray(e))return!1;const[t,i]=e;return!(!t&&!i||"number"!=typeof t&&null!==t||"number"!=typeof i&&null!==i||t&&i&&t>i)};const u={};u.getRGBColor=e=>{if(!e||!e.representations)return;const t=e.representations;for(let e=0;e<t.length;e++){const i=t[e].getValue("color","data");if(i&&"RGB"===i.mode)return i}},u.colorDataToHexString=e=>{const t=Array.isArray(e)?e.find(e=>"RGB"===e.mode):e;return t&&t.value?function(e,t,i){let n=function(e,t,i){return e<<16|t<<8|i}(e,t,i).toString(16);for(;n.length<6;)n="0"+n;return"#"+n}(Math.round(t.value.r),Math.round(t.value.g),Math.round(t.value.b)):""},e.exports=o},function(e,t){e.exports=require("punycode")},function(e,t){e.exports=class{constructor(e){this._ccLibraries=e}init(e){e=e||this._ccLibraries.getLocale().replace("_","-"),this._collator=new Intl.Collator(e,{numeric:!0})}_compare(e,t){return e===t?0:"string"==typeof e&&"string"==typeof t?this._collator.compare(e,t):e<t?-1:1}_sort(e,t,i){return e.sort((e,n)=>{const o=i?this._compare(t(e),t(n)):this._compare(t(n),t(e));if(0===o){if(e.element_ref&&!n.element_ref)return i?-1:1;if(!e.element_ref&&n.element_ref)return i?1:-1}return o})}findNextIndex(e,t,i,n){let o=-1;for(let r=0;r<e.length;r++){if(n?1===this._compare(e[r][t],i):-1===this._compare(e[r][t],i)){o=r;break}}return o}sortResponses(e,t,i){return e&&t&&0!==e.length?"modified_date"===t?this.sortByModified(e,i):"name"===t?this.sortByName(e,i):"size"===t?this.sortBySize(e,i):void 0:e}sortByModified(e,t=!1){return this._sort(e,e=>e.modified_date,t)}sortByName(e,t=!0){return this._sort(e,e=>e.name,t)}sortBySize(e,t=!1){return this._sort(e,e=>e.size,t)}}},function(e,t,i){const n=i(24),o=i(5),r=i(106),s=i(16),a=i(9),c=i(35),l=i(0),h=i(30),d="TLS_SERVER",_=e=>({sniPort:0,trustInProgress:!1,certificateIsTrusted:!1,delayOnDecline:e.getOption("TLS_DELAY_ON_DECLINE"),delayOnReady:e.getOption("TLS_DELAY_ON_READY"),tokens:l.getValue("WSS_TOKENS")||[],dataUploaded:{},dataUploadInProgress:{}});function p(e,t,i){return new Promise((r,s)=>{const a=n.createServer(e);a.on("listening",()=>{o.log(d,`${i} is up and running at port: ${a.address().port}`),r(a)}),a.on("error",e=>{o.log(d,`Failed to launch ${i} at port: ${t} with error: ${e}`),s(e)}),a.listen(t,"127.0.0.1")})}function u(e,t){return Math.floor((e.getTime()-t.getTime())/864e5)}e.exports=class{constructor(e,t){this._ccLibraries=e,this._authentication=t,this._config=_(e),this._locationOfIdentity=a.join(l.getValue("ROOT_DIR"),"identity"),this._deviceID=l.getValue("SNI_SERVER_ID")||c.createHash("md5").update(e._services.uuid()).digest("hex"),l.setValue("SNI_SERVER_ID",this._deviceID)}on(e,t){return"connection"!==e||this._initializationPromise||(this._onConnection=t,this._initialize()),this}_isUserHashValid(e){const t=this._authentication.getUserId();return t&&c.createHash("md5").update(t).digest("hex")===e}_ensureIdentityExists(){return r.isSelfSignedIdentityPresent(this._locationOfIdentity,this._deviceID).then(e=>{o.log(d,`Identity is already present for ${this._deviceID}.adobelocalhost.com`);const t=new Date(e.validFrom),i=new Date(e.validTo),n=new Date,a=u(i,t),c=u(i,n);return a>730||c<60?(o.log(d,"Current Identity is invalid so removing it and creating a new one"),s.unlinkSync(e.key),s.unlinkSync(e.cert),s.unlinkSync(e.dCert),r.createSelfSignedIdentity(this._locationOfIdentity,this._deviceID,".adobelocalhost.com","Adobe Creative Cloud","1","730")):e}).catch(()=>(o.log(d,`Creating new identity for ${this._deviceID}.adobelocalhost.com`),s.ensureDirSync(this._locationOfIdentity),r.createSelfSignedIdentity(this._locationOfIdentity,this._deviceID,".adobelocalhost.com","Adobe Creative Cloud","1","730")))}_enableSystemCertificatesInFirefox(){const e=l.getValue("FIREFOX_DIR");let t;try{t=s.readdirSync(e)}catch(e){return void o.log(d,"Skipping Firefox setup - Firefox is not installed")}t.forEach(t=>{const i=a.join(e,t,"user.js");try{const e=s.readFileSync(i,"utf8"),n="security.enterprise_roots.enabled";if(e.includes(`'${n}'`)||e.includes(`"${n}"`))return void o.log(d,`Skipping Firefox setup for profile ${t} - entry already present`)}catch(e){}try{s.appendFileSync(i,'\n// Adobe Creative Cloud in Microsoft Office\nuser_pref("security.enterprise_roots.enabled", true);\n',{encoding:"utf8"}),o.log(d,`Enabling system certificates for Firefox profile: ${t}`)}catch(e){o.log(d,`Failed to enable system certificates for Firefox profile: ${t}`)}})}_initiateCertificateTrustProcess(e){this._config.trustInProgress||(this._config.trustInProgress=!0,r.isCertificateTrusted(this._dCertificateLocation).then(e=>(this._config.certificateIsTrusted=e,this._config.certificateIsTrusted&&o.log(d,"Certificate is already trusted"),!e)).then(t=>!!t&&(o.log(d,"Starting the certificate trust process"),r.showDialog(this._ccLibraries._localisation.translate("LIBS_PROCESS_CERTIFICATE_TRUST_DIALOG_TITLE"),this._ccLibraries._localisation.translate("LIBS_PROCESS_CERTIFICATE_TRUST_DIALOG_MESSAGE"),this._ccLibraries._localisation.translate("LIBS_PROCESS_OK_LABEL"),this._ccLibraries._localisation.translate("LIBS_PROCESS_CANCEL_LABEL")).then(t=>t?r.addCertificateToTrustStore(this._dCertificateLocation,"Adobe Creative Cloud"):(function(e){const t=l.getValue("IDS_DECLINED_TO_TRUST_CERT")||{};t[e]=!0,l.setValue("IDS_DECLINED_TO_TRUST_CERT",t)}(e),Promise.reject(new Error("User declined to trust the certificate")))).then(()=>this._config.certificateIsTrusted=!0))).then(()=>this._enableSystemCertificatesInFirefox()).catch(e=>o.log(d,"Failed to trust the certificate: ",e)).then(()=>this._config.trustInProgress=!1))}_uploadServerData(e){if(this._config.dataUploadInProgress[e])return;const t=this._ccLibraries.getLoadedCollections().find(e=>!e.isPublic);if(!t)return o.log(d,`Upload secret token info for ${e} failed as there is no private collection loaded`);const i=this._ccLibraries._services.uuid();this._config.dataUploadInProgress[e]=!0,o.log(d,`Uploading secret token info for ${e} to the server`),t._syncManager.pushClientTokenInfo(e,{token:i,deviceID:this._deviceID,port:this.wssPort}).then(t=>{o.log(d,`Upload secret token info for ${e} was ${t?"success":"failure"}`),l.addWSSToken(i),this._config.dataUploaded[e]=t,this._config.dataUploadInProgress[e]=!1})}_sniCallback(e,t){const i=()=>t("error"),n=e.split(".",4);if(n.some((function(e){return!e}))||"adobelocalhost"!==n[2]||"com"!==n[3])return o.log(d,`serverName received is not as per the requirement: ${e}`),void setImmediate(i);if(!this._isUserHashValid(n[1]))return o.log(d,`userHash does not match: ${n[1]}`),void setImmediate(i);const r=n[0];return function(e){const t=l.getValue("IDS_DECLINED_TO_TRUST_CERT")||{};return Boolean(t[e])}(r)&&!this._config.certificateIsTrusted?(o.log(d,"user has declined to trust the certificate"),setTimeout(i,this._config.delayOnDecline)):this._config.certificateIsTrusted?this._config.dataUploaded[r]?void setTimeout(i,this._config.delayOnReady):(this._uploadServerData(r),setImmediate(i)):(this._initiateCertificateTrustProcess(r),setImmediate(i))}get sniPort(){return this._config.sniPort}get wssPort(){return l.getValue("WSS_PORT")||0}waitForInitialization(){return this._initializationPromise?this._initializationPromise:Promise.reject("TLSServer not yet initialized")}_initialize(){const e=this._ccLibraries.getOption("TLS_DISCOVERY_PORT_RANGE"),t=this.wssPort;let i,n;const r=this._sniCallback.bind(this);this._initializationPromise=this._ensureIdentityExists().then(t=>(i=s.readFileSync(t.cert),n=s.readFileSync(t.key),this._dCertificateLocation=t.dCert,function e(t,i,n,o,r){return o>r?Promise.reject(new Error("None of the ports in the specified range are available")):p({cert:t,key:i,SNICallback:n},o,"TLSDiscoveryServer").catch(()=>e(t,i,n,++o,r))}(i,n,r,e[0],e[1]))).then(e=>(this._sniServer=e,this._config.sniPort=e.address().port,p({cert:i,key:n},t,"wssUnderlyingServer"))).then(e=>{this._wssUnderlyingServer=e,l.setValue("WSS_PORT",e.address().port),this._wssServer=new h.Server({server:this._wssUnderlyingServer}),this._wssServer.on("connection",this._onConnection)}).catch(e=>(o.log(d,"Failed to launch tlsServer",e),Promise.reject(e)))}close(){this._sniServer&&this._sniServer.close(),this._wssServer&&this._wssServer.close(),this._wssUnderlyingServer&&this._wssUnderlyingServer.close(),this._sniServer=null,this._wssServer=null,this._wssUnderlyingServer=null,this._initializationPromise=null,this._config=_(this._ccLibraries)}}},function(e,t){e.exports=require("node_ssl")},function(e,t,i){const n=i(19),o=i(0),r=i(5),s=i(40),a=i(41),c=i(42),l=i(13),h=i(32),d=i(1),_=i(10),p="WebSocketServer";e.exports=class{constructor(e,t,i){this._server=e,this._channelManager=t,this._ccLibraryProcess=i,this._nextClientId=0,this._server.on("connection",this._onConnection.bind(this))}get _ccLibraries(){return this._ccLibraryProcess._ccLibraries}get _authentication(){return this._ccLibraryProcess._authentication}get _analytics(){return this._ccLibraryProcess._analytics}get _thorInterface(){return this._ccLibraryProcess._thorInterface}get _coreSyncInterface(){return this._ccLibraryProcess._coreSyncInterface}get _productBridge(){return this._ccLibraryProcess._productBridge}get _productLauncher(){return this._ccLibraryProcess._productLauncher}get _systemFonts(){return this._ccLibraryProcess._systemFonts}_onConnection(e,t){const i="client_"+this._nextClientId++,n=l.parseQueryString(t.url),c=n.version||0,h="true"===n.diagnostics;r.log(p,i,"Client connected: "+(h?"diagnostic":"version="+c));const d=this._channelManager.newChannel(e,c);d.onClose(()=>r.log(p,i,"Client disconnected")),d.onError(e=>{r.log(p,i,`Error on websocket: ${e}`),d.shutdown()}),d.setLogCallback(e=>r.log(p,i,e));let _=!1;if(n.token&&(_=n.token===o.getValue("SERVICE_TOKEN")||o.isWSSTokenValid(n.token)),n.diagnostics||this._analytics.reportEvent("clientConnected",{clientId:i,clientVersion:c,numClients:this._channelManager.numChannels(),hasToken:void 0!==n.token,isRejected:!_}),h)return void d.shutdown();const u=a.getEnvironmentData(this._ccLibraries,c);if(_&&d.send("environmentinfo",u),u.updateRequired)return r.log(p,i,"Incompatible version. Update required: "+u.updateRequired),void d.shutdown();if(!_)return r.log(p,i,"Client validation failed"),void d.shutdown();d.addListener("configure",e=>this._onConfigure(d,e)),d.addListener("sync",this._onSync.bind(this)),d.addListener("configuresync",this._onConfigureSync.bind(this)),d.addListener("clearcachedexternallink",this._onClearCachedExternalLink.bind(this)),d.addListener("canceloperation",this._onCancelOperation.bind(this)),d.addCallListener("commit",(e,t)=>this._onCommit(d,e,t)),d.addCallListener("startcomponentwrite",(e,t)=>this._onStartComponentWrite(d,e,t)),d.addCallListener("getrenditionpath",this._onGetRenditionPath.bind(this)),d.addCallListener("loadpubliclibrary",this._onLoadPublicLibrary.bind(this)),d.addCallListener("unloadpubliclibrary",this._onUnloadPublicLibrary.bind(this)),d.addCallListener("loadteamlibrary",this._onLoadTeamLibrary.bind(this)),d.addCallListener("refreshteams",this._onRefreshTeams.bind(this)),d.addCallListener("unloadteamlibrary",this._onUnloadTeamLibrary.bind(this)),d.addCallListener("createBookmark",(e,t)=>this._onCreateBookmark(d,e,t)),d.addCallListener("removeBookmark",this._onRemoveBookmark.bind(this)),d.addCallListener("downloadfile",this._onDownloadFile.bind(this)),d.addCallListener("downloadexternallink",this._onDownloadExternalLink.bind(this)),d.addCallListener("testexternallink",this._onTestExternalLink.bind(this)),d.addCallListener("fscall",this._onFSCall.bind(this)),d.addCallListener("fspipe",this._onFSPipe.bind(this)),d.addCallListener("performElementAction",this._onPerformElementAction.bind(this)),d.addCallListener("importlibrary",this._onImportLibrary.bind(this)),d.addCallListener("exportlibrary",this._onExportLibrary.bind(this)),d.addCallListener("movelibrary",this._onMoveLibrary.bind(this)),d.addCallListener("getImageDimensions",this._onGetImageDimensions.bind(this)),d.addCallListener("getfontdata",this._onGetFontData.bind(this)),d.addCallListener("getaccesstoken",this._onGetAccessToken.bind(this)),d.addCallListener("isfontavailable",this._onIsFontAvailable.bind(this)),d.addCallListener("computesha",this._onComputeSHA.bind(this)),d.addCallListener("openinccd",this._onOpenInCCD.bind(this));const m=this._ccLibraries.getLoadedCollections();0===m.length?d.send("clearcollections"):m.forEach(e=>{this._ccLibraries._config.isCollectionSupported(d.version,e)&&(d.send("collectionadded",a.getCollectionData(e)),d.send("syncstate",a.getSyncStateData(e)),e.isPrivate&&d.send("bookmarkschanged",s.getCollectionBookmarksData(e,d.version)))})}_getLibraryCollection(e){return c.getLibraryCollection(this._ccLibraries,e.isTeam,e.isPublic,e.userId,e.cloudId,e.platformDirectoryId)}_getLibrary(e,t){const i=this._getLibraryCollection(e);return i&&i.getLibraryById(e[t||"id"])}_getElement(e,t,i){const n=this._getLibrary(e,i);return n&&n.getElementById(e[t||"element"])}_getRepresentation(e){const t=this._getElement(e);return t&&t.getRepresentationById(e.representation)}_setAutoGC(e,t){const i=this._getLibrary(e);i&&i._setAutoGC("client_writing",t)}_notifyLocalLibraryChange(e,t,i){const n=e.getLibraryById(t);n&&(this._channelManager.broadcast("librarychange",a.getLibraryData(n),e=>e!==i),this._productBridge.libraryChanged(n,!0))}_onConfigure(e,t){t.CLIENT_DESCRIPTION&&r.log(p,"Configure: "+t.CLIENT_DESCRIPTION);let i=!1,n=!1;if(t.RENDITION_SIZES&&(this._ccLibraries._config.addToRenditionSizeConfig(t.RENDITION_SIZES),i=o.setValue("RENDITION_SIZES",this._ccLibraries._config.RENDITION_SIZES)),t.FULL_RENDITION_CONFIG&&(this._ccLibraries._config.addToFullRenditionConfig(t.FULL_RENDITION_CONFIG),n=o.setValue("FULL_RENDITION_CONFIG",this._ccLibraries._config.FULL_RENDITION_CONFIG)),(i||n)&&(c.triggerRenditionPrefetch(this._ccLibraries),this._productBridge.collectionsLoaded()),t.LOCAL_SETTINGS){Object.assign(this._ccLibraries._config.LOCAL_SETTINGS,t.LOCAL_SETTINGS),o.setValue("LOCAL_SETTINGS",this._ccLibraries._config.LOCAL_SETTINGS)&&this._channelManager.broadcast("environmentinfo",a.getEnvironmentData(this._ccLibraries),t=>t!==e)}}_onSync(e){const t=this._getLibraryCollection(e),i=t&&t.getPrimarySyncError();!!i&&i.code===d.ACCESS_DENIED||(t&&this._ccLibraryProcess._syncLibraryCollection(t),this._coreSyncInterface.ping())}_onConfigureSync(e){this._thorInterface.configureFileSyncing(e.enable)}_onCommit(e,t,i){const n=this._getLibraryCollection(t);h.obtainLock(t.id,()=>{const o=()=>{this._channelManager.getPendingWriteState(t.userId,t.cloudId,t.id,e)||this._setAutoGC(t,!0)},s=n=>{e.clearPendingWriteState(t.userId,t.cloudId,t.id).forEach(e=>{this._channelManager.getPendingWriteState(e.userId,e.cloudId,e.id)||this._setAutoGC(e,!0)}),i(n)},c=(o,r)=>{h.releaseLock(t.id);const c=n.getLibraryById(t.id);if(o){const e=c?a.getLibraryData(c):{};return e.success=!1,void i(e)}const l=(i,o)=>{r||this._notifyLocalLibraryChange(n,t.id,e),s({success:!0,renditions:i?[]:o})},d=t.renditions||[];c?c._renditionCache.applyRequestSetCache(d).then(e=>l(null,e),l).then(()=>c._prefetchRenditions()):l(null,new Array(d.length).fill(null))},l=n.getLibraryById(t.id);if(!l)return r.log(p,`Commit proceeding: creating new library: ${t.id}`),o(),void this._ccLibraries._storageInterface.createNewLibrary(n,t.id,t.current,c);const d=_.getManifestForComparison(l,t.current);_.areManifestsEqual(d,t.current)?(r.log(p,`Commit skipped: nothing changed: ${t.id}`),o(),c(null,!0)):_.areManifestsEqual(d,t.base)?(r.log(p,`Commit proceeding: fast-forward: ${t.id}`),o(),this._ccLibraries._storageInterface.updateExistingLibrary(n,l,t.current,t.base,void 0,c)):(r.log(p,`Commit fail: base mismatch: ${t.id}`),c(!0))})}_onGetRenditionPath(e,t){const i=this._getElement(e);i?i.getThumbnailPath(e.size,(e,i)=>t(i)):t()}_onStartComponentWrite(e,t,i){this._setAutoGC(t,!1),e.setPendingWriteState(t.userId,t.cloudId,t.id),(t.dependencies||[]).forEach(i=>{this._setAutoGC(i,!1),e.setPendingWriteDependency(t.userId,t.cloudId,t.id,i.userId,i.cloudId,i.id)}),i()}_onLoadPublicLibrary(e,t){const i=this._getLibraryCollection(e);i&&i.isPublic?i.loadLibrary({id:e.id,url:e.url},()=>t()):t()}_onUnloadPublicLibrary(e,t){const i=this._getLibraryCollection(e),n=i&&i.getLibraryById(e.id);i&&i.isPublic&&n?i.unloadLibrary(n,()=>t()):t()}_onLoadTeamLibrary(e,t){const i=this._getLibraryCollection(e);i&&i.isTeam?i.loadLibrary({id:e.id,urn:e.urn,teamUrn:e.teamUrn},()=>t()):t()}_onUnloadTeamLibrary(e,t){const i=this._getLibraryCollection(e),n=i&&i.getLibraryById(e.id);i&&i.isTeam&&n?i.unloadLibrary(n,()=>t()):t()}_onRefreshTeams(e,t){this._ccLibraryProcess.refreshTeams(!1,t)}_onCreateBookmark(e,t,i){const n=this._getLibraryCollection(t);if(n&&n.isPrivate){const o=t.type||"public",r=t.id,s=t.data||{url:t.url},c=t.condition;n._bookmarkManager.createBookmark(o,r,s,c,(t,o)=>{if(t=t&&a.prepareErrorForSerialization(t),!this._ccLibraries._config.isNewBookmarkFormatSupported(e.version))return i({err:t,bookmark:{_id:o.id,_url:o.url}});const r=n._bookmarkManager._toJSON();i({err:t,bookmarks:r})})}else i()}_onRemoveBookmark(e,t){const i=this._getLibraryCollection(e);if(i&&i.isPrivate){const n=i.bookmarks.find(t=>t.id===e.id);if(n)return void i.removeBookmark(n,t)}t()}_onDownloadFile(e,t){const i=this._getLibraryCollection(e);i?i._syncManager.links.download(e.url,e.headers,e.tempDir,void 0,(e,i,n,o)=>{t({err:e&&a.prepareErrorForSerialization(e),tempFilePath:i,etag:n,responseHeaders:o&&o.headers})}):t({err:new d(d.INVALID_PARAMETER,"Library collection not found")})}_onDownloadExternalLink(e,t){const i=this._getRepresentation(e);i?i.getContentPath((e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),path:i})}):t({err:new d(d.INVALID_PARAMETER,"Representation not found")})}_onTestExternalLink(e,t){const i=this._getRepresentation(e);i?i.testExternalLink((e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),success:i})}):t({err:new d(d.INVALID_PARAMETER,"Representation not found")})}_onClearCachedExternalLink(e){const t=this._getRepresentation(e);t&&t.isExternalLink&&t.clearCachedExternalLink()}_onFSCall(e,t){try{e.args.push((...e)=>t(e)),n[e.method].apply(n,e.args)}catch(e){t([e&&a.prepareErrorForSerialization(e)])}}_onFSPipe(e,t){try{const i=n.createReadStream(e.readStream.path,e.readStream.options),o=n.createWriteStream(e.writeStream.path,e.writeStream.options);let r=!1;const s=e=>(...i)=>{r||(r=!0,t({event:e,args:i}))};["end","error"].forEach(e=>i.on(e,s(e))),o.on("error",s("error")),i.pipe(o)}catch(e){t({event:"error",args:[e&&a.prepareErrorForSerialization(e)]})}}_onPerformElementAction(e,t){r.log(p,"Recieved Element Action "+JSON.stringify(e));const i=this._getElement(e,"elementId","libraryId");this._productLauncher.launch({appCode:e.appCode,minVersion:e.minVersion,element:i,action:e.action},(e,i)=>t({err:e,data:i}))}_onImportLibrary(e,t){const i=this._getLibraryCollection(e);i?i._doImportLibrary(e.path,(e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),libraryId:i&&i.id})},e.operationId):t({err:new d(d.INVALID_PARAMETER,"Library collection not found")})}_onExportLibrary(e,t){const i=this._getLibrary(e);i?i.collection._doExportLibrary(i,e.path,e=>{t({err:e&&a.prepareErrorForSerialization(e)})},e.operationId):t({err:new d(d.INVALID_PARAMETER,"Library not found")})}_onCancelOperation(e){const t=this._getLibraryCollection(e);t&&t._operationIdMap[e.operationId]&&t._operationIdMap[e.operationId].cancel()}_onMoveLibrary(e,t){const i=this._getLibrary(e),n=e.target&&this._getLibraryCollection(e.target);i&&n?i.collection.moveLibrary(i,n,(e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),libraryId:i&&i.id})}):t({err:new d(d.INVALID_PARAMETER,"Library or target collection not found")})}_onGetImageDimensions(e,t){this._ccLibraries._storageInterface.getImageDimensions(e,e=>t({data:e}))}_onGetFontData(e,t){const i=this._getLibraryCollection(e);i&&i.fontManager?i.fontManager.getFontData(e.fontId,(e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),data:i})}):t()}_onGetAccessToken(e,t){this._authentication.getClientAccessToken(e.userId,e.clientId,e.clientSecret,e.scopes,(e,i)=>{t({err:e&&a.prepareErrorForSerialization(e),data:i})})}_onOpenInCCD(e,t){r.log(p,`Recieved open-in CCD request: ${e.path}`),this._productLauncher.launchCCD(e.path,(e,i)=>t({err:e,data:i}))}_onComputeSHA(e,t){this._ccLibraries._services.fileUtils.computeSHA(e.path).then(e=>t({err:null,data:e}),e=>t({err:a.prepareErrorForSerialization(e)}))}_onIsFontAvailable(e,t){this._systemFonts.isFontAvailable(e.fontName,e.matchFamily).then(e=>t({data:e}))}}},function(e,t,i){var n=i(2),o=i(4);function r(e,t,i){e?this._setData(e):this._data={},this._readOnly=t,this._isRoot=i}r.ROOT_PATH="/",Object.defineProperties(r.prototype,{id:{get(){return this._data.id},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(this._owner)throw new n(n.READ_ONLY,"Cannot change the id of a node that is part of a branch or element.");if("string"!=typeof e||""===e)throw new n(n.INVALID_PARAMS,"Expecting a non-empty string.");this._data.id=e,this._setDirty()}},name:{get(){return this._data.name},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.name=e,this._setDirty()}},type:{get(){return this._data.type},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.type=e,this._setDirty()}},relationship:{get(){return this._data.rel},set(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new n(n.INVALID_PARAMS,"Expecting a string or undefined.");this._data.rel=e,this._setDirty()}},path:{get(){return this._isRoot?"/":this._data.path},set(e){if(e!==this.path){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if(this._isRoot)throw new n(n.READ_ONLY,"Cannot change the path of the root node.");if(e&&!o.isValidPath(e))throw new n(n.INVALID_PARAMS,"Expecting a valid path or undefined.");this._owner?this._owner._setPathOfNode(this,e||void 0):(this._data.path=e||void 0,this._parentPath=""),this._setDirty()}}},parentPath:{get(){return this._parentPath},set(){throw new n(n.READ_ONLY,"parentPath is read-only.")}},absolutePath:{get(){var e=this.path;return this._isRoot?e:e&&this._owner?o.appendPathElements(this._parentPath,e):void 0},set(){throw new n(n.READ_ONLY,"absolutePath is read-only.")}},isRoot:{get(){return this._isRoot},set(){throw new n(n.READ_ONLY,"isRoot is read-only.")}}}),r.prototype.getLink=function(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');return this._data._links?this._data._links[e]:void 0},r.prototype.setLink=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("object"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "link" must be an object.');if("string"!=typeof t)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');var i=this._data._links;i||(i=this._data._links={}),i[t]=e,this._setDirty()},r.prototype.removeLink=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "relationship" must be a string');var t=this._data._links;t&&(delete t[e],Object.keys(t).length<1&&delete this._data._links,this._setDirty())};var s={components:!0,children:!0,"manifest-format-version":!0,id:!0,name:!0,type:!0,state:!0,local:!0},a={components:!0,children:!0,rel:!0,path:!0,id:!0,name:!0,type:!0};r.prototype.getCustomKeys=function(){var e,t=[],i=Object.keys(this._data),n=i.length;for(e=0;e<n;e++){var o=i[e];(this._isRoot?s[o]:a[o])||t.push(o)}return t},r.prototype.getValue=function(e){if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');if("children"===e||"components"===e)throw new n(n.INVALID_PARAMS,"Illegal key");return this._data[e]},r.prototype.setValue=function(e,t){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');if("children"===e||"components"===e)throw new n(n.INVALID_PARAMS,"Illegal key");this._data[e]=t,this._setDirty()},r.prototype.removeValue=function(e){if(this._readOnly)throw new n(n.READ_ONLY,"This object is read-only.");if("string"!=typeof e)throw new n(n.INVALID_PARAMS,'Param "key" must be a string');if("children"===e||"components"===e)throw new n(n.INVALID_PARAMS,"Illegal key");delete this._data[e],this._setDirty()},r.prototype.copy=function(){var e=null,t=this._data.children,i=this._data.components;try{t&&delete this._data.children,i&&delete this._data.components,e=new r(JSON.parse(JSON.stringify(this._data)))}finally{t&&(this._data.children=t),i&&(this._data.components=i)}return e},r.prototype.isEqualTo=function(e,t,i){return this._isEqual(this._data,e._data,o.merge({children:!0,components:!0},t),i)},r.prototype._isEqual=function(e,t,i,n){var r,s,a,c,l,h,d;if(!o.objectsEqual(e,t,i))return!1;if(s=e.components,a=t.components,(c=s?s.length:0)!==(a?a.length:0))return!1;if(c)for(r=0;r<c;r++){for(l=s[r],h=null,d=0;d<c;d++)if(l.id===a[d].id){h=a[d];break}if(!h)return!1;if(!o.objectsEqual(l,h,n))return!1}if(s=e.children,a=t.children,(c=s?s.length:0)!==(a?a.length:0))return!1;if(c)for(r=0;r<c;r++)if(!this._isEqual(s[r],a[r],i,n))return!1;return!0},r.prototype._setData=function(e){var t=this._verify(e);if(null===t)return this._data=e,this;throw t},r.prototype._verify=function(e){return"string"!=typeof e.id?new n(n.INVALID_DATA,"Node is missing an id of type string"):null},r.prototype._setDirty=function(){this._owner&&this._owner._setDirty()},e.exports=r},function(e,t,i){var n=i(44),o=i(2),r=i(4);function s(e,t,i){(this._owner=t,e)?e=this._setData(e,i):(e={id:r.generateUuid()},this._core=new n(e,this,i),this._data=e)}Object.defineProperties(s.prototype,{rootNode:{get(){return this._core.rootNode},set(e){this._core.rootNode=e}},name:{get(){return this._core.rootNode.name},set(e){var t=this._core;if(t._readOnly)throw new o(o.READ_ONLY,"This object is read-only.");if("string"!=typeof e&&void 0!==e)throw new o(o.INVALID_PARAMS,"Expecting a string or undefined.");t.rootNode.name=e}},type:{get(){return this._core.rootNode.type},set(e){var t=this._core;if(t._readOnly)throw new o(o.READ_ONLY,"This object is read-only.");if("string"!=typeof e||""===e)throw new o(o.INVALID_PARAMS,"Expecting a non-empty string.");t.rootNode.type=e}},compositeHref:{get(){return this._owner.compositeHref},set(){throw new o(o.READ_ONLY,'Property "compositeHref" is read-only.')}},_localStorage:{get(){return this._core._localStorage},set(e){this._core._localStorage=e}},hasLocalStorage:{get(){return this._core.hasLocalStorage},set(e){this._core.hasLocalStorage=e}},_isDirty:{get(){return this._core._isDirty},set(e){this._core._isDirty=e}},isDirty:{get(){return this._isDirty},set(e){this._core.isDirty=e}},changeCount:{get(){return this._core.changeCount},set(e){this._core.changeCount=e}}}),s.prototype.getChildWithId=function(e){return this._core.getChildWithId(e)},s.prototype.getChildWithAbsolutePath=function(e){return this._core.getChildWithAbsolutePath(e)},s.prototype.getChildrenOf=function(e){return this._core.getChildrenOf(e)},s.prototype.addChild=function(e,t,i,n){return this._core.addChild(e,t,i,n)},s.prototype.removeChild=function(e){return this._core.removeChild(e)},s.prototype.moveChild=function(e,t,i){return this._core.moveChild(e,t,i)},s.prototype.copyChild=function(e,t,i,n,o,r){return this._core.copyChild(e,t,i,n,o,r)},s.prototype.allComponents=function(){return this._core.allComponents()},s.prototype.getComponentWithId=function(e){return this._core.getComponentWithId(e)},s.prototype.getComponentWithAbsolutePath=function(e){return this._core.getComponentWithAbsolutePath(e)},s.prototype.getComponentsOf=function(e){return this._core.getComponentsOf(e)},s.prototype.addComponent=function(e,t,i,n,o,r,s,a,c,l){return this._core.addComponent(e,t,i,n,o,r,s,a,c,l)},s.prototype.addComponentWithUploadResults=function(e,t,i,n,o){return this._core.addComponentWithUploadResults(e,t,i,n,o)},s.prototype.updateComponent=function(e,t,i,n){return this._core.updateComponent(e,t,i,n)},s.prototype.updateComponentWithUploadResults=function(e,t){return this._core.updateComponentWithUploadResults(e,t)},s.prototype.removeComponent=function(e){return this._core.removeComponent(e)},s.prototype.moveComponent=function(e,t){return this._core.moveComponent(e,t)},s.prototype.copyComponent=function(e,t,i,n,o){return this._core.copyComponent(e,t,i,n,o)},s.prototype.assetOfComponent=function(e,t){return this._core.assetOfComponent(e,t)},s.prototype.parse=function(e){if("string"!=typeof e)throw new o(o.INVALID_PARAMS,'Param "data" must be a string');var t=null;try{t=JSON.parse(e)}catch(e){throw new o(o.INVALID_JSON,"Manifest could not be parsed. Underlying error: "+e.message)}return this._setData(t,this._core._readOnly)},s.prototype.copy=function(){return new s(JSON.parse(JSON.stringify(this._data)),this._owner)},s.prototype._updateLocalDataFromBranch=function(e){if(this._readOnly)throw new o(o.READ_ONLY,"This object is read-only.");if(!this._localStorage)throw new o(o.NO_LOCAL_STORAGE,"No local storage.");if(!e._localStorage)throw new o(o.NO_LOCAL_STORAGE,"No local storage for source.");if(this._localStorage.compositePath!==e._localStorage.compositePath)throw new o(o.INVALID_PARAMS,"Branches must have same storage path.");this._core._localStorage.copyLocalStorageData(e,e._core._local(),this,this._core._local()),this._core._copySourceHrefsFrom(e._core)},s.prototype._verify=function(e){return"string"!=typeof e.id?new o(o.INVALID_DATA,"Element is missing an id of type string"):"string"!=typeof e.name?new o(o.INVALID_DATA,"Element is missing a name of type string"):"string"!=typeof e.type?new o(o.INVALID_DATA,"Element is missing a type of type string"):null},s.prototype._setData=function(e,t){var i=this._verify(e);if(null===i)return this._core=new n(e,this,t),this._data=e,this;throw i},s.prototype._local=function(){return this._core._local()},s.prototype._setDirty=function(e){this._core._setDirty(e)},s.prototype._setPathOfNode=function(e,t){this._core._setPathOfNode(e,t)},s.prototype._verifyIntegrity=function(e,t,i){return this._core._verifyIntegrity(e,t,i)},e.exports=s},function(e,t,i){const n=i(2),o=i(4),r=i(11),s=i(111);function a(e,t){if("string"!=typeof e||""===e)throw new n(n.INVALID_PARAMS,'Param "compositePath" must be a non-empty string.');this._compositePath=e,this._preserveFileExtensions=t,this._inMemoryBranchesAndElements=[],this._inflightComponents=[]}Object.defineProperties(a.prototype,{compositePath:{get(){return this._compositePath},set(e){if("string"!=typeof e||""===e)throw new n(n.INVALID_PARAMS,'Param "compositePath" must be a non-empty string.');this._compositePath=e}}}),a.prototype.currentManifestPath=function(){return this._compositePath+"/manifest"},a.prototype.currentBaseManifestPath=function(){return this._compositePath+"/manifest.base"},a.prototype.pulledManifestPath=function(){return this._compositePath+"/pull.manifest"},a.prototype.pushedManifestPath=function(){return this._compositePath+"/push.manifest"},a.prototype.resolvePulledBranch=function(e,t){r.writeFileAtomically(this.currentManifestPath(),e.localData,"utf8",e=>{e?(e.code!==n.OUT_OF_SPACE&&(e=new n(n.INVALID_STATE,"Could not write current manifest.",e)),t(e)):r.move(this.pulledManifestPath(),this.currentBaseManifestPath(),!1,e=>{e?t(new n(n.INVALID_STATE,"Could not move pull manifest.",e)):(this._pullJournal&&this._pullJournal.clear(),t())})})},a.prototype.acceptPushedBranch=function(e,t){var i=this;r.writeFileAtomically(this.currentManifestPath(),e.localData,"utf8",(function(e){e?(e.code!==n.OUT_OF_SPACE&&(e=new n(n.INVALID_STATE,"Could not write current manifest.",e)),t(new n(n.INVALID_STATE,"Could not write current manifest.",e))):r.move(i.pushedManifestPath(),i.currentBaseManifestPath(),!1,(function(e){e?t(new n(n.INVALID_STATE,"Could not move push manifest.",e)):i._deleteJournal(t)}))}))},a.prototype.discardPulledBranch=function(e){r.deleteFile(this.pulledManifestPath(),e)},a.prototype.discardPushedBranch=function(e){var t=this;r.deleteFile(this.pushedManifestPath(),(function(i){i?e(i):t._deleteJournal(e)}))},a.prototype.discardBaseBranch=function(e){r.deleteFile(this.currentBaseManifestPath(),e)},a.prototype.registerInMemoryBranchOrElement=function(e){if(this._inMemoryBranchesAndElements.indexOf(e)>=0)throw new n(n.INVALID_STATE,"Branch or element is already registered.");this._inMemoryBranchesAndElements.push(e)},a.prototype.unregisterInMemoryBranchOrElement=function(e){var t=this._inMemoryBranchesAndElements.indexOf(e);if(t<0)throw new n(n.INVALID_STATE,"Unknown branch or element.");this._inMemoryBranchesAndElements.splice(t,1)},a.prototype._deleteJournal=function(e){r.deleteFile(this.pushJournalPath(),e)};var c=/(\/)|(\.$)/;a.prototype.componentAssetName=function(e,t){var i=t["copyOnWrite#storageIds"],n=i?i[e.id]:null;return n&&c.test(n)&&(n=null),n},a.prototype.componentAssetPath=function(e,t){var i=this.componentAssetName(e,t);return i?this._componentPathFromName(i):null},a.prototype.ingestComponentAsset=function(e,t,i,o,s){var a=this,c=this._newFileNameForComponent(e),l=this._componentPathFromName(c);this._inflightComponents.push(c);var h=function(t){if(!t)try{a._setComponentName(e,o,c)}catch(e){t=e}var i=a._inflightComponents.indexOf(c);i<0&&!t&&(t=new n(n.INVALID_STATE,"Could not find inflight component.")),a._inflightComponents.splice(i,1),s(t)};i?r.copyFile(t,l,h):r.move(t,l,!0,h)},a.prototype.removeComponentAsset=function(e,t){var i=t["copyOnWrite#storageIds"];i&&delete i[e.id]},a.prototype.componentIds=function(e){var t=e["copyOnWrite#storageIds"];return t?Object.keys(t):[]},a.prototype.copyLocalStorageData=function(e,t,i,n){var o,r=i.allComponents(),s=r.length,a=t["copyOnWrite#storageIds"];if(a){var c=n["copyOnWrite#storageIds"];for(c||(c=n["copyOnWrite#storageIds"]={}),o=0;o<s;o++){var l=r[o],h=l.id,d=e.getComponentWithId(h);if(d&&d.etag===l.etag){var _=a[h];_&&(c[h]=_)}}}},a.prototype.removeUnusedLocalFiles=function(e,t){var i,o,s,a,c,l=this,h=function(e){l._deleteComponentAsset(e,(function(e){e&&!i&&(i=e),0===--c&&t(i)}))},d=function(){try{var e,i=a.length,n=[];for(e=0;e<i;e++){var r=a[e].name,d=a[e].info;!o[r]&&d.mtime.getTime()<s&&l._inflightComponents.indexOf(r)<0&&n.push(r)}if((c=i=n.length)>0)for(e=0;e<i;e++)h(n[e])}catch(e){return void t(e)}0===c&&t()};this._gatherComponentAssetNames([this.currentManifestPath(),this.currentBaseManifestPath(),this.pulledManifestPath(),this.pushedManifestPath()],e,(function(e,r,c,l){if(i)t(i);else{if(!e)try{if(r<1||!l)throw new n(n.INVALID_STATE,r<1?"No manifest found.":"Invalid time stamp");o=c,s=l}catch(t){e=t}e&&(i=e),a&&(i?t(i):d())}})),r.directoryListing(this._compositePath+"/components",(function(e,n){if(i)t(i);else{if(!e)try{a=n}catch(t){e=t}e&&(i=e),o&&(i?t(i):d())}}))},a.prototype.tempPathForComponent=function(){return this._compositePath+"/tmp/"+o.generateUuid()},a.prototype.deleteTempFiles=function(e){r.deleteDirectory(this._compositePath+"/tmp",e)},a.prototype.clientDataPath=function(){return this._compositePath+"/clientdata"},a.prototype.pushJournalPath=function(){return this._compositePath+"/push.journal"},a.prototype.pullJournalPath=function(){return this._compositePath+"/pull.journal"},a.prototype.loadPullJournal=function(){return this._pullJournal?Promise.resolve(this._pullJournal):(this._pullJournal=new s(this.pullJournalPath()),this._pullJournal.load())},a.prototype._copyComponentMapping=function(e,t,i,n){var o=t["copyOnWrite#storageIds"];if(o){var r=n["copyOnWrite#storageIds"];r||(r=n["copyOnWrite#storageIds"]={});var s=o[e];return s&&(r[i]=s),s}},a.prototype._componentPathFromName=function(e){return this._compositePath+"/components/"+e},a.prototype._newFileNameForComponent=function(e){var t=o.generateUuid();if(this._preserveFileExtensions){var i=e.path?o.filePathComponents(e.path).extension:null;i&&(t=t+"."+i)}return t},a.prototype._setComponentName=function(e,t,i){var n=t["copyOnWrite#storageIds"];n||(n=t["copyOnWrite#storageIds"]={}),n[e.id]=i},a.prototype._gatherComponentAssetNames=function(e,t,i){try{var n,s,a={},c=t||o.timeStamp(!0),l=e.length,h=l,d=0,_=function(e){if(e){e=e["copyOnWrite#storageIds"];var t,i=Object.keys(e);for(t=0;t<i.length;t++){var n=e[i[t]];a[n]=!0}}},p=function(e){r.exists(e,(function(t){t?(d++,r.info(e,(function(t,n){if(!t)try{var o=n.mtime.getTime();o<c&&(c=o),r.readFile(e,"utf8",(function(e,t){if(h--,!e)try{t=JSON.parse(t),_(t.local)}catch(t){e=t}e&&!s&&(s=e),0===h&&i(s,d,a,c)}))}catch(e){t=e}t&&(h--,s||(s=t),0===h&&i(s))}))):0===--h&&i(s,d,a,c)}))};for(n=0;n<l;n++)p(e[n]);for(l=this._inMemoryBranchesAndElements.length,n=0;n<l;n++)_(this._inMemoryBranchesAndElements[n]._local())}catch(e){i(e)}},a.prototype._deleteComponentAsset=function(e,t){r.deleteFile(this._componentPathFromName(e),t)},e.exports=a},function(e,t,i){const n=i(11),o=i(4);e.exports=class{constructor(e){this._filePath=e,this._data={version:1,downloadedComponents:{}}}saveComponentPath(e){const t=e._owner;return this._data.downloadedComponents=this._data.downloadedComponents||[],this._data.downloadedComponents[e.id]={version:e.version,path:t._localStorage.componentAssetName(e,t._local())},this.save()}restoreComponentPath(e){const t=e._owner,i=this._data.downloadedComponents[e.id];return!(!i||i.version!==e.version)&&(t._localStorage._setComponentName(e,t._local(),i.path),!0)}clear(){return this._data.downloadedComponents=[],this.save()}load(){return new Promise(e=>{n.readFile(this._filePath,"utf8",(t,i)=>{let n;try{n=JSON.parse(i)}catch(t){}n&&1===n.version&&n.downloadComponents&&(this._data=n),e(this)})})}_doSave(){return new Promise(e=>{const t=t=>{t&&o.log(`Error writing pull journal: ${t}`),e()};0===this._data.downloadedComponents.length?n.deleteFile(this._filePath,t):n.writeFileAtomically(this._filePath,JSON.stringify(this._data),"utf8",t)})}save(){return this._savingPromise?this._pendingSave=!0:this._savingPromise=this._doSave().then(()=>{if(delete this._savingPromise,this._pendingSave)return delete this._pendingSave,this.save()}),this._savingPromise}}},function(e,t,i){var n=i(4),o=i(2),r=i(11);const s=i(28),a=i(46),c=i(113).TextEncoder;var l,h;l=i(24),h=i(34);var d=n.merge;function _(e){this._requestQueue=[],this._requestsOutstanding=[],this._rejectedAuths=[],this._authCallback=e,this._isActive=!0,this._waitingForAuthentication=!!e,this._currentAuthId=n.generateUuid(),this._https=l,this._XMLHttpRequest=void 0,this._handlesRedirects=!1,this._maxOutstanding=5}Object.defineProperties(_.prototype,{isActive:{get(){return this._isActive},set(e){this._isActive!==e&&(this._isActive=e,e||(this._authValue=void 0,this._checkQueue()))}},crossOriginCredentials:{get(){return this._withCredentials},set(e){this._withCredentials=e}},maxOutstanding:{get(){return this._maxOutstanding},set(e){this._maxOutstanding=e,this._checkQueue()}},handlesRedirects:{get(){return this._handlesRedirects}}}),_.prototype._forceXhr=function(e,t){this._https=void 0,this._XMLHttpRequest=e||void 0,this._handlesRedirects=!t},_.prototype.setAdditionalHeaders=function(e){this._additionalHeaders=e||{}},_.prototype.setAdditionalNodeOptions=function(e){this._additionalNodeOptions=e},_.prototype.setApiKey=function(e){this._apiKey=e},_.prototype.setTimeout=function(e){this._timeout=e},_.prototype.setAuthToken=function(e){e?(this._authValue="Bearer "+e,this.resume()):(this._authValue=void 0,this._currentAuthId=n.generateUuid())},_.prototype.resume=function(){this._currentAuthId=n.generateUuid(),this._waitingForAuthentication=!1,this._checkQueue()},_.prototype.setRequestHooks=function(e,t){this._beforeHook=e,this._afterHook=t},_.prototype.invoke=function(e,t,i,a,c,l){if(void 0===t)return l(new o(o.INVALID_PARAMS,"No href provided"));var h=(c=c||{}).responseType;if(h instanceof s){if(!r.canUseFileSystem)throw new o(o.INVALID_PARAMS,"No filesystem access")}else if("buffer"===h){if("function"!=typeof Buffer)throw new o(o.INVALID_PARAMS,"No Buffer class")}else if("blob"===h){if("function"!=typeof Blob)throw new o(o.INVALID_PARAMS,"No Blob class")}else if(h&&"text"!==h&&"json"!==h&&"arraybuffer"!==h)throw new o(o.INVALID_PARAMS,"Unsupported response type");i=d({},i,this._additionalHeaders),this._apiKey&&(i["x-api-key"]=this._apiKey);var _={method:e,href:t,headers:i,callback:l,body:a,options:c},p=c.reuseRequestDesc;if(p){if(this._requestQueue.indexOf(p)>=0||this._requestsOutstanding.indexOf(p)>=0)throw new o(o.INVALID_PARAMS,"Request descriptor still in use.");_=n.merge(p,_)}return this._doRequest(_),_},_.prototype._getSize=function(e){return new Promise(t=>{e instanceof s?r.info(e.filename,(e,i)=>t(i&&i.size)):"string"==typeof e?t((new c).encode(e).length):t()})},_.prototype._doRequest=function(e){var t,i,c,l=this,_=0,p=[],u=e.body,m=e.options.responseType;function g(t,r){if(t)n.log("["+e.id+"] error: "+t);else{const t=(new Date).valueOf()-e.startTime;r.complete?n.log("["+e.id+"] success ("+t+"ms)"):n.log("["+e.id+"] success ("+t+"ms) but response is incomplete")}var s=l._requestsOutstanding.indexOf(e);s>=0&&l._requestsOutstanding.splice(s,1);var a=e.callback;a&&(e.callback=void 0,t&&(t.clientRequest=e.clientRequest,t.xhr=e.xhr),t&&t.code!==o.SERVICE_IS_INACTIVE&&!l._isActive?t=new o(o.SERVICE_IS_INACTIVE,"Service is now inactive",t):e.timedOut&&(t=new o(o.TIMED_OUT,"timed out request",t)),a(t,r)),i&&i.end(),l._isActive&&l._checkQueue()}if(!this._isActive)return g(new o(o.SERVICE_IS_INACTIVE,"Network request in inactive state"));function f(t){var a=!1,c=!1,h=!1;function d(){if(!c)return c=!0,i=void 0,g(void 0,t)}var _=l._requestsOutstanding.indexOf(e);if(_<0)l._checkQueue();else{e.response=t;var u=(new Date).valueOf()-e.startTime;if(n.log("["+e.id+"] "+t.statusCode+" ("+u+"ms)"),401===t.statusCode&&l._authCallback)l._requestsOutstanding.splice(_,1),l._requestQueue.unshift(e),l._authFail(e),n.consumeStream(t);else{var f=e.progress;200===t.statusCode||201===t.statusCode||202===t.statusCode?(t.on("data",(function(e){e.length&&f&&f(e.length),!i&&e&&p.push(e)})),l._https&&m instanceof s&&(i=r.createWriteStream(m.filename),t.pipe(i),a=!0)):n.consumeStream(t),t.once("end",(function(){h=!0;var i=l._requestsOutstanding.indexOf(e);if(!(i<0||(l._requestsOutstanding.splice(i,1),l._checkQueue(),a||c)))return c=!0,t.response=Buffer.concat(p),"arraybuffer"===m?t.response=new ArrayBuffer(t.response):"text"===m&&(t.response=t.response.toString()),g(void 0,t)}));const _=()=>{if(!h&&!c)return c=!0,g(new o(o.NETWORK_ERROR,"incomplete response"))};t.once("close",_),t.once("aborted",()=>{t.complete||_()}),a&&(i.once("finish",d),i.once("close",d))}}}function E(t){t.pipe(c),t.on("error",(function(t){g(new o(o.TERMINATED_INPUTSTREAM,"Input stream terminated abnormally",t)),l.abort(e)}))}if(this._waitingForAuthentication||this._requestsOutstanding.length>=this._maxOutstanding||e.options.noSoonerThen)this._requestQueue.push(e),this._waitingForAuthentication||this._checkQueue();else{var y=e.headers;if(0!==e.href.indexOf("https:"))return g(new o(o.INVALID_PARAMS,"http not supported - network requests must use https"));if(null===y.Authorization?delete y.Authorization:this._authValue&&(y.Authorization=this._authValue),this._currentAuthId&&(e.authId=this._currentAuthId),this._beforeHook&&this._beforeHook(e),e.id=n.generateUuid(),e.startTime=(new Date).valueOf(),null!==y["X-Request-Id"]?y["X-Request-Id"]=e.id:delete y["X-Request-Id"],this._https){this._requestsOutstanding.push(e);var v=h.parse(e.href),A=d({},this._additionalNodeOptions,v);A.method=e.method||"GET",A.headers=y,n.log("["+e.id+"] "+A.method+" "+e.href),this._getSize(u).then(t=>{t&&(null===A.headers["Content-Length"]?delete A.headers["Content-Length"]:void 0===A.headers["Content-Length"]&&(A.headers["Content-Length"]=t)),c=this._https.request(A,f),e.clientRequest=c,c.once("error",g),c.once("abort",()=>g(new o(o.NETWORK_ERROR,"Request aborted"))),l._timeout&&c.setTimeout(l._timeout,(function(){e.timedOut=!0,c.abort()})),e.bytesSent=0,e.bytesReported=0,c.once("end",(function(){if(e.progress){var t=e.bytesSent-e.bytesReported;t>0&&(e.progress(t),e.bytesReported+=t)}}));var i=c.write;if(c.write=function(t){var n=t&&t.length;return n&&(e.bytesSent+=n),i.call(c,t,(function(){e.progress&&t&&(e.progress(n),e.bytesReported+=n)}))},u instanceof s){E(r.createReadStream(u.filename,u.range))}else if(u instanceof a){if(u.getStream)E(u.getStream());else u.getStreamAsync&&u.getStreamAsync((function(t,i){if(t)return g(new o(o.TERMINATED_INPUTSTREAM,"Error creating input stream",t)),void l.abort(e);E(i)}))}else if(u instanceof Buffer)c.write(u),c.end();else if(u instanceof ArrayBuffer)c.write(Buffer.from(new Int8Array(u))),c.end();else if("string"==typeof u)c.write(Buffer.from(u,"utf8")),c.end();else{if(u)return g(new o(o.INVALID_PARAMS,"Invalid data type"));c.end()}this._afterHook&&this._afterHook(e,c)}).catch(g)}else{if(u instanceof s)return r.canUseFileSystem?void r.readFile(u.filename,{},(function(t,i){if(t)return g(t);e.body=i,l._doRequest(e)})):g(new o(o.INVALID_PARAMS,"Can't use FileContent without filesystem support"));var C;for(C in"function"==typeof Buffer&&u instanceof Buffer&&(e.body=u=new Int8Array(u)),this._requestsOutstanding.push(e),n.log("["+e.id+"] "+e.method+" "+e.href),(t=new this._XMLHttpRequest).open(e.method,e.href,!0),this._withCredentials&&(t.withCredentials=!0),m&&(t.responseType=m instanceof s?"buffer":m),t.onreadystatechange=function(){var i=e.progress;if(i&&t.response){var a=t.response.length;i(a-_),_=a}if(4===t.readyState){if(0===t.status)return g(new o(o.UNEXPECTED,"XHR failure"));var c=l._requestsOutstanding.indexOf(e);if(c<0)l._checkQueue();else{var h=(new Date).valueOf()-e.startTime;if(n.log("["+e.id+"] "+t.status+" ("+h+"ms)"),l._requestsOutstanding.splice(c,1),401!==t.status||!l._authCallback){if(e.xhr=t,e.response=t,t.statusCode=t.status,t.headers=n.parseHeaders(t.getAllResponseHeaders()),m instanceof s){var d=t.response.response;return void r.writeFileAtomically(m.filename,d,void 0,(function(e){return e?g(new o(o.UNEXPECTED,"Can't create file",e,t)):g(void 0,t)}))}return i&&u&&i(u.length||u.size),g(void 0,t)}l._requestQueue.unshift(e),l._authFail(e),l._checkQueue()}}},y)y.hasOwnProperty(C)&&t.setRequestHeader(C,y[C]);e.xhr=t,l._timeout&&(t.timeout=l._timeout,t.ontimeout=function(){e.timedOut=!0,t.abort()}),u?t.send(u):t.send(),this._afterHook&&this._afterHook(e,t)}}},_.prototype._authFail=function(e){if(this._authCallback){var t=e.authId;if(-1!==this._rejectedAuths.indexOf(t))return;this._authValue=null,this._waitingForAuthentication=!0,this._rejectedAuths.unshift(t)>this._maxOutstanding&&(this._rejectedAuths.length=this._maxOutstanding),this._authCallback(this)}},_.prototype._checkQueue=function(){if(!this._isActive){var e=this._requestsOutstanding;this._requestsOutstanding=[],e.forEach((function(e){e.xhr&&e.xhr.abort(),e.clientRequest&&e.clientRequest.abort();var t=e.callback;t&&(e.callback=void 0,t(new o(o.SERVICE_IS_INACTIVE,"Network request in inactive state")))}));var t=this._requestQueue;return this._requestQueue=[],t.forEach((function(e){var t=new o(o.SERVICE_IS_INACTIVE,"Network request in inactive state"),i=e.callback;i&&(e.callback=void 0,i(t))})),void(this._checkQueueTimerId&&(clearTimeout(this._checkQueueTimerId),this._checkQueueTimerId=void 0,this._checkQueueTimerWhen=void 0))}for(var i,n=Date.now(),r=n+3e5,s=0;!(this._waitingForAuthentication||this._requestsOutstanding.length>=this._maxOutstanding||s>=this._requestQueue.length);){var a=this._requestQueue[s];(i=a.options.noSoonerThen||n)&&i>r&&(i=a.options.noSoonerThen=r),i<=n?(this._requestQueue.splice(s,1),a.options.noSoonerThen=void 0,this._doRequest(a)):s++}if(!this._waitingForAuthentication&&this._requestsOutstanding.length<this._maxOutstanding&&this._requestQueue.length>0){var c,l,h=this._requestQueue.length;for(l=0;l<h;l++)(i=this._requestQueue[l].options.noSoonerThen)&&i>r&&(i=this._requestQueue[l].options.noSoonerThen=r),i&&(c=c&&c<i?c:i);if(c&&(!this._checkQueueTimerWhen||this._checkQueueTimerWhen>c)){this._checkQueueTimerId&&clearTimeout(this._checkQueueTimerId),this._checkQueueTimerWhen=c;var d=this;this._checkQueueTimerId=setTimeout((function(){d._checkQueueTimerWhen=void 0,d._checkQueueTimerId=void 0,d._checkQueue()}),c-n)}}},_.prototype.abort=function(e){var t=this._requestQueue.indexOf(e);t>=0?this._requestQueue.splice(t,1):(t=this._requestsOutstanding.indexOf(e))>=0&&(this._requestsOutstanding.splice(t,1),e.xhr&&e.xhr.abort(),e.clientRequest&&e.clientRequest.abort(),this._checkQueue())};const p=e=>{const t=e&&e.callback;t&&(e.callback=void 0,t(new o(o.NETWORK_ERROR,"Request aborted")))};_.prototype.abortAllWithToken=function(e){if(e){for(let t=0;t<this._requestQueue.length;++t){const i=this._requestQueue[t];i.token===e&&(p(i),this._requestQueue.splice(t,1),--t)}for(let t=0;t<this._requestsOutstanding.length;++t)if(this._requestsOutstanding[t].token===e){const e=this._requestsOutstanding[t];this._requestsOutstanding.splice(t,1),--t,e.xhr&&e.xhr.abort(),e.clientRequest&&e.clientRequest.abort()}this._checkQueue()}},_.prototype.abortAll=function(){this._requestQueue.slice().forEach(p),this._requestQueue=[],this._requestsOutstanding.slice().forEach(e=>{e.xhr&&e.xhr.abort(),e.clientRequest&&e.clientRequest.abort()}),this._requestsOutstanding=[],this._checkQueue()},e.exports=_},function(e,t){e.exports=require("util")},function(e,t,i){var n=i(47),o=i(2),r=i(14),s=i(49),a=o.networkError,c=o.unexpectedResponse,l=i(4),h=l.appendPathElements;const d=/^https:\/\/platform-cs(?:-stage)?(?:-[a-zA-Z0-9]+)?\.adobe\.io/;e.exports=class extends n{constructor(e,t,i,n){super(e,t,i),this._platformEndpoint=n}getCollection(e,t,i){if(!(e=this._resolveUrl(e)))return i(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+e));var n;e+="?order=asc&orderby=name";var r={};t&&(r["If-None-Match"]=t);var s=this;return this._service.invoke("GET",e,r,void 0,{responseType:"text"},(function t(l,h){if(l)return i(a("Error retrieving a collection",l,h));if(200===h.statusCode){var d,_=h.responseText||h.response;try{d=JSON.parse(_)}catch(e){return(l=new o(o.INVALID_DATA,"Invalid JSON returned by server",e)).response=h,i(l)}n?n.children=n.children.concat(d.children):n=d;var p=h.headers["x-children-next-start"];if(p){var u=e+"&start="+p;s._service.invoke("GET",u,r,void 0,{responseType:"text"},t)}else i(void 0,n,h.headers.etag,h.headers)}else 304===h.statusCode?i(void 0,null,h.headers.etag,h.headers):i(c("Unexpected status code while getting a collection",void 0,h))}))}pagedGetCollection(e,t,i,n,r,s,l,h){if(!(e=this._resolveUrl(e)))return h(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+e));e+=((e,t,i,n)=>{const o=[t&&`order=${t}`,e&&`orderBy=${e}`,i&&`start=${i}`,n&&`limit=${n}`].filter(e=>e);return 0===o.length?"":`?${o.join("&")}`})(i,n,r,s);var d={};return t&&(d["If-None-Match"]=t),this._service.invoke("GET",e,d,void 0,{responseType:"text"},(function(e,t){if(e)return h(a("Error retrieving a collection",e,t));if(200===t.statusCode){var i,n=t.responseText||t.response;try{i=JSON.parse(n)}catch(i){return(e=new o(o.INVALID_DATA,"Invalid JSON returned by server",i)).response=t,h(e)}l?l.children=l.children.concat(i.children):l=i,h(void 0,l,t.headers.etag,t.headers)}else 304===t.statusCode?h(void 0,null,t.headers.etag,t.headers):h(c("Unexpected status code while getting a collection",void 0,t))}))}getComponent(e,t,i){var n=this.getComponentHref(e,e.version);return this.getAsset(n,void 0,t,i)}getRenditionOfComponent(e,t,i,n,o){var r=this.getComponentRenditionHref(e,e.version,i);return this.getAsset(r,{accept:t},n,o)}getSyncGroups(e,t){var i=h(this._server,"assets");return this.getCollection(i,e,t)}getSyncGroup(e,t,i){var n=h(this._server,"assets",e);return this.getCollection(n,t,i)}getCompositeManifest(e,t,i){var n=e.href;return n&&(n=this._resolveUrl(n)),n?(n=h(n,"manifest"),this.getAssetAsType(n,"text",t,i)):i(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+n))}createCompositeDirectory(e,t,i){var n=this,r=this._resolveUrl(e.href);if(!r)return i(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+r));function s(e,t,i){var s={"Content-Type":"application/vnd.adobe.directory+json","X-Update":"content"};t&&(s["If-Match"]="*"),n._service.invoke("PUT",r,s,void 0,void 0,(function(e,t){return e?i(a("Error Creating composite directory",e,t)):409===t.statusCode?((e=new o(o.ALREADY_EXISTS,e)).response=t,i(e)):void i(void 0,t)}))}s(0,t,(function(e,o){if(e)return i(e);var h=o.statusCode;if(200===h||201===h)i(void 0,o);else if(404===h){var d=l.parentDirectory(r);n._service.invoke("PUT",d,{},void 0,void 0,(function(e,n){if(e)return i(a("Error creating composite directory",e,n));var o=n.statusCode;200===o||201===o||409===o?s(0,t,(function(e,t){if(e)return i(e);var n=t.statusCode;200===n||201===n?i(void 0,t):i(a("Error creating composite directory",e,t))})):i(c("Unexpected response creating composite directory",e,n))}))}else i(c("Unexpected response creating composite directory",e,o))}))}deleteCompositeDirectory(e,t){var i=this,n=this._resolveUrl(e.href);if(!n)return t(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+n));n+="?recursive=true&invocation_mode=sync,async";var r=this._service.invoke("DELETE",n,{"If-Match":"*"},void 0,void 0,(function(e,n){if(e)return t(a("Error deleting composite directory",e,n));var o=n.statusCode;return 200===o||204===o||404===o?t(void 0,n):202===o?i._handle202Response(n,r,i.SYNC_ASYNC_DEFAULT_DELAY,void 0,t):void t(c("Unexpected response deleting composite directory",e,n))}))}discardComposite(e,t){t(new o(o.INVALID_STATE,"Composites can only be discarded on platform."))}archiveCompositeDirectory(e,t){var i=this,n=this._makeRelativeUrl(e.href);if(!n)return t(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+e.href));var r={"Content-Type":"application/vnd.adobe.directory+json",Link:"<"+n+">;rel=self"},s=this._resolveUrl("/archive/"+e.id)+"?invocation_mode=sync,async",l=this._service.invoke("PUT",s,r,void 0,void 0,(function(e,n){if(e)return t(a("Error archiving composite directory",e,n));var o=n.statusCode;return 200===o||204===o||404===o?t(void 0,n):202===o?i._handle202Response(n,l,i.SYNC_ASYNC_DEFAULT_DELAY,void 0,t):void t(c("Unexpected response archiving composite directory",e,n))}))}uploadComponent(e,t,i,n,r,s){if(!e._owner||!e._owner.compositeHref)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");return this.uploadAssetForComponentId(e.id,e.type,e._owner.compositeHref,t,i,n,r,s)}uploadAssetForComponentId(e,t,i,n,o,r,s,a){let c=this._constructComponentHref(i,e);return o&&(c+="?intermediates=false"),this.uploadAssetAtComponentHref(c,t,i,n,o,r,s,a)}copyAssetToComponentId(e,t,i,n,r,s,l,h){var d=this._makeRelativeUrl(l);if(!d)return h(new o(o.WRONG_ENDPOINT,"Cannot copy asset: "+l));var _=this,p=this._constructComponentHref(i,e);p+="?invocation_mode=sync,async",r&&(p+="&intermediates=false");var u={};function m(e,t,i){e?delete u["If-Match"]:u["If-Match"]="*";var n=_._service.invoke("PUT",p,u,void 0,{responseType:"text"},(function(e,o){if(e)return i(a("Error uploading component",e,o));var r=o.statusCode;200===r||201===r||204===r?i(void 0,o,t):202===r?_._handle202Response(o,n,_.SYNC_ASYNC_DEFAULT_DELAY,void 0,(function(e,n){i(e,n,t)})):i(c("Unexpected response copying a component asset",e,o),o,t)}));return n.token=s,n}t&&(u["Content-Type"]=t),u.Link="<"+d+">;rel=source";var g=function(e,t,i){var r;if(e){if(!(t=e.response))return h(e);var s=t.statusCode;i||404!==s&&409!==s&&412!==s?507===s?((e=new o(o.EXCEEDS_QUOTA,"Exceeds quota",e)).response=t,h(e)):h(e):m(!n,!0,g)}else{try{r=JSON.parse(t.responseText||t.response)}catch(i){return(e=new o(o.INVALID_DATA,"Invalid JSON returned by server",i)).response=t,h(e)}h(void 0,t,r)}};return m(n,!0,g)}updateManifest(e,t,i,n){const o=this.getBranchManifestHref(e);this.updateManifestAtHref(o,t,e.manifestEtag,i,n)}getHrefForComposite(e,t){if(!e.type)throw new o(o.INVALID_STATE,"Composite needs a type");if(!e.id)throw new o(o.INVALID_STATE,"Composite needs an id");return e.href?e.href:this._resolveUrl(h("assets",t,e.id))}getHrefForCompositeWithId(e,t){return this._resolveUrl(h("assets",t,e))}getCompositeManifestHref(e){var t=this._resolveUrl(e.href);if(!t)throw new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+t);return h(t,"manifest")}getBranchManifestHref(e){var t=this._resolveUrl(e.compositeHref);if(!t)throw new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+t);return h(t,"manifest")}getComponentHref(e,t){var i,n=e._owner;if(!n||!n.compositeHref)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");return n._core&&(i=n._core._getSourceHrefOfComponent(e)),i&&this._resolveUrl(i)||this._constructComponentHref(n.compositeHref,e.id,t)}getComponentRenditionHref(e,t,i){var n=e._owner;if(!n||!n.compositeHref)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");if(n._core&&n._core._getSourceHrefOfComponent(e))throw new o(o.INVALID_STATE,"Getting a rendition of a source href not implemented.");return this._constructComponentRenditionHref(n.compositeHref,e,t,i)}_constructComponentHref(e,t,i){var n=h(this._resolveUrl(e),t);return n&&void 0!==i&&(n+=";version="+i),n}_invokeOperation(e,t,i,n,r){const s=`${this._resolveUrl("/ops")}?invocation_mode=sync,async`,h={op:e,id:l.generateUuid(),target:i,source:t};n&&(h.value=n),l.log(`[invoke operation]: ${JSON.stringify(h,void 0,2)}`);const d=(e,t)=>{let i;if(e){if(!(t=e.response))return r(e);507===t.statusCode?((e=new o(o.EXCEEDS_QUOTA,"Exceeds quota",e)).response=t,r(e)):r(e)}else{try{i=JSON.parse(t.responseText||t.response)}catch(i){return(e=new o(o.INVALID_DATA,"Invalid JSON returned by server",i)).response=t,r(e)}if(i.error)return(e=new o(o.UNEXPECTED_RESPONSE,"Error in operation result: "+JSON.stringify(i.error,void 0,2))).response=t,r(e);r(void 0,t,i)}},_=this._service.invoke("POST",s,{"Content-Type":"application/vnd.adobe.asset-operation+json"},JSON.stringify(h),{responseType:"text"},(t,i)=>{if(t)return d(a("Error invoking operation "+e,t,i));const n=i.statusCode;200===n||201===n||204===n?d(void 0,i):202===n?this._handle202Response(i,_,this.SYNC_ASYNC_DEFAULT_DELAY,void 0,(function(e,t){d(e,t)})):d(c("Unexpected response for operation "+e,t,i),i)});return _}_constructComponentRenditionHref(e,t,i,n){var o=h(this._constructComponentHref(e,t.id),":rendition");return o+=";size="+(n||"full"),void 0!==i&&(o+=";version="+i),o}_getTransientPlatformSession(){return this._transientPlatformSession?Promise.resolve(this._transientPlatformSession):new Promise((e,t)=>{const i=new s(this._service,this._platformEndpoint,d);i.getRootDocument(n=>{if(n)return t(n);this._transientPlatformSession=i,e(this._transientPlatformSession)})})}_getCopyDelegate(e,t,i){super._getCopyDelegate(e,t,(n,s)=>n?d.test(e)?void this._doHeadRequest(t).then(n=>{const s=(n&&n.headers||{})["x-resource-urn"];if(!s)return i(new o(o.INVALID_DATA,`Request for composite did not return a URN: ${t}`));this._getTransientPlatformSession().then(t=>{t.getLinksFromUrn(s,(t,n)=>{if(t)return i(new o(o.INVALID_DATA,`Could not get links for URN: ${s}`));const a=l.getUrlFromLinks(n,r.PRIMARY);i(null,(t,i,n,o,r,s)=>this._transientPlatformSession.copyAssetToComponentId(t,i,a,n,o,r,e,s))})},i)}):i(new o(o.INVALID_PARAMS,`Href is not for a platform component: ${e}`)):i(null,s))}}},function(e,t){e.exports=class{constructor(){this._requests=[],this._bytesTransferred=0}_onProgress(e){this._bytesTransferred+=e,this._progress&&this._progress(e)}set token(e){this._token=e,this._requests.forEach(t=>t.token=e)}set progress(e){this._progress=e}get bytesSent(){return this._bytesTransferred}push(e,t){this._requests.push(e),e.token=this._token,t&&(e.progress=this._onProgress.bind(this))}}},function(e,t){e.exports=require("http-link-header")},function(e,t,i){var n=i(48),o=i(2),r=i(4),s=/^\/?content\/2\/[^/]+\/[^/]+/,a=/^\/?api\/v2\/[^/]+\/assets\/[^/]+/,c={"image/jpeg":"jpg","image/png":"png"},l=r.appendPathElements;e.exports=class extends n{getCompositeManifestHref(e){var t=this._resolveUrl(e.href);if(!t)throw new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+t);return l(t,"manifest")}getComponent(e,t,i){var n=this.getComponentHref(e,e.version);return this.getAsset(n,void 0,t,i)}getRenditionOfComponent(e,t,i,n,o,r){var s=this.getComponentRenditionHref(e,e.version,t,i,n);return this.getAsset(s,{accept:t},o,r)}getCompositeManifest(e,t,i){var n=e.href;return n&&(n=this._resolveUrl(n)),n?(n=l(n,"manifest"),this.getAssetAsType(n,"text",t,i)):i(new o(o.WRONG_ENDPOINT,"Wrong endpoint: "+n))}getComponentHref(e,t){var i,n=e._owner;if(!n||!n.compositeHref)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");return n._core&&(i=n._core._getSourceHrefOfComponent(e)),i||this._constructComponentHref(n.compositeHref,e,t)}getComponentRenditionHref(e,t,i,n,r){var s=e._owner;if(!s||!s.compositeHref)throw new o(o.INVALID_STATE,"Component must be part of a branch of a bound composite.");if(s._core&&s._core._getSourceHrefOfComponent(e))throw new o(o.INVALID_STATE,"Getting a rendition of a source href not implemented.");return this._constructComponentRenditionHref(s.compositeHref,e,t,i,n,r)}_constructComponentHref(e,t,i){var n=t.absolutePath.slice(1),o=l(this._resolveUrl(e),n);return o&&void 0!==i&&(this._hrefUsesContentApis(e)?o+="/version/"+i:o+="?version="+i),o}_constructComponentRenditionHref(e,t,i,n,l,h){var d,_,p=t.absolutePath.slice(1),u=r.parseURI(e).path;if("/content/2/"===u.slice(0,"/content/2/".length)){var m=c[n];if(!m)throw new o(o.INVALID_PARAMS,"Unsupported rendition media type: "+n);if(!((d=s.exec(u))&&d.length>0))throw new o(o.INVALID_PARAMS,"Failed to parse composite href: "+e);_=this._resolveUrl(r.appendPathElements(d[0],"rendition",p,"version",i,"format",m,"dimension",l,"size",String(h)))}else{if(!((d=a.exec(u))&&d.length>0))throw new o(o.INVALID_PARAMS,"Failed to parse composite href: "+e);_=this._resolveUrl(r.appendPathElements(d[0],"rendition",l,String(h),p)+"?version="+i)}return _}_hrefUsesContentApis(e){return"/content/2/"===r.parseURI(e).path.slice(0,"/content/2/".length)}}},function(e,t,i){const n=i(119),o=i(12),r=i(122),s=i(54),a=i(61),c=i(62),l=i(139),h=i(1),d=i(140),_=i(165),p=i(168),u=i(169),m=i(23),g=i(57),f=i(38),E=i(10),y=new RegExp("cloud-asset://(.+)/([A-Za-z0-9-]+);node=([A-Za-z0-9-]+)");e.exports=class{constructor(e,t){if(this._config=new o,this._services=new n(this._config),this._services.hasFileSystem()||void 0!==t.SHARED_LOCAL_STORAGE||(t.SHARED_LOCAL_STORAGE=!1),this._services.hasFileSystem()&&!t.ROOT_DIR&&!1===t.SHARED_LOCAL_STORAGE)throw new h(h.INVALID_PARAMETER,"Missing ROOT_DIR option");if(this._services.hasFileSystem()&&t.ROOT_DIR&&!1!==t.SHARED_LOCAL_STORAGE)throw new h(h.INVALID_PARAMETER,"ROOT_DIR option doesn't apply when using shared local storage");if(!this._services.hasFileSystem()&&t.ROOT_DIR)throw new h(h.REQUIRES_FILESYSTEM,"ROOT_DIR option only applies when you have a filesystem");if(!1===t.SHARED_LOCAL_STORAGE&&!t.STORAGE_API_KEY)throw new h(h.INVALID_PARAMETER,"Missing STORAGE_API_KEY option");if(!1===t.SHARED_LOCAL_STORAGE&&!t.DEVICE_ID)throw new h(h.INVALID_PARAMETER,"Missing DEVICE_ID option");if(!1!==t.SHARED_LOCAL_STORAGE&&!this._services.hasCEPVulcan()&&!e.vulcanCall)throw new h(h.INVALID_PARAMETER,"Shared local storage requires either the CEP VulcanInterface/VulcanMessage as globals, or for you to pass in the vulcanCall dependency");if(!t.APP_DESCRIPTION)throw new h(h.INVALID_PARAMETER,'Missing APP_DESCRIPTION option - should be a string of the form <name>-<version>, e.g. "PHXS-16.0".');if(t.ROOT_DIR)for(;-1!==["/","\\"].indexOf(t.ROOT_DIR.substr(-1));)t.ROOT_DIR=t.ROOT_DIR.slice(0,-1);this._services.vulcanCall=e.vulcanCall,this._services._log=e.log,this._services._getDisplayName=e.getDisplayName,this._services._getNodeTunnelOptions=e.getNodeTunnelOptions,this._services._refreshTeams=e.refreshTeams,e.renditionGenerator&&this._services.setRenditionGenerator(e.renditionGenerator),this._analytics=new r(e.analytics,this._config),this._storageInterface=new _(this,{onConnected:e.onClientConnected}),this._externalUtils=new p(this),this._externalAnalyticsUtils=new u(this),this._localisation=new d(this,t.LOCALE),delete t.LOCALE,Object.keys(t).forEach(e=>this._config.setParameter(e,t[e])),this._collectionManager=new l(this),this._loadingState={},this._services.log("Configure: "+(this._config.SHARED_LOCAL_STORAGE?"<shared local storage>":this._config.ROOT_DIR))}_addLoadCallback(e,t,i){const n=e+"/"+t,o=void 0!==this._loadingState[n];return this._loadingState[n]=this._loadingState[n]||[],this._loadingState[n].push(i),o}_notifyLoadCallbacks(e,t){let i;i=e===this._config.PUBLIC_USER_ID?this._collectionManager.getPublicLibraryCollection(t):f.isTeam(t)?this._collectionManager.getTeamLibraryCollection(f.getUrnFromCloudId(t)):this._collectionManager.getLibraryCollection(e,t);const n=e+"/"+t,o=this._loadingState[n];o&&(delete this._loadingState[n],o.forEach(e=>e(null,i)))}_getPrivateCollection(e){return this._collectionManager.getLoadedCollections().find(t=>t.isPrivate&&t.userId===e)}setOption(e,t){if(-1!==["ROOT_DIR","SHARED_LOCAL_STORAGE","ELEMENT_TYPE_FILTERS","STORAGE_API_KEY"].indexOf(e))throw new h(h.INVALID_PARAMETER,"Cannot reconfigure "+e);this._config.setParameter(e,t),this._storageInterface.updateConfiguration()}getOption(e){return this._config[e]}setLocalSetting(e,t){if("string"!=typeof e)throw new h(h.INVALID_PARAMETER,"Key must be a string");try{JSON.stringify(t)}catch(e){throw new h(h.INVALID_PARAMETER,"Value must be serializable to JSON")}this._config.setLocalSetting(e,t),this._storageInterface.updateConfiguration()}getLocalSetting(e){return this._config.LOCAL_SETTINGS[e]}addConfigurationChangeListener(e){this._config.addChangeListener(e)}removeConfigurationChangeListener(e){this._config.removeChangeListener(e)}getLoadedCollections(){return this._collectionManager.getLoadedCollections().slice(0)}getLoadedCollectionById(e,t){return this._collectionManager.getLibraryCollection(e,t)}getLoadedPublicCollectionById(e){return this._collectionManager.getPublicLibraryCollection(e)}getLoadedTeamCollectionById(e){return this._collectionManager.getTeamLibraryCollection(e)}addLoadedCollectionsListener(e){this._collectionManager.addLoadedCollectionsListener(e)}removeLoadedCollectionsListener(e){this._collectionManager.removeLoadedCollectionsListener(e)}getRootDir(){if(!this._services.hasFileSystem())throw new h(h.REQUIRES_FILESYSTEM,"ROOT_DIR option only applies when you have a filesystem");return this._config.ROOT_DIR}refreshTeams(e){if(this._config.SHARED_LOCAL_STORAGE)return this._storageInterface.refreshTeams(e);this._services._refreshTeams(!1,e)}getLocale(){return this._localisation.getLocale()}unloadLibraryCollection(e){if(this._config.SHARED_LOCAL_STORAGE)throw new h(h.NOT_SUPPORTED,"unloadLibraryCollection() not supported with shared local storage");e.stopPolling(),e._removeAllListeners(),e._abortPushOrPull(!0),this._collectionManager.removeLibraryCollection(e)}loadLibraryCollection(e={},t){if("function"==typeof e)return void(t=e)(new h(h.INVALID_PARAMETER,"options argument not specified"));if(this._config.SHARED_LOCAL_STORAGE)return void t(new h(h.NOT_SUPPORTED,"loadLibraryCollection() not supported with shared local storage"));e.CLOUD_ID=e.CLOUD_ID||this._config.DEFAULT_CLOUD_ID;const i=["STORAGE_HOSTNAME","CC_LIBRARY_SERVICE_HOSTNAME","CC_IMAGE_HOSTNAME","CC_IMAGE_X_HOSTNAME","TYPEKIT_HOSTNAME"];this._services.hasFileSystem()&&i.unshift("USER_ID");for(let n=0;n<i.length;n++){const o=i[n];if(!e[o])return void t(new h(h.INVALID_PARAMETER,`Missing ${o} option`))}let n=this._collectionManager.getLibraryCollection(e.USER_ID,e.CLOUD_ID);const o=this._addLoadCallback(e.USER_ID,e.CLOUD_ID,t);if(n&&!o)return void this._notifyLoadCallbacks(e.USER_ID,e.CLOUD_ID);if(o)return;n=new s(this,e);const r=()=>{this._collectionManager.addLibraryCollection(n),this._config.AUTO_START_POLLING&&n.startPolling(),this._notifyLoadCallbacks(e.USER_ID,e.CLOUD_ID)};if(this._services.hasFileSystem())this._services.fileUtils.doesRootDirExist(n,(e,t)=>{n._load(()=>{t||n._setInitialSyncState(!0),n.sync(()=>n._setInitialSyncState(!1)),r()})});else if("all"===e.WAIT_FOR)n._setInitialSyncState(!0),n.sync(()=>{n._setInitialSyncState(!1),r()});else if(E.validateLibraryId(e.WAIT_FOR,!1)){n._setInitialSyncState(!0,[e.WAIT_FOR]),n.sync(()=>n._setInitialSyncState(!1));const t=()=>{"syncing"===n.syncState&&"pending"===n._libraryIdMap[e.WAIT_FOR]||(n.removeChangeListener(t),n.removeSyncListener(t),r())};n.addChangeListener(t),n.addSyncListener(t)}else n._setInitialSyncState(!0),n.sync(()=>n._setInitialSyncState(!1)),r()}loadPublicLibraryCollection(e={},t){if("function"==typeof e)return void(t=e)(new h(h.INVALID_PARAMETER,"options argument not specified"));if(this._config.SHARED_LOCAL_STORAGE)return void t(new h(h.NOT_SUPPORTED,"loadPublicLibraryCollection() not supported with shared local storage"));if(e.CLOUD_ID=e.CLOUD_ID||this._config.DEFAULT_CLOUD_ID,!e.STORAGE_HOSTNAME)return void t(new h(h.INVALID_PARAMETER,"Missing STORAGE_HOSTNAME option"));let i=this._collectionManager.getPublicLibraryCollection(e.CLOUD_ID);const n=this._addLoadCallback(this._config.PUBLIC_USER_ID,e.CLOUD_ID,t);if(i&&!n)return void this._notifyLoadCallbacks(this._config.PUBLIC_USER_ID,e.CLOUD_ID);if(n)return;const o=this._getPrivateCollection(e.USER_ID);i=new c(this,e,o);const r=()=>{this._collectionManager.addLibraryCollection(i),this._config.AUTO_START_POLLING&&i.startPolling(),this._notifyLoadCallbacks(this._config.PUBLIC_USER_ID,e.CLOUD_ID)};this._services.hasFileSystem()?i._load(()=>{i.sync(),r()}):r()}loadTeamLibraryCollection(e={},t){if("function"==typeof e)return void(t=e)(new h(h.INVALID_PARAMETER,"options argument not specified"));if(this._config.SHARED_LOCAL_STORAGE)return void t(new h(h.NOT_SUPPORTED,"loadTeamLibraryCollection() not supported with shared local storage"));if(!e.STORAGE_HOSTNAME)return void t(new h(h.INVALID_PARAMETER,"Missing STORAGE_HOSTNAME option"));if(!e.TEAM)return void t(new h(h.INVALID_PARAMETER,"Missing TEAM option"));let i=this._collectionManager.getTeamLibraryCollection(e.TEAM.id);const n=this._addLoadCallback(e.USER_ID,e.CLOUD_ID,t);if(i&&!n)return void this._notifyLoadCallbacks(e.USER_ID,e.CLOUD_ID);if(n)return;const o=this._getPrivateCollection(e.USER_ID);i=new a(this,e,o);const r=()=>{this._collectionManager.addLibraryCollection(i),this._notifyLoadCallbacks(e.USER_ID,e.CLOUD_ID)};this._services.hasFileSystem()?i._load(()=>{i.sync(),r()}):r()}isConnected(){if(!this._config.SHARED_LOCAL_STORAGE)throw new h(h.NOT_SUPPORTED,"isConnected() is only applicable if using shared local storage");return this._storageInterface&&this._storageInterface.isConnected()}reconnect(){if(!this._config.SHARED_LOCAL_STORAGE)throw new h(h.NOT_SUPPORTED,"reconnect() is only applicable if using shared local storage");this._storageInterface&&this._storageInterface.reconnect()}disconnect(){if(!this._config.SHARED_LOCAL_STORAGE)throw new h(h.NOT_SUPPORTED,"disconnect() is only applicable if using shared local storage");this._storageInterface&&this._storageInterface.isConnected()&&this._storageInterface.shutdown()}getServiceInfo(){if(!this._config.SHARED_LOCAL_STORAGE)throw new h(h.NOT_SUPPORTED,"getServiceInfo() is only applicable if using shared local storage");return this._storageInterface&&this._storageInterface.getServiceInfo()}isSyncingEnabled(){if(this._config.SHARED_LOCAL_STORAGE){const e=this.getServiceInfo();return Boolean(e&&e.syncingEnabled)}return this._config.SYNCING_ENABLED}enableSyncing(){this._config.SHARED_LOCAL_STORAGE?this._storageInterface.setSyncEnabled(!0):(this._config.SYNCING_ENABLED=!0,this.getLoadedCollections().forEach(e=>e.sync()))}disableSyncing(){this._config.SHARED_LOCAL_STORAGE?this._storageInterface.setSyncEnabled(!1):(this._config.SYNCING_ENABLED=!1,this.getLoadedCollections().forEach(e=>e._abortPushOrPull()))}getLibraryById(e){return this.getLoadedCollections().reduce((t,i)=>t||i.getLibraryById(e),null)}resolveElementReference(e=""){const t=e.match(y);if(!t)return;const[,,i,n]=t;return this.getLoadedCollections().map(e=>{const t=e.getLibraryById(i);return t&&t.getElementById(n)}).find(e=>e)}getAccessToken(e,t,i,n,o){this._config.SHARED_LOCAL_STORAGE?0!==this._collectionManager.getLoadedCollections().length?this._storageInterface.getAccessToken(e,t,i,n,o):o(new h(h.LOGGED_OUT,"User must be logged in to request an access token")):o(new h(h.NOT_SUPPORTED,"getAccessToken() is only supported with shared local storage"))}openInCCD(e,t){this._config.SHARED_LOCAL_STORAGE?this._storageInterface.openInCCD(e,t):t(new h(h.NOT_SUPPORTED,"launchCCD() is only supported with shared local storage"))}get utils(){return this._externalUtils}get analyticsUtils(){return this._externalAnalyticsUtils}static getSNISettings(){const e=new o;return{TLS_DISCOVERY_PORT_RANGE:e.TLS_DISCOVERY_PORT_RANGE,TLS_DELAY_ON_DECLINE:2*e.TLS_DELAY_ON_DECLINE,TLS_DELAY_ON_READY:2*e.TLS_DELAY_ON_READY}}static get errors(){return h}static mimeTypeToExtensions(e){return m.getExtensions(e)}static extensionToMimeTypes(e){return m.getMimeTypes(e)}static canGenerateRenditionFromMimeType(e){return g.canComputeRenditionFromMimeType(e)}}},function(e,t,i){const n=i(25),o=i(120);e.exports=class{constructor(e){this._config=e,this._fileUtils=new o(this,e),this.uuid=i(7),this.fs=i(19),this.crypto=i(35),this.path=i(9),this.imageSize=i(121),this.yazl=i(52),this.yauzl=i(53),this._initDCX()}_initDCX(){this.dcx=new n(this.fs,{preserveFileExtensions:!0,logCallback:e=>this._log&&this._log("DCX: "+e)})}get fileUtils(){return this._fileUtils}log(e){this._log&&this._log("CC Libraries: "+e)}getDisplayName(e){return this._getDisplayName?this._getDisplayName(e):e.name}hasFileSystem(){return void 0!==this.fs}setFileSystem(e){this.fs=e,this._initDCX()}hasRenditionGenerator(){return void 0!==this.renditionGenerator}setRenditionGenerator(e){this.renditionGenerator=e}getVulcanInterface(){if("undefined"!==typeof VulcanInterface)return VulcanInterface}getVulcanMessage(){if("undefined"!==typeof VulcanMessage)return VulcanMessage}hasCEPVulcan(){return void 0!==this.getVulcanInterface()&&void 0!==this.getVulcanMessage()}getNodeTunnelOptions(e){return this._getNodeTunnelOptions?this._getNodeTunnelOptions(e):{}}getPathSeparator(){return"/"}getFileNameFromPath(e){return!e.includes("/")&&e.includes("\\")&&(e=e.replace(/\\/g,"/")),e.split("/").pop()}}},function(e,t,i){var n=i(6),o=i(1);const r=/(.*)\.TEMP_[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;e.exports=class{constructor(e,t){this._config=t,this._services=e}get _fs(){return this._services.fs}get _pathSep(){return this._services.getPathSeparator()}_uuid(){return this._services.uuid()}_getTempPath(e){return e+".TEMP_"+this._uuid()}_stripTempSuffix(e){var t=e.match(r);return t&&t[1]?t[1]:e}_fsApply(e,...t){const i=t.find(e=>"function"==typeof e),n=t.slice(0,t.indexOf(i)),o=t.indexOf(i)===t.length-1?0:t[t.length-1];this._fs[e].apply(this._fs,n.concat((t,...r)=>{t&&"EPERM"===t.code&&o<this._config.FS_MAX_RETRIES?setTimeout(()=>{this._fsApply(e,...n,i,o+1)},this._config.FS_RETRY_INTERVAL):i(t,...r)}))}ensurePathExists(e,t){const i=(e,t,n)=>{var o=t.slice(0,e).join(this._pathSep),r=()=>{e<t.length?i(e+1,t,n):n(null)};this._fs.exists(o,e=>e?r():this._fs.mkdir(o,r))},n=e.replace(/\\/g,this._pathSep).split(this._pathSep);i(2,n,t)}copyFile(e,t,i){try{var n=this._getTempPath(t),o=this._fs.createWriteStream(n),r=this._fs.createReadStream(e),s=!1;r.on("end",()=>{s||this._fsApply("rename",n,t,e=>{e?setTimeout(()=>{this._fsApply("rename",n,t,i)},this._config.FS_RETRY_INTERVAL):i(null)})}),r.on("error",e=>{s=!0,i(e)}),r.pipe(o)}catch(e){i(e)}}getAvailablePath(e,t,i,n=0){let o=t.lastIndexOf(".");o=-1===o?t.length:o;const r=t.substring(0,o),s=t.substring(o+1),a=`${n?` (${n})`:""}${s?`.${s}`:""}`,c=255-this._getTempPath("").length-a.length;let l=r.substr(0,c);l[l.length-1].charCodeAt(0)>=55296&&l[l.length-1].charCodeAt(0)<=56319&&(l=l.substr(0,l.length-1));const h=`${e}${l}${a}`;this.statFile(h,o=>{o&&o.underlyingError&&"ENOENT"===o.underlyingError.code?i(null,h):o?i(o):this.getAvailablePath(e,t,i,n+1)})}rename(e,t,i){this._fsApply("rename",e,t,i)}deleteFile(e,t){this._fsApply("unlink",e,t)}normaliseTempFileName(e){return this._stripTempSuffix(e)}getFileExtension(e){var t=e&&e.replace(/^.*[\\/]/,""),i=t?t.lastIndexOf("."):-1;if(-1!==i)return t.substr(i+1).toLowerCase()}recursiveDeleteDirectory(e,t){const i=e=>{e&&"ENOENT"===e.code&&(e=null),t&&t(e)};this._fsApply("readdir",e,(t,n)=>{if(t)return void i(t);if(!n||0===n.length)return void this._fs.rmdir(e,i);var o=null,r=0;const s=t=>{t&&"ENOENT"===t.code&&(t=null),o=o||t,++r===n.length&&(o?i(o):this._fs.rmdir(e,i))};n.forEach(t=>{var i=e+this._pathSep+t;this._fsApply("readdir",i,e=>{e?this._fs.unlink(i,s):this.recursiveDeleteDirectory(i,s)})})})}getUserDir(e){const t=this._services.getPathSeparator(),i=e.replace(/@/g,"_");return this._config.ROOT_DIR+t+i}moveLibrary(e,t,i){if(t!==e.id){var n=e._collection._getCompositeDir(t),o=e._getCompositeDir(),r=e._collection._getRenditionCacheDir(t),s=e._getRenditionCacheDir();this.rename(n,o,t=>{t?i(t):(e._dcxComposite.path=o,this.rename(r,s,e=>i(e&&"ENOENT"===e.code?null:e)))})}else i(null)}readLibraryDirectory(e,t){var i=e._getTempDir();this.recursiveDeleteDirectory(i,()=>{var i=e._getCompositeDir();this._fsApply("readdir",i,t)})}doesRootDirExist(e,t){const i=e._getCompositeDir();this._fs.exists(i,e=>t(null,e))}deleteLibraryFromDisk(e,t,i=(()=>{})){if(this._fs){var n=e._getCompositeDir(t),o=e._getRenditionCacheDir(t);this.recursiveDeleteDirectory(n,()=>this.recursiveDeleteDirectory(o,i))}else i(null)}writeJSONData(e,t,i){return new Promise((n,o)=>{this.ensurePathExists(e,r=>{if(r)return void o(r);const s=e+this._services.getPathSeparator()+t,a=s+".TEMP_"+this._uuid();this._fs.writeFile(a,JSON.stringify(i,void 0,2),"utf8",e=>{e?o(e):this._fsApply("rename",a,s,e=>e?o(e):n(s))})})})}readJSONData(e){return new Promise((t,i)=>{this._fs.readFile(e,"utf8",(e,n)=>{if(e)"ENOENT"===e.code?t():i(e);else try{const e=n&&JSON.parse(n);t("object"==typeof e?e:void 0)}catch(e){i(e)}})})}statFile(e,t){this._fs.stat(e,(e,i)=>{e?t(n.getFileSystemError(e,"unable to stat file")):t(null,i)})}checkFileSize(e,t){this.statFile(e,(e,i)=>{e?t(e):i&&i.size>this._config.MAX_COMPONENT_SIZE?t(new o(o.FILE_TOO_LARGE,"Exceeds maximum file size")):t(null)})}computeSHA(e){return new Promise((t,i)=>{const n=this._services.crypto.createHash("sha256");n.setEncoding("hex");const o=this._fs.createReadStream(e);o.on("error",e=>i(e)),n.on("finish",()=>t(n.read())),o.pipe(n)})}}},function(e,t){e.exports=require("image-size")},function(e,t){function i(e){if(!e)return{};var t={libraryID:e.id,libraryElementCount:e._elements.length,libraryGroupCount:e._groups?e._groups.length:0};return e.collection.isPublic?t.libraryShared="incoming-public":e.collaboration&&(t.libraryShared=e.collaboration,e.isWritable||(t.libraryShared+="-readonly")),t}function n(e){if(!e)return{};var t=i(e._library);t.elementID=e.id,t.elementType=function(e){if(e.type){var t=e.type.match(/application\/vnd\.adobe\.element\.(.*)\+dcx/);return t&&2===t.length?t[1]:e.type}return null}(e),t.elementGroupIDs=e.getGroups(/.*/).map((function(e){return e.id}));var n=e.getPrimaryRepresentation();if(n){var o=function(e){var t=null;return e.getValues().forEach(e=>{"trackingdata"===e.key&&(t||(t={}),t[e.namespace]=e.value)}),t}(n);o&&(t.trackingData=JSON.stringify(o)),t.elementPrimaryType=n.type}return t}function o(e,t){if(!e)return{};var n=t?{}:i(e._library);return n.groupID=e.id,n.groupClassifierName=e.classifierName,n}function r(e){if(!e)return{};var t=n(e.element);return t.appCode=e.appCode,t.elementAction=e.id,t}e.exports=class{constructor(e,t){this._analytics=e,this._config=t}_isReportingEnabled(){return null!==this._analytics&&void 0!==this._analytics}reportError(e){this._isReportingEnabled()&&e&&this._analytics.reportError(e.code+(e.underlyingError?":"+e.underlyingError.code:""))}reportCreateLibrary(e){this._isReportingEnabled()&&this._analytics.reportEvent("createLibrary",{libraryID:e.id})}reportDeleteLibrary(e){this._isReportingEnabled()&&this._analytics.reportEvent("deleteLibrary",i(e))}reportExportLibrary(e,t){if(this._isReportingEnabled()){var n=t?i(t):{};e&&(n.error=e.code),this._analytics.reportEvent("exportLibrary",n)}}reportImportLibrary(e,t){if(this._isReportingEnabled()){var n=t?i(t):{};e&&(n.error=e.code),this._analytics.reportEvent("importLibrary",n)}}reportCreateElement(e){this._isReportingEnabled()&&(this._lastUpdatedElement=e,this._lastUpdatedElementOn=Date.now(),this._analytics.reportEvent("createElement",n(e)))}reportUpdateElement(e,t){if(this._isReportingEnabled()){if(e===this._lastUpdatedElement&&Date.now()-this._lastUpdatedElementOn<this._config.ANALYTICS_ELEMENT_UPDATE_THRESHOLD)return;this._lastUpdatedElement=e,this._lastUpdatedElementOn=Date.now();var i=n(e);i.updateType=t?"info":"representation",this._analytics.reportEvent("updateElement",i)}}_reportUpdateElementMetadata(e,t,i){if(this._isReportingEnabled()){var o=n(e);o.updateType=t,i&&Object.assign(o,i),this._analytics.reportEvent("updateElementMetadata",o)}}reportSetOrderInGroup(e,t,i){var n=o(t,!0);n.elementOrderInGroup=e.getOrderInGroup(t),n.removeExistingGroups=i,this._reportUpdateElementMetadata(e,"order",n)}reportSetDescription(e){this._reportUpdateElementMetadata(e,"description")}reportUseElement(e,t,i){if(this._isReportingEnabled()){var o=function(e){if(!e)return{};var t=n(e._element);return t.representationType=e.type,t.representationId=e.id,t}(e);o.opType=t,o.details=i,this._analytics.reportEvent("useElement",o)}}reportCheckoutElement(e,t,i){if(this._isReportingEnabled()){var o=n(e);o.opType=t,o.details=i,this._analytics.reportEvent("checkoutElement",o)}}reportDeleteElement(e,t){if(this._isReportingEnabled()){var i=n(e);i.isPermanent=!!t,this._analytics.reportEvent("deleteElement",i)}}reportRestoreElement(e){this._isReportingEnabled()&&this._analytics.reportEvent("restoreElement",n(e))}reportCopyElement(e,t){if(this._isReportingEnabled()){this._lastUpdatedElement=e,this._lastUpdatedElementOn=Date.now();var i=n(e);i.oldLibraryID=t._library.id,i.oldElementID=t.id,this._analytics.reportEvent("copyElement",i)}}reportMoveElement(e,t){if(this._isReportingEnabled()){this._lastUpdatedElement=e,this._lastUpdatedElementOn=Date.now();var i=n(e);i.oldLibraryID=t._library.id,i.oldElementID=t.id,this._analytics.reportEvent("moveElement",i)}}reportCreateGroup(e){this._isReportingEnabled()&&this._analytics.reportEvent("createGroup",o(e))}reportUpdateGroup(e){if(this._isReportingEnabled()){var t=o(e);t.updateType="name",this._analytics.reportEvent("updateGroup",t)}}reportUpdateGroupMetadata(e,t){if(this._isReportingEnabled()){var i=o(e);i.updateType="order",i.groupOrder=t,this._analytics.reportEvent("updateGroupMetadata",i)}}reportDeleteGroup(e,t,i){if(this._isReportingEnabled()){var n=o(e);n.includeContents=t,t&&(n.numberElementsInGroup=i),this._analytics.reportEvent("deleteGroup",n)}}reportCopyGroup(e,t,i,n){if(this._isReportingEnabled()){var r=o(e);r.oldLibraryID=t._library.id,r.oldGroupID=t.id,r.includeContents=i,i&&(r.numberElementsInGroup=n),this._analytics.reportEvent("copyGroup",r)}}reportMoveGroup(e,t,i,n){if(this._isReportingEnabled()){var r=o(e);r.oldLibraryID=t._library.id,r.oldGroupID=t.id,r.includeContents=i,i&&(r.numberElementsInGroup=n),this._analytics.reportEvent("moveGroup",r)}}reportCollisionElement(e){this._isReportingEnabled()&&this._analytics.reportEvent("collisionLibrary",n(e))}reportCreateLink(e,t){if(this._isReportingEnabled()){var i=n(e);i.opType=t,this._analytics.reportEvent("createLink",i)}}reportShareElementLink(e){this._isReportingEnabled()&&this._analytics.reportEvent("shareElementLink",n(e))}reportShareLibraryLink(e){this._isReportingEnabled()&&this._analytics.reportEvent("shareLibraryLink",i(e))}reportElementActionInvoked(e){this._isReportingEnabled()&&this._analytics.reportEvent("elementActionInvoked",r(e))}reportElementActionSuccessful(e,t){if(this._isReportingEnabled()){var i=r(e);i.appVersion=t&&t.version,i.appLaunchStatus=t?t.isAlreadyRunning?"Running":"Launched":"Unknown",this._analytics.reportEvent("elementActionSuccessful",i)}}reportElementActionFailed(e,t){if(this._isReportingEnabled()){var i=r(e);i.error=t?t.code+":"+t.message:"",this._analytics.reportEvent("elementActionFailed",i)}}reportUnexpectedState(e,t){if(this._isReportingEnabled()){var n=i(e);n.details=t,this._analytics.reportEvent("unexpectedState",n)}}reportRemoveMissingComponents(e,t,i){if(this._isReportingEnabled()){var n={libraryID:e,numMissing:t.length,numFixed:i,componentErrors:[]};t.forEach(e=>{var t=e.error,i=t&&t.code,o=t&&t.response&&t.response.statusCode,r=(i||"UNKNOWN_ERROR")+(o?": "+o:"");n.componentErrors.push(r)}),this._analytics.reportEvent("removeMissingComponents",n)}}}},function(e,t,i){const n=i(1),o=i(10),r=i(3);e.exports=class{constructor(e,t){this._library=e,this._listenerManager=new r(["change"],e=>this._services.log(e)),this._setDCXNode(t)}get _config(){return this._library._config}get _services(){return this._library._services}get _analytics(){return this._library._analytics}_setDCXNode(e){this._dcxNode=e,this._deletedLocally=!1}_getEventData(e){return this._dcxNode.getValue(this._config[e+"_DATA_KEY"])||{}}_getEventContext(e){const t=JSON.parse(JSON.stringify(this._getEventData(e)));return delete t.deviceId,delete t.userId,t}_isLocalEvent(e){const t=this._getEventData(e).deviceId;if(t&&this._config.DEVICE_ID)return t===this._config.DEVICE_ID}_markDeletedLocally(e){this._deletedLocally=e,e&&this._listenerManager.removeAll()}_commit(){this._updateModifiedTime(),this._library._commit(),this._listenerManager.notify("change"),this._analytics.reportUpdateGroup(this)}_commitMetadata(){this._library._commit(),this._listenerManager.notify("change")}_updateCreatedTime(){const e=Date.now();this._dcxNode.setValue(this._config.CREATED_KEY,e),this._dcxNode.setValue(this._config.MODIFIED_KEY,e),this._setEventData("CREATED"),this._setEventData("MODIFIED")}_updateModifiedTime(){const e=Date.now();this._dcxNode.setValue(this._config.MODIFIED_KEY,e),this._setEventData("MODIFIED")}_toJSON(){return{id:this.id,classifierName:this.classifierName,name:this.name,order:this.order}}toString(){return JSON.stringify(this._toJSON())}jasmineToString(){return this.toString()}_setEventData(e){if(!this._config.DEVICE_ID)return void this._clearEventData(e);const t={userId:this.library.collection.userId,deviceId:this._config.DEVICE_ID};this._config.DEVICE_DESCRIPTION&&(t.device=this._config.DEVICE_DESCRIPTION),this._config.APP_DESCRIPTION&&(t.app=this._config.APP_DESCRIPTION),this._dcxNode.setValue(this._config[e+"_DATA_KEY"],t)}_clearEventData(e){this._dcxNode.getValue(this._config[e+"_DATA_KEY"])&&this._dcxNode.removeValue(this._config[e+"_DATA_KEY"])}get id(){return this._dcxNode.id}get library(){return this._library}get name(){return this._dcxNode.name}set name(e){if(o.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this._library.id);this._dcxNode.name=e,this._commit()}get classifierName(){return this._dcxNode.getValue(this._config.CLASSIFIER_KEY)}get order(){return this._dcxNode.getValue(this._config.ORDER_KEY)}set order(e){if(!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if("string"!=typeof e)throw new n(n.INVALID_PARAMETER,"order must be a string",this._library.id);this._dcxNode.setValue(this._config.ORDER_KEY,e),this._commitMetadata(),this._analytics.reportUpdateGroupMetadata(this,e)}get isWritable(){return this._library.isWritable}get created(){return this._dcxNode.getValue(this._config.CREATED_KEY)}get createdBy(){return this._getEventData("CREATED").userId}get createdContext(){return this._getEventContext("CREATED")}get wasCreatedLocally(){return this._isLocalEvent("CREATED")}get modified(){return this._dcxNode.getValue(this._config.MODIFIED_KEY)}get modifiedBy(){return this._getEventData("MODIFIED").userId}get modifiedContext(){return this._getEventContext("MODIFIED")}get wasModifiedLocally(){return this._isLocalEvent("MODIFIED")}get isDeletedLocally(){return this._deletedLocally}addChangeListener(e){o.checkDeletedState(this),this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}}},function(e,t,i){const n=i(125),o=i(1),r=i(126),s=i(17),a=i(10),c=i(57),l=i(6),h=i(3),d=i(8).promisify;e.exports=class{constructor(e,t){this._library=e,this._renditionFetchLock=new s,this._listenerManager=new h(["change"],e=>this._services.log(e)),this._transactionCount=0,this._setDCXNode(t,!0)}get _services(){return this._library._services}get _config(){return this._library._config}get _analytics(){return this._library._analytics}get _storageInterface(){return this._library._storageInterface}_setDCXNode(e,t){const i={};this._representations&&this._representations.forEach(e=>{i[e.id]=e}),this._dcxNode=e,this._representations=[],this._deletedLocally=!1,this._library._dcxBranch.getChildrenOf(e).forEach(e=>{let t=i[e.id];t?(t._setDCXNode(e),delete i[e.id]):t=new n(this,e),this._representations.push(t)}),this._library._dcxBranch.getComponentsOf(e).forEach(e=>{let t=i[e.id];t?(t._setDCXComponent(e),delete i[e.id]):t=new n(this,void 0,e),this._representations.push(t)}),a.sortRepresentations(this._representations),t||this.library._renditionCache.clearCache(this),this._displayName=void 0}_markDeletedLocally(e){this._deletedLocally=e,this._representations.forEach(t=>{t._markDeletedLocally(e)}),e&&this._listenerManager.removeAll()}_removeAllListeners(){this._listenerManager.removeAll()}_toJSON(){const e={id:this.id,name:this.name,type:this.type,description:this.description,representations:this._representations.map(e=>e._toJSON())};return e.representations.sort((e,t)=>e.type>t.type?1:e.type<t.type?-1:0),e}_addRepresentation(e,t){void 0!==t?this._representations.splice(t,0,e):this._representations.push(e)}_removeRepresentation(e){const t=this._representations.indexOf(e);-1!==t&&this._representations.splice(t,1)}_validateRelationship(e){if(-1===this._config.VALID_RELATIONS.indexOf(e))throw new o(o.INVALID_PARAMETER,"Unsupported relationship",this._library.id);this._representations.length>0&&"primary"===e&&this._representations.forEach(t=>{if(t!==e&&"primary"===t.relationship)throw new o(o.INVALID_PARAMETER,"Cannot have more than one primary representation",this._library.id)})}_doCreateRepresentation(e,t,i){const o=this._library._dcxBranch.addChild(void 0,void 0,void 0,this._dcxNode);if(o.type=e,o.setValue(this._config.RELATIONSHIP_KEY,t),void 0===i){const e=this.representations[this.representations.length-1],t=Math.max(this.representations.length,e?e._getOrder()+1:0);o.setValue(this._config.REPRESENTATION_ORDER_KEY,t)}else o.setValue(this._config.REPRESENTATION_ORDER_KEY,i),this._representations.forEach((e,t)=>{if(t>=i){const t=e._getDCXElement(),i=t.getValue(this._config.REPRESENTATION_ORDER_KEY);void 0!==i&&t.setValue(this._config.REPRESENTATION_ORDER_KEY,i+1)}});const r=new n(this,o);return this._addRepresentation(r,i),r}_getEventData(e,t){const i=!t&&{},n=this._dcxNode.getValue(this._config[e+"_DATA_KEY"])||i;if("CREATED"!==e&&"DESCRIPTION"!==e){const t=this._dcxNode.getValue(this._config[e+"_KEY"]);if(!t||t!==n.time)return i}return n}_isLocalEvent(e){const t=this._getEventData(e).deviceId;if(t&&this._config.DEVICE_ID)return t===this._config.DEVICE_ID}_getEventContext(e){const t=JSON.parse(JSON.stringify(this._getEventData(e)));return delete t.time,delete t.deviceId,delete t.userId,t}_clearEventData(e){this._dcxNode.getValue(this._config[e+"_DATA_KEY"])&&this._dcxNode.removeValue(this._config[e+"_DATA_KEY"])}_setEventData(e,t){if(!this._config.DEVICE_ID)return void this._clearEventData(e);const i={userId:this.library.collection.userId,deviceId:this._config.DEVICE_ID};this._config.DEVICE_DESCRIPTION&&(i.device=this._config.DEVICE_DESCRIPTION),this._config.APP_DESCRIPTION&&(i.app=this._config.APP_DESCRIPTION),t&&(i.time=t),this._dcxNode.setValue(this._config[e+"_DATA_KEY"],i)}_updateModifiedTime(){const e=Date.now();this._dcxNode.setValue(this._config.MODIFIED_KEY,e),this._setEventData("MODIFIED",e)}_updateCreatedTime(){const e=Date.now();this._dcxNode.setValue(this._config.CREATED_KEY,e),this._dcxNode.setValue(this._config.MODIFIED_KEY,e),this._setEventData("CREATED"),this._setEventData("MODIFIED",e)}_updateTimestampOnRemove(e){const t=e||Date.now();this._dcxNode.setValue(this._config.REMOVED_KEY,t),this._setEventData("REMOVED",t)}_updateTimestampOnRestore(){this._dcxNode.removeValue(this._config.REMOVED_KEY),this._clearEventData("REMOVED")}_ensureRemovedDataValid(e){this.removed&&!this._getEventData("REMOVED",!0)?e?this._setEventData("REMOVED",this.removed):this._clearEventData("REMOVED"):this.removed||this._clearEventData("REMOVED")}_ensureModifiedDataValid(e){this._getEventData("MODIFIED",!0)||(e?this._setEventData("MODIFIED",this.modified):this._clearEventData("MODIFIED")),this._ensureRemovedDataValid(e)}_ensureCreatedDataValid(e){e&&!this._getEventData("CREATED",!0)&&this._setEventData("CREATED"),this._ensureModifiedDataValid(e)}_commit(e){this._displayName=void 0,this._updateModifiedTime(),this._forEachRepresentation(e=>e._clearCachedExternalLink(!0)),this._listenerManager.notify("change"),this._library._commit(),this._analytics.reportUpdateElement(this,e)}_commitMetadata(){this._listenerManager.notify("change"),this._library._commit()}_wrapOperation(e,t){return this._library._wrapOperation(()=>{const i=this._library._wrapOperation(e,t);return this._updateModifiedTime(),this._listenerManager.notify("change"),i})}_getMissingLocalComponents(){return this._representations.reduce((e,t)=>e.concat(t._getMissingLocalComponents()),[])}_forEachRepresentation(e,t=this.representations){t.forEach(t=>{e(t),this._forEachRepresentation(e,t.children)})}_shouldGCLocalData(){const e=Date.now();return this.removed&&e-this.removed>=this._config.REMOVED_ELEMENTS_CACHE_TIMEOUT}jasmineToString(){return this.toString()}toString(){return JSON.stringify(this._toJSON())}_stripObsoleteGroupsData(e){const t=this._dcxNode.getValue(this._config.GROUPS_KEY);if(!t)return;const i=(e=e||this._config.DEFAULT_GROUP_CLASSIFIER)+"#";let n=!1;Object.keys(t).forEach(e=>{if(e.startsWith(i)){const o=e.substring(i.length);this.library.getGroupById(o)||(delete t[e],n=!0)}}),n&&this._dcxNode.setValue(this._config.GROUPS_KEY,t)}_prefetchRenditions(){if(!this._services.hasFileSystem())return Promise.resolve();const e=this._config.RENDITION_SIZES||{},t=e[this.type]||e["*"]||[],i=d(this.getThumbnailPath.bind(this)),n=t.map(e=>i(e));return this._config.shouldPrefetchFullRendition(this)&&n.push(i(void 0)),this._forEachRepresentation(e=>{if(this._config.shouldPrefetchExternalLink(e)){const t=d(e.getContentPath.bind(e));n.push(t())}else if(e.isExternalLink){const t=d(e.testExternalLink.bind(e));n.push(t())}}),Promise.all(n).catch(()=>{})}_getRenditionCandidate(e){let t,i=0;if("vector"===e&&this.supportsVectorThumbnail())return this.getPrimaryRepresentation();for(let n=0;n<this._representations.length;n++){const o=this._representations[n],r=Math.max(o.width||0,o.height||0),s=o.isFullSize?Number.POSITIVE_INFINITY:r,a="primary"===o.relationship,l="rendition"===o.relationship;if((!t||o.isPreferredThumbnail&&!t.isPreferredThumbnail||a&&"primary"!==t.relationship||l&&"primary"!==t.relationship&&"rendition"!==t.relationship||l&&"rendition"===t.relationship&&s>i)&&c.canComputeRendition(o)&&(t=o,i=s),l&&"image/png"===o.type&&e&&r===e)break}return t}_setRenditionCache(e,t,i,n,o){this.library._renditionCache.setCache(this,e,t,i).then(e=>{n&&this._storageInterface.notifyDownloadRendition(this),o(null,e)},o)}_doSetOrderInGroup(e,t,i){const n=this._dcxNode.getValue(this._config.GROUPS_KEY)||{},o=e.classifierName+"#"+e.id;i&&Object.keys(n).forEach(t=>{t.startsWith(e.classifierName+"#")&&delete n[t]}),void 0===t&&n[o]&&delete n[o],void 0!==t&&(n[o]={order:t}),this._dcxNode.setValue(this._config.GROUPS_KEY,n)}_getActions(e){const t=this.getPrimaryRepresentation();if(!t)return[];const i=this._config.ELEMENT_ACTION_PRODUCT_MAP,n=(i.types[this.type]||{})[t.type]||[],o=[];n.forEach(t=>{!i.products[t]||e&&e!==i.products[t].action||o.push(new r(this,i.products[t]))});const s=o.map((e,t)=>({i:t,v:e}));return s.sort((e,t)=>e.v.isCompatibleVersionInstalled&&!t.v.isCompatibleVersionInstalled?-1:t.v.isCompatibleVersionInstalled&&!e.v.isCompatibleVersionInstalled?1:e.i-t.i),s.map(e=>e.v)}get id(){return this._dcxNode.id}get library(){return this._library}get isWritable(){return this._library.isWritable}get name(){return this._dcxNode.name||""}set name(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);this._dcxNode.name=e,this._commit(!0)}get displayName(){return void 0===this._displayName&&(this._displayName=this._services.getDisplayName(this)||""),this._displayName}get type(){return this._dcxNode.type}get tags(){return this._dcxNode.getValue("tags")||[]}set tags(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if(!e||e.constructor!==Array)throw new o(o.INVALID_PARAMETER,"tags must be an array",this._library.id);if(!e.every(e=>"string"==typeof e))throw new o(o.INVALID_PARAMETER,"tags must be an array of strings",this._library.id);0===e.length?this._dcxNode.removeValue("tags"):this._dcxNode.setValue("tags",e),this._commit(!0)}get description(){return this._dcxNode.getValue(this._config.DESCRIPTION_KEY)||""}set description(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);this._dcxNode.setValue(this._config.DESCRIPTION_KEY,e);const t=Date.now();this._setEventData("DESCRIPTION",t),this._commitMetadata(),this._analytics.reportSetDescription(this)}get descriptionModified(){return this._getEventData("DESCRIPTION").time||0}get descriptionModifiedBy(){return this._getEventData("DESCRIPTION").userId}get descriptionModifiedContext(){return this._getEventContext("DESCRIPTION")}get wasDescriptionModifiedLocally(){return this._isLocalEvent("DESCRIPTION")}get modified(){return this._dcxNode.getValue(this._config.MODIFIED_KEY)}get modifiedBy(){return this._getEventData("MODIFIED").userId}get modifiedContext(){return this._getEventContext("MODIFIED")}get wasModifiedLocally(){return this._isLocalEvent("MODIFIED")}get created(){return this._dcxNode.getValue(this._config.CREATED_KEY)}get createdBy(){return this._getEventData("CREATED").userId}get createdContext(){return this._getEventContext("CREATED")}get wasCreatedLocally(){return this._isLocalEvent("CREATED")}get removed(){return this._dcxNode.getValue(this._config.REMOVED_KEY)}get removedBy(){return this._getEventData("REMOVED").userId}get removedContext(){return this._getEventContext("REMOVED")}get wasRemovedLocally(){return this._isLocalEvent("REMOVED")}get representations(){return this._representations}get isDeletedLocally(){return this._deletedLocally}get sourceRef(){return this._dcxNode.getValue(this._config.SOURCE_REF_KEY)}set sourceRef(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if("string"!=typeof e||!e.startsWith("urn:"))throw new o(o.INVALID_PARAMETER,"sourceRef must be a string and a valid URN",this._library.id);this._dcxNode.setValue(this._config.SOURCE_REF_KEY,e),this._commit(!0)}addChangeListener(e){a.checkDeletedState(this),this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}beginOperation(){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this.id);this._transactionCount++,this._library._beginOperation()}endOperation(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this.id);this._transactionCount>0&&(this._transactionCount--,this._library._endOperation()),e&&this._library._waitForCommit(e,!0)}createRepresentation(e,t,i,n){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);return this._wrapOperation(()=>{if(e===this._config.LINK_REPRESENTATION_TYPE)throw new o(o.INVALID_PARAMETER,"Cannot create external link representation directly - use setContentFromURL instead",this._library.id);if(void 0!==i&&(i<0||i>this._representations.length))throw new o(o.INVALID_PARAMETER,"Invalid index",this._library.id);this._validateRelationship(t);const r=this._doCreateRepresentation(e,t,i);return n||this.library._renditionCache.clearCache(this,!0),r})}removeRepresentation(e){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);return this._wrapOperation(()=>{this._removeRepresentation(e),e._dcxComponent?this._library._dcxBranch.removeComponent(e._dcxComponent):this._library._dcxBranch.removeChild(e._dcxNode),this.library._renditionCache.clearCache(this,!0),e._markDeletedLocally(!0)})}removeAllRepresentations(){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);return this._wrapOperation(()=>{for(;this._representations[0];)this.removeRepresentation(this._representations[0])})}getPrimaryRepresentation(){return this._representations.find(e=>"primary"===e.relationship)}getValue(e,t){if(e===this._config.DL_NAMESPACE)throw new o(o.INVALID_PARAMETER,"Reserved namespace",this._library.id);const i=a.getDCXKey(e,t);return this._dcxNode.getValue(i)}getValues(){return a.getCustomDCXData(this._dcxNode)}setValue(e,t,i){if(a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if(e===this._config.DL_NAMESPACE)throw new o(o.INVALID_PARAMETER,"Reserved namespace",this._library.id);const n=a.getDCXKey(e,t);let r;try{r=JSON.parse(JSON.stringify(i))}catch(e){throw new o(o.INVALID_PARAMETER,"Value cannot be serialized to JSON",this._library.id)}this._dcxNode.setValue(n,r),this._commit()}removeValue(e,t){if(e===this._config.DL_NAMESPACE)throw new o(o.INVALID_PARAMETER,"Reserved namespace",this.id);const i=a.getDCXKey(e,t);this._dcxNode.removeValue(i)}getThumbnailURL(e,t){a.checkDeletedState(this,t)||this._library._waitForCommit(()=>{if(a.checkDeletedState(this,t))return;const i=this._getRenditionCandidate(e);if(i){this._library._collection._syncManager.renditions.getURL(i,e,t)}else t(new o(o.THUMBNAIL_NOT_AVAILABLE,"no representation that can be converted into a thumbnail",this._library.id))},!0)}getAuthenticatedThumbnailURL(e,t){this.getThumbnailURL(e,(e,i)=>{if(e)return void t(e);this._library._collection._syncManager.appendAccessTokenToURL(i,t)})}getThumbnailPath(e,t){this._services.hasFileSystem()?a.checkDeletedState(this,t)||this._library._waitForCommit(()=>{if(a.checkDeletedState(this,t))return;if(this._config.SHARED_LOCAL_STORAGE)return void this._storageInterface.getRenditionPath(this,e,t);const i=(e,i)=>{this._renditionFetchLock.release(),t(e,i)};this._renditionFetchLock.obtain(()=>{if(a.checkDeletedState(this,i))return;const t=this.library._renditionCache.getCache(this,e);if(t)return void i(null,t);const n=this._getRenditionCandidate(e);if(n){if("rendition"===n.relationship&&"image/png"===n.type&&e&&Math.max(n.width||0,n.height||0)===e)return void n.getContentPath(i);const t=this._library._collection._syncManager,r=this.modified,s=(t,n)=>{this.modified>r?i(new o(o.STALE_THUMBNAIL,"element changed before the rendition was received",this._library.id,t)):a.checkDeletedState(this,i)||(t?i(new o(o.THUMBNAIL_NOT_AVAILABLE,"error generating thumbnail",this._library.id,t)):this._setRenditionCache(e,n,!0,!0,i))};this._services.hasRenditionGenerator()&&e&&"vector"!==e?n.getContentPath((i,o)=>{if(i||!o)return void t.renditions.download(n,e,s);const r=n.element.library.collection._getTempDir()+this._services.getPathSeparator()+this._services.uuid()+".png";this._services.renditionGenerator(o,r,e,i=>{i?t.renditions.download(n,e,s):s(null,r)})}):t.renditions.download(n,e,s)}else i(new o(o.THUMBNAIL_NOT_AVAILABLE,"no representation that can be converted into a thumbnail",this._library.id))})},!0):t(new o(o.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this._library.id))}getCachedThumbnailPath(e){return this.library._renditionCache.getCache(this,e)}getThumbnailContent(e,t,i){const n=this._services.fs;this._services.hasFileSystem()?a.checkDeletedState(this,i)||a.checkEncoding(t,["utf8","ascii","base64","buffer"],i)&&this.getThumbnailPath(e,(e,o)=>{if(e||!o)return void i(e);if(a.checkDeletedState(this,i))return;const r=(e,t)=>{e&&(e=l.getCommitError(e,this._library.id,"error reading content from disk")),i(e,t)};"buffer"===t?n.readFile(o,r):n.readFile(o,t,r)}):i(new o(o.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this._library.id))}setThumbnailCache(e,t,i){"string"==typeof t?this._services.hasFileSystem()?a.checkDeletedState(this,i)||this._setRenditionCache(e,t,!1,!1,i):i(new o(o.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this._library.id)):i(new o(o.INVALID_PARAMETER,"path must be a string",this._library.id))}supportsVectorThumbnail(){const e=this.getPrimaryRepresentation();return!!e&&this._config.VECTOR_RENDITION_ELEMENT_TYPES.indexOf(e.type)>-1}getActions(e){if(!this._config.SHARED_LOCAL_STORAGE)throw new o(o.NOT_SUPPORTED,"getActions() not supported without shared local storage");if(e&&-1===this._config.ELEMENT_ACTIONS.indexOf(e))throw new o(o.INVALID_PARAMETER,"Unknown id supplied. Potential ids are",this._config.ELEMENT_ACTIONS.join(", "));return this._getActions(e)}getGroups(e){e=e||this._config.DEFAULT_GROUP_CLASSIFIER;const t=this._dcxNode.getValue(this._config.GROUPS_KEY);if(!t)return[];const i=Object.keys(t);return this.library.getGroups(e).filter(e=>void 0!==this.getOrderInGroup(e)).sort((e,t)=>{const n=i.indexOf(e.classifierName+"#"+e.id),o=i.indexOf(t.classifierName+"#"+t.id);return n===o?0:n<o?-1:1})}getOrderInGroup(e){if(!e)throw new o(o.INVALID_PARAMETER,"No group specified",this._library.id);if(e.library!==this.library)return;const t=this._dcxNode.getValue(this._config.GROUPS_KEY)||{},i=e.classifierName+"#"+e.id;return t[i]&&t[i].order}setOrderInGroup(e,t,i){if(i=!1!==i,a.checkDeletedState(this),!this.isWritable)throw new o(o.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if(!e)throw new o(o.INVALID_PARAMETER,"No group specified",this._library.id);if(e.library!==this.library)throw new o(o.INVALID_PARAMETER,"Cannot set element order in a group that is in a different library.",this._library.id);if("string"!=typeof t&&void 0!==t)throw new o(o.INVALID_PARAMETER,"order must be a string",this._library.id);this._doSetOrderInGroup(e,t,i),this._commitMetadata(),this._analytics.reportSetOrderInGroup(this,e,i)}getReference(){return"cloud-asset://"+this._library._collection._syncManager.getElementRefDomain()+this._library._collection._syncManager.getElementRefPath()+"/"+this._library.id+";node="+this.id}getRepresentationById(e){return this.representations.find(t=>t.id===e)}}},function(e,t,i){const n=i(1),o=i(17),r=i(23),s=i(10),a=i(6);class c{constructor(e,t,i){e instanceof c?this._parent=e:this._element=e,t?this._setDCXNode(t):this._setDCXComponent(i),this._lock=new o,this._pendingDownloadCallbacks=[]}get _services(){return this.element._services}get _storageInterface(){return this.element._storageInterface}get _config(){return this.element._config}_setDCXNode(e){const t={};this._children&&this._children.forEach(e=>{t[e.id]=e}),this._dcxNode=e,delete this._dcxComponent,this._deletedLocally=!1,this._children=[],this.element.library._dcxBranch.getChildrenOf(e).forEach(e=>{let i=t[e.id];i?(i._setDCXNode(e),delete t[e.id]):i=new c(this,e),this._children.push(i)}),this.element.library._dcxBranch.getComponentsOf(e).forEach(e=>{let i=t[e.id];i?(i._setDCXComponent(e),delete t[e.id]):i=new c(this,void 0,e),this._children.push(i)})}_setDCXComponent(e,t){this._dcxComponent=e,delete this._dcxNode,this._children=[],t||(this._deletedLocally=!1)}_markDeletedLocally(e){this._deletedLocally=e}_toJSON(){const e={id:this.id,type:this.type,relationship:this.relationship};return this._services.hasFileSystem()&&(e._componentPath=this._getComponentPath()),e}_getOrder(){return this._getDCXElement().getValue(this._config.REPRESENTATION_ORDER_KEY)||0}_setComponentInBrowser(e,t,i){this.element._library._collection._syncManager.uploadNewComponentForRepresentation(e,t,this,(e,t)=>{if(s.checkDeletedState(this,i))return void i(e);if(e)return void i(e);s.copyCustomDCXData(this._dcxNode,t),this.element._library._dcxBranch.removeChild(this._dcxNode),this._setDCXComponent(t,!0),this._commit(),i(null)})}_setComponentFromPath(e,t,i,n){const o=e&&this._services.getFileNameFromPath(e),r=this._services.fileUtils.getFileExtension(o),a=this.id+"."+r;this._services.fileUtils.checkFileSize(e,r=>{r?n(r):this._storageInterface.getImageDimensions(e,r=>{this._storageInterface.notifyStartWrite(this.element._library,[],()=>{const c=this.element._library._dcxBranch,l=this._parent?this._parent._dcxNode:this._element._dcxNode;c.addComponent(o,this.type,this.relationship,a,e,i,void 0,l,this.id,(e,i)=>{s.checkDeletedState(this,n)||(e?n(e):(s.copyCustomDCXData(this._dcxNode,i),c.removeChild(this._dcxNode),this._setDCXComponent(i,!0),r&&(i.setValue("width",r.width),i.setValue("height",r.height)),t&&i.setValue(this._config.SHA_KEY,t),this._commit(),n(null)))})})})})}_setComponent(e,t,i,n){const o=this._services.fs;let c;const l=e=>{s.checkDeletedState(this,n)||(e?n(a.getCommitError(e,this.element._library.id,"error writing representation contents")):this._setComponentFromPath(c,void 0,!1,n))};const h=this.element.library.collection._getTempDir();this._services.fileUtils.ensurePathExists(h,d=>{if(!s.checkDeletedState(this,n))if(d)n(a.getCommitError(d,this.element._library.id,"error creating temp directory"));else{if(!i){const e=r.getExtensions(this.type)[0];i=this.id+"."+e}c=h+this._services.getPathSeparator()+i,"buffer"===t?o.writeFile(c,e,l):o.writeFile(c,e,t,l)}})}_getCurrentComponentPath(){if(this._dcxComponent)return this.element._library._dcxBranch.assetOfComponent(this._dcxComponent)}_getComponentPath(e,t){if(!e)return this._getCurrentComponentPath();if(this.isExternalLink){return this.element.library.collection._externalLinkCache.getExternalLink(this).then(t=>e(null,t),e)}if(this._dcxComponent){const i=this._getCurrentComponentPath();if(i||t)e(null,i);else{const t=this.element._library;t._networkLock.obtain(i=>{if(i)return void e(i);if(s.checkDeletedState(this,e))return void t._networkLock.release();t._setSyncState("downloading"),t._collection._syncManager.downloadRepresentation(this,i=>{t._networkLock.release(),t._setSyncState(),s.checkDeletedState(this,e)||(i?e(a.getSyncError(i,this.element._library.id)):(t._commit(!0,!0),t._notifyChange(),this._getComponentPath(e,!0)))})})}}else{const t=this._getContentFromData();if(t){const i=this.element.library._renditionCache.getCache(this.element,this.id);i?e(null,i):this._generateContentDataFile(t,e)}else e(null)}}_getContentFromData(){if(this._services.hasFileSystem()){const e=this._config.REPRESENTATION_CONTENT_VALUES[this.type];if(e&&e.contentFromData)return this.getValue(e.namespace,e.key)}}_setExternalLink(e,t){if(this._dcxNode.setValue(this._config.LINK_TYPE_KEY,this._dcxNode.type),this._dcxNode.type=this._config.LINK_REPRESENTATION_TYPE,this._dcxNode.setValue(this._config.LINK_URL_KEY,e),t){t=t.replace(/\\/g,"/");const i=this._config.DEFAULT_CONTENT_LOCATIONS.find(e=>t.startsWith(e));if(i){const e=t.substring(i.length);this._dcxNode.setValue(this._config.LINK_LOCAL_PATH_KEY,e)}return this.element.library.collection._externalLinkCache.ensureExternalLinkCache(e,t)}return Promise.resolve()}_clearCachedExternalLink(e){const t=this.element.library.collection._externalLinkCache;t&&this.isExternalLink&&(!e||t.getCachedError(this))&&(this._config.SHARED_LOCAL_STORAGE?this._storageInterface.clearCachedExternalLink(this):this._config.shouldPrefetchExternalLink(this)?t.getExternalLink(this,!0).catch(()=>{}):t.testExternalLink(this,!0).catch(()=>{}))}_getLinkLocalPaths(){const e=this._dcxNode&&this._dcxNode.getValue(this._config.LINK_LOCAL_PATH_KEY);return e?this._config.DEFAULT_CONTENT_LOCATIONS.map(t=>`${t}${e}`):[]}_setContentFromPath(e,t,i){const n=n=>{const o=n&&this._config.SHA_CACHE[n];if(o){this._dcxNode.setValue(this._config.SHA_KEY,n);const t=()=>{this._commit(),i(null)};this._setExternalLink(o,e).then(t,t)}else this._setComponentFromPath(e,n,t,i)};this._storageInterface.computeSHA(e).then(n,()=>n())}_generateContentDataFile(e,t){const i=this.element.library.collection._getTempDir(),n=r.getExtensions(this.type)[0];this._services.fileUtils.writeJSONData(i,this.id+"."+n,e).then(e=>{this.element.setThumbnailCache(this.id,e,(e,i)=>{this._storageInterface.notifyDownloadRendition(this.element),t(e,i)})},e=>t(a.getCommitError(e)))}_getDCXElement(){return this._dcxComponent||this._dcxNode}_commit(e){e?this.element._commitMetadata():this.element._commit()}_getMissingLocalComponents(){return this._services.hasFileSystem()&&this._dcxComponent&&!this._getCurrentComponentPath()?[this._dcxComponent]:[]}jasmineToString(){return this.toString()}toString(){return JSON.stringify(this._toJSON())}get id(){return this._getDCXElement().id}get element(){return this._parent?this._parent.element:this._element}get children(){return this._children}get isWritable(){return this.element.isWritable}get type(){const e=this._getDCXElement().type;return e===this._config.LINK_REPRESENTATION_TYPE?this._getDCXElement().getValue(this._config.LINK_TYPE_KEY):e}get relationship(){return this._dcxComponent?this._dcxComponent.relationship||this._dcxComponent.getValue(this._config.RELATIONSHIP_KEY):this._dcxNode.getValue(this._config.RELATIONSHIP_KEY)||this._dcxNode.getValue("relationship")}set relationship(e){if(this._parent)throw new n(n.NOT_ALLOWED,"you cannot set relationship on child representations",this.element._library.id);this.element._validateRelationship(e,this),this._dcxComponent?this._dcxComponent.relationship=e:this._dcxNode.setValue(this._config.RELATIONSHIP_KEY,e)}get width(){return this._dcxComponent?this._dcxComponent.getValue("width"):this._dcxNode.getValue(this._config.WIDTH_KEY)}set width(e){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id);if(!this._dcxComponent&&!this.isExternalLink)throw new n(n.INVALID_PARAMETER,"Cannot set width on a representation without contents",this.element._library.id);if("number"!=typeof e||e<0)throw new n(n.INVALID_PARAMETER,"Invalid width",this.element._library.id);this._dcxComponent?this._dcxComponent.setValue("width",e):this._dcxNode.setValue(this._config.WIDTH_KEY,e),this._commit()}get height(){return this._dcxComponent?this._dcxComponent.getValue("height"):this._dcxNode.getValue(this._config.HEIGHT_KEY)}set height(e){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id);if(!this._dcxComponent&&!this.isExternalLink)throw new n(n.INVALID_PARAMETER,"Cannot set height on a representation without contents",this.element._library.id);if("number"!=typeof e||e<0)throw new n(n.INVALID_PARAMETER,"Invalid height",this.element._library.id);this._dcxComponent?this._dcxComponent.setValue("height",e):this._dcxNode.setValue(this._config.HEIGHT_KEY,e),this._commit()}get isFullSize(){return this._getDCXElement().getValue(this._config.IS_FULL_SIZE_KEY)}set isFullSize(e){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id);if(!this._dcxComponent&&!this.isExternalLink)throw new n(n.INVALID_PARAMETER,"Cannot set isFullSize on a representation without contents",this.element._library.id);if("boolean"!=typeof e)throw new n(n.INVALID_PARAMETER,"Invalid isFullSize",this.element._library.id);this._getDCXElement().setValue(this._config.IS_FULL_SIZE_KEY,e),this._commit()}get isPreferredThumbnail(){return this._getDCXElement().getValue(this._config.IS_PREFERRED_THUMBNAIL_KEY)||!1}set isPreferredThumbnail(e){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id);if("boolean"!=typeof e)throw new n(n.INVALID_PARAMETER,"Invalid isPreferredThumbnail",this.element._library.id);this._getDCXElement().setValue(this._config.IS_PREFERRED_THUMBNAIL_KEY,e),this._commit()}get contentLength(){if(this.isExternalLink)return this._dcxNode.getValue(this._config.LENGTH_KEY);if(this._dcxComponent){if(void 0===this._dcxComponent.length&&this._services.hasFileSystem()){const e=this._getCurrentComponentPath();try{const t=this._services.fs.statSync(e);return t&&t.size}catch(e){}}return this._dcxComponent.length}}set contentLength(e){if(!this.isExternalLink)throw new n(n.READ_ONLY,"setContentLength can only be used for an externally-linked representation",this.element._library.id);if("number"!=typeof e||e<0)throw new n(n.INVALID_PARAMETER,"Invalid content length",this.element._library.id);this._dcxNode.setValue(this._config.LENGTH_KEY,e),this._commit()}get contentHash(){return this._getDCXElement().getValue(this._config.SHA_KEY)}get isDeletedLocally(){return this._deletedLocally}get isExternalLink(){return void 0!==this._dcxNode&&this._dcxNode.type===this._config.LINK_REPRESENTATION_TYPE}isCompatibleType(e){if(this._dcxComponent){const t=this._services.fileUtils.getFileExtension(this._dcxComponent.path);if(-1===r.getExtensions(e).indexOf(t))return!1}return s.isCompatibleType(e,this.type)}getValue(e,t){if(e===this._config.DL_NAMESPACE)throw new n(n.INVALID_PARAMETER,"Reserved namespace",this.element._library.id);const i=s.getDCXKey(e,t);return this._getDCXElement().getValue(i)}getValues(){return s.getCustomDCXData(this._getDCXElement())}setValue(e,t,i,o=!1){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id);if(e===this._config.DL_NAMESPACE)throw new n(n.INVALID_PARAMETER,"Reserved namespace",this.element._library.id);const r=s.getDCXKey(e,t);let a;try{a=JSON.parse(JSON.stringify(i))}catch(e){throw new n(n.INVALID_PARAMETER,"Value cannot be serialized to JSON",this.element._library.id)}this._getDCXElement().setValue(r,a),this._commit(o)}setContent(e,t,i,o){if(!s.checkDeletedState(this,o))if(this.isWritable)if(this._dcxComponent||this.isExternalLink)o(new n(n.INVALID_PARAMETER,"Cannot modify representation content once set",this.element._library.id));else if(this._services.hasFileSystem()){if(!s.checkEncoding(t,["utf8","ascii","base64","buffer"],o))return;this._setComponent(e,t,i,o)}else{if(void 0!==t)return void o(new n(n.INVALID_PARAMETER,"Encoding parameter not supported in-browser"));this._setComponentInBrowser(e,i,o)}else o(new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id))}setContentFromPath(e,t,i){"function"==typeof t&&(i=t,t=!1),this._services.hasFileSystem()?s.checkDeletedState(this,i)||(this.isWritable?this._dcxComponent||this.isExternalLink?i(new n(n.INVALID_PARAMETER,"Cannot modify representation content once set",this.element._library.id)):this._setContentFromPath(e,!t,i):i(new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id))):i(new n(n.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this.element._library.id))}setContentFromURL(e,t,i,o){if(!this._services.hasFileSystem()&&!e)return void o(new n(n.NOT_IMPLEMENTED,"not yet implemented setContentFromURL without a filesystem",this.element._library.id));if(s.checkDeletedState(this,o))return;if(!this.isWritable)return void o(new n(n.NOT_ALLOWED,"you do not have write access to this library",this.element._library.id));if("boolean"!=typeof e)return void o(new n(n.INVALID_PARAMETER,"Invalid createLink parameter: must be Boolean",this.element._library.id));if(this._dcxComponent||this.isExternalLink)return void o(new n(n.INVALID_PARAMETER,"Cannot modify representation content once set",this.element._library.id));if(e)return this._setExternalLink(t),this._commit(),void o(null);const c=this.element.library.collection,l=c._getTempDir();this._storageInterface.downloadURL(c,t,i,l,(e,t,i,n)=>{if(e)return void o(a.getSyncError(e));if(s.checkDeletedState(this,o))return;const c=this._config.getContentTypeHeader(n&&n.headers);if(c){const e=t+"."+r.getExtensions(c)[0];this._services.fileUtils.rename(t,e,t=>{t?o(a.getCommitError(t)):this._setComponentFromPath(e,void 0,!1,o)})}else this._setComponentFromPath(t,void 0,!1,o)})}getContentPath(e){this._services.hasFileSystem()?s.checkDeletedState(this,e)||this._getComponentPath(e):e(new n(n.REQUIRES_FILESYSTEM,"path-based APIs require a filesystem",this.element._library.id))}getCachedContentPath(){if(!this._services.hasFileSystem())return;if(this.isExternalLink){return this.element.library.collection._externalLinkCache.getCachedPath(this)}if(this._dcxComponent)return this._getCurrentComponentPath()||void 0;return this._getContentFromData()&&this.element.library._renditionCache.getCache(this.element,this.id)||void 0}getContent(e,t){const i=this._services.fs;if(!s.checkDeletedState(this,t))if(this._services.hasFileSystem()){if(!s.checkEncoding(e,["utf8","ascii","base64","buffer"],t))return;this._getComponentPath((n,o)=>{if(n||!o)return void t(n);if(s.checkDeletedState(this,t))return;const r=(e,i)=>{e&&(e=a.getCommitError(e,this.element._library.id,"error reading content from disk")),t(e,i)};"buffer"===e?i.readFile(o,r):i.readFile(o,e,r)})}else{if(!s.checkEncoding(e,["text","blob","arraybuffer"],t))return;if(!this._dcxComponent)return void t(null);this.element._library._collection._syncManager.getContent(this._dcxComponent,e,t)}}getContentURL(){if(this.isExternalLink)return this._dcxNode.getValue(this._config.LINK_URL_KEY);if(this._dcxComponent){return this.element._library._collection._syncManager.getContentURL(this._dcxComponent)}}getAuthenticatedContentURL(e){const t=this.getContentURL();this.element._library._collection._syncManager.appendAccessTokenToURL(t,e)}createChild(e){if(!this._dcxNode)throw new n(n.NOT_ALLOWED,"can't create child on a component representation",this.element.library.id);const t=this.element.library._dcxBranch.addChild(void 0,void 0,void 0,this._dcxNode);t.type=e,t.setValue(this._config.RELATIONSHIP_KEY,this._config.RELATIONSHIP_CHILD);const i=new c(this,t);return this._children.push(i),this._commit(),i}removeChild(e){if(s.checkDeletedState(this),!this.isWritable)throw new n(n.NOT_ALLOWED,"you do not have write access to this library",this._library.id);if(e._parent!==this)throw new n(n.INVALID_PARAMETER,"cannot remove a child that doesn't belong to this representation",this._library.id);e._dcxComponent?this.element.library._dcxBranch.removeComponent(e._dcxComponent):this.element.library._dcxBranch.removeChild(e._dcxNode);const t=this._children.indexOf(e);-1!==t&&this._children.splice(t,1),this._commit()}testExternalLink(e){this.isExternalLink&&this.getContentURL()?this.element.library.collection._externalLinkCache.testExternalLink(this).then(()=>e(null,!0),()=>e(null,!1)):e(new n(n.INVALID_PARAMETER,"Not an external link",this.element._library.id))}clearCachedExternalLink(){if(!this.isExternalLink||!this.getContentURL())throw new n(n.INVALID_PARAMETER,"Not an external link",this.element._library.id);this._clearCachedExternalLink()}getCachedExternalLinkError(){if(!this.isExternalLink||!this.getContentURL())return new n(n.INVALID_PARAMETER,"Not an external link",this.element._library.id);return this.element.library.collection._externalLinkCache.getCachedError(this)}getExternalLinkDownloadProgress(){if(this.isExternalLink)return this.element.library.collection._getExternalLinkDownloadProgress(this)}}e.exports=c},function(e,t,i){const n=i(1),o=i(8);e.exports=class{constructor(e,t){this._element=e,this._id=t.action,this._appCode=t.appCode,this._appName=t.appName,this._minVersion=t.minVersion,this._installedVersions=this._config.ELEMENT_ACTION_PRODUCT_MAP.installedApps.filter(e=>e.code===t.appCode).map(e=>e.version).sort(o.compareVersions),this._invokable=this._installedVersions.length>0&&o.compareVersions(t.minVersion,this._installedVersions[0])>=0,Object.freeze(this._installedVersions)}get _config(){return this._element._config}get _analytics(){return this._element._analytics}get _storageInterface(){return this._element._storageInterface}get id(){return this._id}get element(){return this._element}get appCode(){return this._appCode}get appName(){return this._appName}get minAppVersion(){return this._minVersion}get installedVersions(){return this._installedVersions}get isCompatibleVersionInstalled(){return!!this._invokable}invoke(e=(()=>{})){this.isCompatibleVersionInstalled?(this._analytics.reportElementActionInvoked(this),this._storageInterface.sendElementAction(this,(t,i)=>{t?(t=-1!==["APP_NOT_INSTALLED","NO_COMPATIBLE_VERSION"].indexOf(t)?new n(n.NO_COMPATIBLE_APP_FOUND,"A compatible version of application is needed for this action:"+t):new n(n.APP_LAUNCH_FAILED,"Launching the app failed:"+t),this._analytics.reportElementActionFailed(this,t)):this._analytics.reportElementActionSuccessful(this,i),e(t,i)})):e(new n(n.NO_COMPATIBLE_APP_FOUND,"A compatible version of application is needed for this action",this._appCode))}}},function(e,t,i){const n=i(58),o="renditions";e.exports=class extends n{constructor(e){super(e.collection._apiRoot,e._getRenditionCacheDir()),this._library=e,this._pendingSetCache=[]}getCache(e,t="full"){const i=this._getCache([o,e.id,t]);return this._getFilePath(i)}setCache(e,t="full",i,n=!1){return this._config.SHARED_LOCAL_STORAGE?this._requestSetCache(e.id,t,i):this._doTransaction(()=>this._setCache([o,e.id,t],i,n))}clearCache(e,t){const i=this._getCache([o,e.id]);return i?(t&&this._config.SHARED_LOCAL_STORAGE&&this._storageInterface.supportsClearRenditionCache()&&Object.keys(i).forEach(t=>this._requestSetCache(e.id,t,"CLEAR")),this._clearCache(e)):Promise.resolve()}copyCache(e,t){return this._config.SHARED_LOCAL_STORAGE?(this._copyCache(e,t),Promise.resolve()):this._doTransaction(()=>this._copyCache(e,t))}copyFullCache(e){return this._config.SHARED_LOCAL_STORAGE?this._copyFullCache(e):this._doTransaction(()=>this._copyFullCache(e))}serializeCache(e=!1,t){const i={},n=n=>{i[n.id]=this.serializeElementCache(n,e,t)};return this._library.elements.forEach(n),this._library.removedElements.forEach(n),i}serializeElementCache(e,t=!1,i){const n=Object.assign({},this._cache.renditions&&this._cache.renditions[e.id]||{});return t&&this._convertToAbsolutePaths(n),this._addExternalLinksToElementCache(n,e,t,i),n}replaceCache(e){this._cache={[o]:e}}replaceElementCache(e,t){this._cache.renditions=this._cache.renditions||{},this._cache.renditions[e.id]=t}checkAndInvalidateRenditions(e,t){const i=this._getCache([o,e.id])||{};let n;return Object.keys(i).some(o=>{if(!Number(o))return;const r=this._path.join(this._rootDir,i[o]),s=r&&this._fs.statSync(r);return s&&s.size>t?(this.clearCache(e),n=`Invalidating rendition - ${e.id} ${e.name} dimension: ${o} size: ${s.size}`,!0):void 0}),n}doRequestSetCache(){return this._requestingSetCache=this._pendingSetCache,this._pendingSetCache=[],{data:this._requestingSetCache.map(({element:e,size:t,path:i})=>({element:e,size:t,path:i})),cancel:()=>{this._pendingSetCache=this._requestingSetCache.concat(this._pendingSetCache),delete this._requestingSetCache},complete:e=>this._completeRequestSetCache(e)}}applyRequestSetCache(e){return this._doTransaction(()=>this._applyRequestSetCache(e))}gc(){const e={},t=t=>{t._shouldGCLocalData()||(e[t.id]=!0)};this._library.elements.forEach(t),this._library.removedElements.forEach(t);const i=this._cache.renditions||{};let n=!1;Object.keys(i).forEach(t=>{e[t]||(this._setCacheEntry([o,t]),n=!0)});const r=n?this.save():Promise.resolve(),s=this._library.collection._externalLinkCache;return r.then(()=>s&&s.gc())}_load(){return super._load().then(()=>{this.serializeCache(!0,!1)})}_gcUnreferencedFiles(){return this._library._dcxComposite.autoRemoveUnusedLocalFiles?super._gcUnreferencedFiles():Promise.resolve()}_copyCache(e,t){const i=e.library._renditionCache,n=i._getCache([o,e.id])||{},r=Object.keys(n).map(r=>{const s=i._getFilePath(n[r],!0);if(!s)return Promise.resolve();var a=e.getRepresentationById(r);if(a&&!t.getRepresentationById(r)){const i=e.representations.indexOf(a);i>=0&&i<t.representations.length&&(r=t.representations[i].id)}return i._isPath(s)?this._config.SHARED_LOCAL_STORAGE?this._requestSetCache(t.id,r,s):this._setCache([o,t.id,r],s):Promise.resolve(this._setCacheEntry([o,t.id,r],s))});return Promise.all(r)}_copyFullCache(e){return Promise.all(e.elements.map(e=>{const t=this._library.getElementById(e.id);return t?this._copyCache(e,t):Promise.resolve()}))}_requestSetCache(e,t,i){return new Promise((n,o)=>{this._pendingSetCache=this._pendingSetCache.filter(i=>!(i.element===e&&i.size===t&&"CLEAR"===i.path)),this._pendingSetCache.push({element:e,size:t,path:i,callback:(e,t)=>e?o(e):n(t)})})}_applyRequestSetCache(e){const t=e.map(({element:e,size:t,path:i})=>"CLEAR"===i?(this._setCacheEntry([o,e,t]),Promise.resolve()):this._setCache([o,e,t],i));return Promise.all(t)}_completeRequestSetCache(e){const t={};return e.forEach((e,i)=>{const n=this._requestingSetCache[i],r=this._library.getElementById(n.element);if(n&&r&&e&&0===e.indexOf(this._rootDir)){const i=e.substring(this._rootDir.length+1);this._setCacheEntry([o,n.element,n.size],i),t[r.id]=r}n&&n.callback(null,e)}),delete this._requestingSetCache,Object.keys(t).map(e=>t[e])}_clearCache(e,t){const i=t?[o,e.id,t]:[o,e.id];return this._setCacheEntry(i),this.save()}_convertToAbsolutePaths(e){Object.keys(e).forEach(t=>{const i=e[t];e[t]=this._isPath(i)?this._path.join(this._rootDir,i):i})}_legacyGetCacheEntry(e){const t=this._getCache([o,e.element.id,e.id]);return this._getFilePath(t,!0)}_legacyClearCacheEntry(e){const t=[o,e.element.id,e.id];this._getCache(t)&&(this._setCacheEntry(t),this.save())}_addExternalLinksToElementCache(e,t,i=!1,n){e=e||{};const o=this._library.collection._externalLinkCache;t._forEachRepresentation(t=>{if(t.isExternalLink&&!e[t.id]){const r=o._getCacheEntry(t);r&&(e[t.id]=!i&&r.startsWith(o._rootDir)?this._path.relative(this._rootDir,r):r,o._notifyDownloadRendition(t,n))}})}}},function(e,t,i){const n=i(6),o=i(8).promisify,r=(e,t)=>{const i=e[t].bind(e);return(...e)=>o(i)(...e).catch(e=>Promise.reject(n.getCommitError(e)))};e.exports=(e,t)=>({stat:t=>r(e,"stat")(t),statSync(t){try{return e.statSync(t)}catch(e){}},unlink:t=>r(e,"unlink")(t),readdir:t=>r(e,"readdir")(t),rename:(e,i)=>r(t,"rename")(e,i),copy:(e,i)=>r(t,"copyFile")(e,i),ensureDir:e=>r(t,"ensurePathExists")(e),remove(e){return this.stat(e).then(i=>i&&i.isDirectory()?r(t,"recursiveDeleteDirectory")(e):this.unlink(e))}})},function(e,t){e.exports=e=>({join:(...t)=>t.join(e),relative(t,i){const n=t.replace(/\\/g,e).split(e),o=i.replace(/\\/g,e).split(e);for(;n[0]===o[0];)n.shift(),o.shift();return new Array(n.length).fill("..").concat(o).join(e)}})},function(e,t,i){const n=i(50),o=i(4),r=i(2),s=i(1),a=i(10),c=i(23),l=i(131),h=i(132),d=i(133),_=i(38);e.exports=class{constructor(e,t){this._apiRoot=e,this._isPublic=t.IS_PUBLIC,this._storageHost=t.STORAGE_HOSTNAME,this._storageHostRegex=t.STORAGE_HOSTNAME_REGEX,this._platformHost=t.PLATFORM_HOSTNAME,this._platformRootDocument=t.PLATFORM_ROOT_DOCUMENT,this._isACP=_.isACPHost(t.STORAGE_HOSTNAME),this._ccLibraryHost=t.CC_LIBRARY_SERVICE_HOSTNAME,this._invitationsHost=t.INVITATIONS_HOSTNAME,this._apiKey=this._config.STORAGE_API_KEY,this._XHR=t.XHR,this._requiresCommunitySession=t.REQUIRES_COMMUNITY_SESSION,this._getAccessToken=t.getAccessToken,this._httpServices=[],this._storageService=this._createStorageSession(this.getStorageHost(),!0),this._storageServices={},this._renditionSync=new h(this,t),this._externalLinkSync=new l(this),this._typekitSync=new d(this,t),this._lastSyncGroupState={},this._hasSetAuthToken=!1,this._authToken=void 0,this._inProgressSyncMap={},this._config.SHARED_LOCAL_STORAGE||this._isPublic||this._updateAuthToken()}get _config(){return this._apiRoot._config}get _services(){return this._apiRoot._services}get typekit(){return this._typekitSync}get renditions(){return this._renditionSync}get links(){return this._externalLinkSync}_getCommonRequestHeaders(){const e={};return this._config.USER_AGENT_HEADER&&(e["User-Agent"]=this._config.USER_AGENT_HEADER),e}_setAuthToken(e){this._hasSetAuthToken=!0,this._authToken=e,this._httpServices.forEach(t=>{e?(t.isActive=!0,t.setAuthToken(e)):t.isActive=!1})}_updateAuthToken(e=(()=>{})){this._getAccessToken(this._authToken,(t,i)=>{!t&&i?this._setAuthToken(i):(t&&t.code===s.ACCESS_DENIED&&this._apiRoot.getLoadedCollections().forEach(e=>{e._syncManager===this&&(e._reportSyncError(t),e._updateSyncState())}),this._setAuthToken()),e(null,i)})}_getAuthToken(e){this._hasSetAuthToken?e(null,this._authToken):this._updateAuthToken(e)}_authHandler(){this._updateAuthToken()}_createStorageSession(e,t){const i=this._isPublic&&e===this.getStorageHost();let n;if(t&&this._getAccessToken&&!i?(this._authToken||this._updateAuthToken(),n=this._services.dcx.createHTTPService(this._authHandler.bind(this)),n.setAuthToken(this._authToken),this._httpServices.push(n)):n=this._services.dcx.createHTTPService(),n.setTimeout(this._config.NETWORK_TIMEOUT),n.setAdditionalNodeOptions(this._services.getNodeTunnelOptions(e)),(t||i)&&(n.setApiKey(this._apiKey),n.setAdditionalHeaders(this._getCommonRequestHeaders())),this._XHR&&n._forceXhr(this._XHR),e===this.getStorageHost()){if(this._requiresCommunitySession)return this._services.dcx.createCommunitySession(n,e,this._storageHostRegex);if(this._isACP)return this._services.dcx.createPlatformSession(n,e,this._storageHostRegex,this._platformRootDocument)}return this._services.dcx.createStorageSession(n,e,this._storageHostRegex,this.getPlatformHost(),this._platformRootDocument)}_getStorageSession(e){var t=o.parseURI(e),i=t.scheme+"://"+t.authority,n=this._config.isAdobeDomain(t.authority);return this._storageServices[i]||(this._storageServices[i]=this._createStorageSession(i,n)),this._storageServices[i]}_doJSONRequest(e,t,i){const n=this._getStorageSession(t),o={"Content-Type":"application/json"};return i=i&&JSON.stringify(i),new Promise((r,a)=>{n._service.invoke(e,t,o,i,{responseType:"text"},(e,t)=>{if(e)return a(e);let i;if(t.response)try{i=JSON.parse(t.response)}catch(e){return void a(new s(s.TRANSFER_ERROR,`Invalid JSON: ${t.response}`))}r({statusCode:t.statusCode,response:i})})})}_isManifestOnly(){return"manifestOnly"===this._config.SYNC_POLICY||!this._services.hasFileSystem()}_pullCompositeComponents(e,t,i,o,r){if(this._isManifestOnly())r(null);else{var s=n.downloadComponents(e,t,this._storageService,r);this._inProgressSyncMap[o]=s,s.onProgress=function(e,t){0!==t&&i._updateProgress(o,e,t)}}}_pullComposite(e,t,i,o){this._inProgressSyncMap[i]=n.pullCompositeManifestOnly(e,this._storageService,(e,n)=>{if(e||!n)return void o(e,n);const r=(e,t)=>{t.push(...n.getComponentsOf(e)),n.getChildrenOf(e).forEach(e=>r(e,t))},s=n.getChildrenOf().find(e=>e.name===this._config.ELEMENTS_NAME),a=n.getComponentsOf();s&&r(s,a),this._pullCompositeComponents(a,n,t,i,e=>o(e,n))})}getServerComposites(e,t){if(!e._href)return t(null,[]);var i=this._lastSyncGroupState.etag;this._storageService.getCollection(e._href,i,(e,i,n,o)=>{if(e)e.response&&404===e.response.statusCode?t(null,[]):t(e);else{if(!i){var r=Math.max(this._config.DEFAULT_MAX_SYNC_INTERVAL,1e3*this._config.getRetryAfterHeader(o));return this._config.MAX_SYNC_INTERVAL=r,void t(null,[])}this._config.MAX_SYNC_INTERVAL=this._config.DEFAULT_MAX_SYNC_INTERVAL;var s=this._lastSyncGroupState.compositeEtags||{},c={},l=[],h={};(i.children||[]).forEach(e=>{e&&a.validateLibraryId(e.name,!1)&&(e.isUnmodified=e.etag&&s[e.name]===e.etag,l.push(e),h[e.name]=e,c[e.name]=e.etag)}),this._lastSyncGroupState={etag:n,compositeEtags:c},t(null,l,h)}})}deleteAllServerComposites(e,t){const i=e._href;i?this._storageService.deleteCompositeDirectory({href:i},t):t(null)}abortAllDownloads(){Object.keys(this._storageServices).map(e=>this._storageServices[e]).forEach(e=>e.abortAll())}clearSyncGroupCache(){this._lastSyncGroupState={}}doHeadRequest(e,t){let i;try{i=this._storageService.getCompositeManifestHref(e)}catch(e){return void t(e)}this._storageService.headRequest(i,t)}hasCompositeChangedOnServer(e,t){this.doHeadRequest(e,(i,n)=>{if(i)t(!0);else{var o=n&&n.headers&&n.headers.etag,r=e.current&&e.current.manifestEtag;t(o!==r)}})}downloadComponent(e,t,i){n.downloadComponents([t],e,this._storageService,i)}downloadRepresentation(e,t){var i=e._dcxComponent,n=e.element.library._dcxBranch;this.downloadComponent(n,i,t)}abortPushOrPull(e){this._inProgressSyncMap[e]&&(this._inProgressSyncMap[e].abort(new s(s.TRANSFER_ABORTED,"abort push or pull operation")),delete this._inProgressSyncMap[e])}pullLibrary(e,t){const i=e._dcxComposite,n=e.collection;let o=e.id;if(!o&&i.href){const e=i.href.split("/");o=e&&e[e.length-1]}this._services.log("Started pulling: "+o+(this._isManifestOnly()?" (manifest only)":""));var s=Date.now();n._updateProgress(o),this._pullComposite(i,n,o,(e,c)=>{var l=Date.now()-s;this._services.log("Finished pulling: "+o+(e?" ["+e.code+"]":"")+" duration="+l),delete this._inProgressSyncMap[o],n._updateProgress(o),c&&(c=c.copy(),a.ensureBranchDataValid(c)),e&&e.code===r.COMPONENT_DOWNLOAD_ERROR?this.doHeadRequest(i,(i,o)=>{if(!i&&o&&200===o.statusCode){var r=a.removeMissingComponents(n,e.pulledBranch.copy(),e.failedComponents);if(r)return void t(null,r)}t(e,c)}):t(e,c)})}pullMissingComponents(e,t){var i=e.id,n=e.collection,o=e._getMissingLocalComponents();if(this._isManifestOnly()||0===o.length)t(null);else{e._setSyncState("downloading"),this._services.log("Started pulling missing components: "+i);var r=Date.now();n._updateProgress(i),this._pullCompositeComponents(o,e._dcxBranch,n,i,o=>{var a=Date.now()-r;this._services.log("Finished pulling missing components: "+i+(o?" ["+o.code+"]":"")+" duration="+a),delete this._inProgressSyncMap[i],n._updateProgress(i),e._setSyncState(),o&&o.code===s.TRANSFER_ABORTED?t(null):t(o)})}}pushLibrary(e,t,i){const o=e._dcxComposite,r=e.collection,s=e.id;this._services.log("Started pushing: "+s);var a=Date.now();r._updateProgress(s),this._inProgressSyncMap[s]=n.pushComposite(o,t,this._storageService,e=>{var t=Date.now()-a;this._services.log("Finished pushing: "+s+(e?" ["+e.code+"]":"")+" duration="+t),delete this._inProgressSyncMap[s],r._updateProgress(s),i(e)}),this._inProgressSyncMap[s].onProgress=(e,t)=>{0!==t&&r._updateProgress(s,e,t)}}pushDeletedLibrary(e,t,i,n){const o=e._dcxComposite;if("incoming"===t)return this._services.log("Deleting incoming collaboration without pushing: "+o.id),void this._storageService.deleteCompositeDirectory(o,n);if(!o.current||o.current.isBound){if(this._isACP)return this._storageService.discardComposite(o,n);this._services.log("Pushing deleted composite: "+o.id),this.pushLibrary(e,i,t=>{if(t){if(t.code===r.UNEXPECTED_RESPONSE&&t.response&&404===t.response.statusCode)return void this._storageService.deleteCompositeDirectory(o,n);if(t.code===r.UPDATE_CONFLICT){var i=t;return void this.pullLibrary(e,e=>{e&&e.code===r.NO_COMPOSITE?this._storageService.deleteCompositeDirectory(o,n):e&&e.code===r.DELETED_COMPOSITE?n(null):n(e||i)})}}n(t)})}else n(null)}getStorageHost(){return`https://${this._storageHost}`}getPlatformHost(){return this._platformHost&&`https://${this._platformHost}`}getElementRefDomain(){return this._requiresCommunitySession?this._config.CP_CLOUD_ID:this._storageHost}getElementRefPath(){return this._config.STORAGE_ASSETS_PATH+this._config.LIBRARY_SYNC_GROUP}getElementRefDomainPath(){return this.getElementRefDomain()+this.getElementRefPath()}getCollaborationHost(){return"https://"+this._collaborationHost}getContentURL(e){return this._storageService.getComponentHref(e,e.version)}getContent(e,t,i){this._storageService.getAssetAsType(this.getContentURL(e),t,{},(e,t)=>e?i(e):i(null,t))}appendAccessTokenToURL(e,t){if(e){var i=this._apiKey;this._getAuthToken((n,o)=>{t(null,e+="?api_key="+i+(o?"&user_token="+o:""))})}else t(null,void 0)}updateAccessToken(e){this._setAuthToken(e)}isLoggedIn(){return this._isPublic||this._httpServices[0].isActive}uploadNewComponentForRepresentation(e,t,i,o){var r=i._element._library._dcxComposite;n.uploadNewComponent(e,i.type,r,i.id,this._storageService,(e,n)=>{if(e)return void o(e);const s=t?t.lastIndexOf("."):-1,a=-1!==s&&t.substr(s+1).toLowerCase(),c=i.id+"."+a,l=i._parent?i._parent._dcxNode:i._element._dcxNode,h=r.current.addComponentWithUploadResults(t,i.relationship,c,l,n);o(null,h)})}uploadNewComponentForLibrary(e,t,i,o,r,s){var a=r._dcxComposite;n.uploadNewComponent(e,i,a,t,this._storageService,(e,n)=>{if(e)s(e);else{var r=c.getExtensions(i)[0],l=t+"."+r,h=a.current.addComponentWithUploadResults(l,o,l,a,n);s(null,h)}})}pushClientTokenInfo(e,t){const i=`https://${this._ccLibraryHost}/api/v1/client-tokens/${e}`,n={token:JSON.stringify(t),ttl:300};return this._doJSONRequest("POST",i,n).then(({statusCode:e})=>201===e,()=>!1)}getBookmarks(){const e=`https://${this._ccLibraryHost}/api/v1/libraries/bookmarks`;return this._doJSONRequest("GET",e).then(({statusCode:e,response:t})=>{if(404!==e)return 200!==e?Promise.reject(new s(s.TRANSFER_ERROR,`Unexpected response getting bookmarks: ${e}`)):t})}createBookmarks(e){const t=`https://${this._ccLibraryHost}/api/v1/libraries/bookmarks`;return this._doJSONRequest("POST",t,e).then(({statusCode:e,response:t})=>201!==e?Promise.reject(new s(s.TRANSFER_ERROR,`Unexpected response creating bookmarks: ${e}`)):t)}removeBookmark(e){const t=`https://${this._ccLibraryHost}/api/v1/libraries/bookmarks/${e}`;return this._doJSONRequest("DELETE",t).then(({statusCode:e})=>{if(![200,204,404].includes(e))return Promise.reject(new s(s.TRANSFER_ERROR,`Unexpected response deleting bookmark: ${e}`))})}removeCollaborators(e){if("incoming"===e.collaboration||!e.collection.isPrivate)return Promise.resolve();const t=e._dcxComposite.href&&encodeURIComponent(e._dcxComposite.href),i=`https://${this._invitationsHost}/api/v3/share/${t}`;return this._doJSONRequest("GET",i).then(({response:e,statusCode:t})=>[200,204,404].includes(t)?this._doJSONRequest("PATCH",i,{collaborators:e.collaborators.map(({id:e})=>({id:e,action:"remove"})),invitations:e.invitations.map(({id:e})=>({id:e,action:"remove"}))}).then(({statusCode:e})=>{if(![200,204,404].includes(e))return Promise.reject(e)}):Promise.reject(t)).catch(e=>Promise.reject(new s(s.TRANSFER_ERROR,`Unexpected response removing collaborators: ${e}`)))}}},function(e,t,i){const n=i(25),o=i(2);e.exports=class{constructor(e){this._syncManager=e}get _config(){return this._syncManager._config}get _services(){return this._syncManager._services}_getStorageSession(e){return this._syncManager._getStorageSession(e)}download(e,t,i,r,s,a=0){this._services.log("download external link: "+e);var c=this._getStorageSession(e),l=i+this._services.getPathSeparator()+this._services.uuid(),h=new n.FileContent(l);t=t||{},this._services.fileUtils.ensurePathExists(i,n=>{if(n)s(n);else{var d=c.getAssetAsType(e,h,t,(n,c,h,_)=>{if(d&&delete d.progress,n&&n.code===o.UNEXPECTED_RESPONSE){var p=n.response&&n.response.statusCode;if(this._services.log("download external link: Unexpected Response "+p+" from "+e),this._config.isRedirect(p)){var u=this._config.getLocationHeader(n.response.headers);if(u&&a<this._config.MAX_REDIRECT_FOLLOW)return this._services.log("download external link: Redirecting to "+u),void this.download(u,t,i,r,s,a+1);n.response.statusCode=404}}s(n,l,h,_)});if(d&&r){var _,p=0;d.progress=e=>{p+=e,!_&&d.response&&d.response.headers&&(_=this._config.getContentLengthHeader(d.response.headers)),r(p,_||1)},r(0,1)}}})}test(e,t,i=0){this._getStorageSession(e).headRequest(e,(n,o)=>{var r=o?o.statusCode:n;if(this._services.log("test external link: "+e+" -> "+r),o&&this._config.isRedirect(o.statusCode)){var s=this._config.getLocationHeader(o.headers);if(s&&i<this._config.MAX_HEAD_REDIRECT_FOLLOW)return this._services.log("test external link: Redirecting to "+s),void this.test(s,t,i+1);i>0&&(o.statusCode=404)}t(n,o)})}}},function(e,t,i){const n=i(25),o=i(6);e.exports=class{constructor(e,t){this._syncManager=e,this._imageHost=t.CC_IMAGE_HOSTNAME,this._imageXHost=t.CC_IMAGE_X_HOSTNAME,this._renditionStorageService=this._getStorageSession(e.getStorageHost()),this._requiresCommunitySession=t.REQUIRES_COMMUNITY_SESSION}get _config(){return this._syncManager._config}get _services(){return this._syncManager._services}_getStorageSession(e){return this._syncManager._getStorageSession(e)}_downloadRendition(e,t,i,r,s,a=0){if(e.isDeletedLocally||e.element.library.isDeletedFromServer)s("Error: representation deleted");else{var c=n=>this._downloadRendition(e,t,i,r,s,n);if(a>0&&"uploading"===e.element.library.syncState)setTimeout(()=>c(a),this._config.RENDITION_RETRY_INTERVAL);else{var l=i+this._services.getPathSeparator()+this._services.uuid()+".png",h=new n.FileContent(l);this._renditionStorageService.getAssetAsType(t,h,r,t=>{var i=t&&t.response&&t.response.headers,n=()=>s(t,l);if(404===o.getErrorStatusCode(t))return this._retry404IfNeeded(e,i,a,c,n);n()})}}}_retry404IfNeeded(e,t,i,n,o){var r=1e3*this._config.getRetryAfterHeader(t);if(this._config.RENDITION_RETRY_INTERVAL=Math.max(this._config.DEFAULT_RENDITION_RETRY_INTERVAL,r),this._config.RENDITION_404_BACKOFF=Math.max(this._config.DEFAULT_RENDITION_404_BACKOFF,r),i<this._config.RENDITION_MAX_RETRIES)return i++,this._services.log("404 fetching rendition: retrying ("+i+")"),void setTimeout(()=>n(i),this._config.RENDITION_RETRY_INTERVAL);this._services.log("404 fetching rendition: reached maximum retries"),this._services.log("Backing off rendition fetch of "+e.id+" for "+this._config.RENDITION_404_BACKOFF+"ms"),e._lastRendition404=Date.now(),o()}_getImageServiceSVGRendition(e,t,i){var n=e.element,o="https://"+this._imageHost+"/createagc",r=this._getStorageSession(o),s={"Content-Type":"application/vnd.adobe.image-operation+json"},a={inputs:{application_file:{href:n.getReference()}},outputs:{agc:{disposition:"location"}}};if(e.isDeletedLocally||e.element.library.isDeletedFromServer)i("Error: representation deleted");else{var c=t=>this._getImageServiceSVGRendition(e,t,i);r._service.invoke("POST",o,s,JSON.stringify(a),{responseType:"text"},(l,h)=>{if(l||200!==h.statusCode){var d=function(){return i(l||"Image service call failed with: "+h.statusCode)};return h&&404===h.statusCode?this._retry404IfNeeded(e,h&&h.headers,t,c,d):void d()}var _;try{_=JSON.parse(h.response)}catch(e){return i(e)}if(_&&_.outputs&&_.outputs.agc&&_.outputs.agc.location)return o="https://"+this._imageXHost+"/agctosvg",r=this._getStorageSession(o),s={"Content-Type":"application/vnd.adobe.dwbedrockservice-operation+json"},a={inputs:{href:_.outputs.agc.location}},r._service.invoke("POST",o,s,JSON.stringify(a),{responseType:"text"},(e,t)=>{if(e||200!==t.statusCode)return i(e||"Image-x service call failed with: "+t.statusCode);var o=t.response,r=n.library.collection._getTempDir(),s=r+this._services.getPathSeparator()+this._services.uuid()+".svg";this._services.fileUtils.ensurePathExists(r,e=>{if(e)return i(e);this._services.fs.writeFile(s,o,e=>e?i(e):i(null,s))})});i("Invalid image service response")})}}getURL(e,t,i,n=0){if(e._dcxComponent)try{var r;r=this._requiresCommunitySession?this._renditionStorageService.getComponentRenditionHref(e._dcxComponent,e._dcxComponent.version,"image/png","width",t||"full"):this._renditionStorageService.getComponentRenditionHref(e._dcxComponent,e._dcxComponent.version,t||"full"),Promise.resolve(r).then(e=>i(null,e),r=>{if(404===o.getErrorStatusCode(r)){const o=n=>this.getURL(e,t,i,n),s=()=>i(r);return this._retry404IfNeeded(e,r.response.headers,n,o,s)}i(r)})}catch(e){i(e)}else i("representation must be a component to generate a rendition")}download(e,t,i){if(e.element.library.isDeletedFromServer)return this._services.log("Error: Trying to fetch rendition from deleted library."),void i("Error: library deleted");if(Date.now()-(e._lastRendition404||0)<this._config.RENDITION_404_BACKOFF)i("Error: got 404 on last rendition attempt - backing off");else if("vector"===t&&e.element.supportsVectorThumbnail()){const t=()=>{"uploading"!==e.element.library.syncState?this._getImageServiceSVGRendition(e,0,i):setTimeout(t,this._config.RENDITION_RETRY_INTERVAL)};t()}else this.getURL(e,t,(t,n)=>{if(t)i(t);else{var o={Accept:"image/png"},r=e.element.library.collection._getTempDir();this._services.fileUtils.ensurePathExists(r,t=>{t?i(t):this._downloadRendition(e,n,r,o,i)})}})}}},function(e,t){e.exports=class{constructor(e,t){this._syncManager=e,this._typekitHost=t.TYPEKIT_HOSTNAME}_getStorageSession(e){return this._syncManager._getStorageSession(e)}getFontData(e,t){var i="https://"+this._typekitHost+"/v1/variations?include=trial,full,marketplace,purchased&include_marketplace_data=true&purpose=sync";this._getStorageSession(i)._service.invoke("POST",i,null,JSON.stringify(e),{responseType:"text"},(e,i)=>{if(e||200!==i.statusCode)return t(e||"Typekit service call failed with: "+i.statusCode);try{t(null,JSON.parse(i.response))}catch(e){t(e)}})}}},function(e,t,i){const n=i(3);e.exports=class{constructor(e,t,i,o,r){this._listenerManager=new n(["progress"],e=>this._collection._services.log(e)),this._collection=e,this._id=t,this._type=i,this._data=o,this._cancelCallback=r,this._progress=0}get _config(){return this._collection._config}get _storageInterface(){return this._collection._storageInterface}_updateProgress(e){this._progress!==e&&(this._progress=e,this._listenerManager.notify("progress",[this]),this._collection._notifyOperationChange())}get id(){return this._id}get type(){return this._type}get data(){return this._data}get progress(){return this._progress}addProgressListener(e){this._listenerManager.add("progress",e)}removeProgressListener(e){this._listenerManager.remove("progress",e)}cancel(){this._config.SHARED_LOCAL_STORAGE?this._storageInterface.cancelOperation(this._collection,this._id):this._cancelCallback&&this._cancelCallback()}}},function(e,t,i){const n=i(59);e.exports=class extends n{constructor(e,t){super("public",e),this._url=t}toJSON(){return super.toJSON({url:this._url})}get url(){return this._url}isReferenceTo(e){return this.url===e._dcxComposite.href}}},function(e,t,i){const n=i(59);e.exports=class extends n{constructor(e,t,i,n){super("team",e,n),this._urn=t,this._teamUrn=i,this._orgId=n}toJSON(){return super.toJSON({urn:this._urn,team_urn:this._teamUrn,org_id:this._orgId})}get urn(){return this._urn}get teamUrn(){return this._teamUrn}get orgId(){return this._orgId}isReferenceTo(e){return e.id===this.id}}},function(e,t,i){const n=i(1),o=i(3);e.exports=class{constructor(e){this._collection=e,this._listenerManager=new o(["change"],e=>this._services.log(e)),this._fontsCache={}}get _config(){return this._collection._config}get _services(){return this._collection._services}get _storageInterface(){return this._collection._storageInterface}_clearCache(){this._fontsCache={},this._listenerManager.notify("change")}addChangeListener(e){this._listenerManager.add("change",e)}removeChangeListener(e){this._listenerManager.remove("change",e)}getFontData(e,t){const i=this._fontsCache[e];i?t(null,i):this._config.SHARED_LOCAL_STORAGE?this._storageInterface.getFontData(this._collection,e,(i,n)=>{n&&(this._fontsCache[e]=n),t(i,n)}):this._collection._syncManager.typekit.getFontData([e],(i,o)=>{if(i)return void t(new n(n.NETWORK_ERROR,"Error occurred while getting font data",null,i));const r=o&&o[0];this._fontsCache[e]=r,t(null,r)})}isSystemFontAvailable(e,t,i){if(!this._config.SHARED_LOCAL_STORAGE)return i(new n(n.NOT_SUPPORTED,"isSystemFontAvailable() is only supported with shared local storage"));this._storageInterface.isFontAvailable(e,t,i)}}},function(e,t,i){const n=i(1),o=i(23),r=i(6),s=i(58),a=i(8).promisify,c={};class l extends s{static connect(e){const t=e.userId,i=c[t]=c[t]||new l(e._apiRoot,t);return i._connect(e),i}static disconnect(e){const t=e.userId;c[t]&&c[t]._disconnect(e)}constructor(e,t){const i=e._services.fileUtils.getUserDir(t)+e._services.getPathSeparator()+"links";super(e,i),this._userId=t,this._collections=[],this._pendingDownloads={},this._pendingTests={},this._referencedLinks={},this._sentNotifications={},this._sharedStorage={downloadExternalLink:e=>a(this._storageInterface.downloadExternalLink.bind(this._storageInterface))(e),testExternalLink:e=>a(this._storageInterface.testExternalLink.bind(this._storageInterface))(e)}}getCachedPath(e){const t=this._getCacheEntry(e);return this._isPath(t)?t:void 0}getCachedError(e){const t=this._config.validateURL(e.getContentURL(),this._privateCollection);if(t)return t;const i=this._getCacheEntry(e);return this._isErrorCode(i)?new n(i,"Broken link, or access denied"):null}getExternalLink(e,t=!1){const i=e.getContentURL(),o=this._config.validateURL(i,this._privateCollection);if(o)return Promise.reject(o);if(t)e.element.library._renditionCache._legacyClearCacheEntry(e),this._setCacheEntry(["urls",i]);else{const t=this._getCacheEntry(e);if(this._isPath(t))return Promise.resolve(t);if(this._isErrorCode(t))return Promise.reject(new n(t,"Broken link, or access denied"))}if(this._config.SHARED_LOCAL_STORAGE)return this._sharedStorage.downloadExternalLink(e);if(!this._pendingDownloads[i]){const t=()=>{this._notifyDownloadFinished(this._pendingDownloads[i]);const t=e.element;t.supportsVectorThumbnail()&&t.library._renditionCache._clearCache(t,"vector"),delete this._pendingDownloads[i]};this._pendingDownloads[i]={promise:this._doGetExternalLink(e),representations:[]},this._pendingDownloads[i].promise.then(t,t)}return this._pendingDownloads[i].representations.push(e),this._pendingDownloads[i].promise}testExternalLink(e,t=!1){const i=e.getContentURL();if(this._config.validateURL(i,this._privateCollection))return Promise.reject();if(t)e.element.library._renditionCache._legacyClearCacheEntry(e),this._setCacheEntry(["urls",i]);else{const t=this._getCacheEntry(e);if(t)return this._isErrorCode(t)?Promise.reject():Promise.resolve()}if(this._config.SHARED_LOCAL_STORAGE&&this._privateCollection._storageInterface.supportsTestExternalLink())return this._sharedStorage.testExternalLink(e);if(!this._pendingTests[i]){const e=this._getOnDownloadProgressCallback("_pendingTests",i),t=()=>{this._notifyDownloadFinished(this._pendingTests[i]),e(),delete this._pendingTests[i]};this._pendingTests[i]={promise:this._doTest(i),representations:[]},e(0,1),this._pendingTests[i].promise.then(t,t)}return this._pendingTests[i].representations.push(e),this._pendingTests[i].promise}ensureExternalLinkCache(e,t){const i=this._getCache(["urls",e]);return this._getFilePath(i)?Promise.resolve():this._doTransaction(()=>this._setCache(["urls",e],t))}gc(){const e={};this._collections.forEach(t=>{t.libraries.forEach(t=>{Object.assign(e,this._getReferences(t))})});const t=this._cache.urls||{};let i=!1;return Object.keys(t).forEach(t=>{e[t]||(this._setCacheEntry(["urls",t]),i=!0)}),i?this.save():Promise.resolve()}get _privateCollection(){return this._collections.find(e=>e.isPrivate)}_connect(e){this._collections.push(e),e._externalLinkCache=this}_disconnect(e){const t=this._collections.indexOf(e);-1!==t&&this._collections.splice(t,1),0===this._collections.length&&delete c[this._userId]}_getCacheEntry(e){const t=e.element.library._renditionCache._legacyGetCacheEntry(e);if(t)return t;const i=e.getContentURL(),n=this._getCache(["urls",i]);return this._getFilePath(n,!0)}_doGetExternalLink(e){const t=e.getContentURL(),i=e._getLinkLocalPaths().find(e=>this._fs.statSync(e));return i?this._doTransaction(()=>this._setCache(["urls",t],i)):this._doDownload(t,e.type)}_doDownload(e,t){const i=this._getOnDownloadProgressCallback("_pendingDownloads",e),s=this._privateCollection._getTempDir();return this._downloadURL(this._privateCollection,e,s,i).then(({tempFilePath:n,response:r})=>{var s=this._config.getContentTypeHeader(r&&r.headers)||t,a=n+"."+(o.getExtensions(s)[0]||"data");const c=this._fs.rename(n,a).then(()=>this._doTransaction(()=>this._setCache(["urls",e],a,!0)));return c.then(i,i),c}).catch(t=>{let o;var s=t&&t.response&&t.response.statusCode;return this._config.isUnrecoverableClientError(s)?(this._setCacheEntry(["urls",e],n.RENDITION_NOT_AVAILABLE),o=this.save().then(()=>Promise.reject(new n(n.RENDITION_NOT_AVAILABLE,"Broken link, or access denied")))):o=Promise.reject(r.getSyncError(t)),o.catch(()=>i(void 0,void 0,t)),o})}_doTest(e){return this._testURL(this._privateCollection,e).then(t=>{const i=t&&t.statusCode;let o;return this._config.isUnrecoverableClientError(i)?o=n.RENDITION_NOT_AVAILABLE:i&&i>=200&&i<400&&(o=this._config.RENDITION_CACHE_PLACEHOLDER),o?(this._setCacheEntry(["urls",e],o),this.save().then(()=>this._isErrorCode(o)?Promise.reject():Promise.resolve())):Promise.resolve()})}_getOnDownloadProgressCallback(e,t){return(i,n,o)=>{const r=this[e]&&this[e][t]&&this[e][t].representations;r&&r.forEach(e=>{e.element.library.collection._updateExternalLinkDownloadProgress(e,i,n,o)})}}_notifyDownloadFinished(e){e.representations.forEach(e=>this._notifyDownloadRendition(e,!0))}_notifyDownloadRendition(e,t){const i=`${e.element.library.id}.${e.element.id}.${e.id}`;!0!==t&&this._sentNotifications[i]||(this._sentNotifications[i]=!0,!1!==t&&this._storageInterface.notifyDownloadRendition(e.element))}_getReferences(e){if(this._referencedLinks[e.id]=this._referencedLinks[e.id]||{},this._referencedLinks[e.id].modified!==e.modified){this._referencedLinks[e.id].modified=e.modified,this._referencedLinks[e.id].urlMap={};const t=t=>{t._shouldGCLocalData()||t._forEachRepresentation(t=>{const i=t.isExternalLink&&t.getContentURL();i&&(this._referencedLinks[e.id].urlMap[i]=!0)})};e.elements.forEach(t),e.removedElements.forEach(t)}return this._referencedLinks[e.id].urlMap}_downloadURL(e,t,i,n){return new Promise((o,r)=>{const s=Date.now();this._services.log("Downloading from external URL: "+t),e._syncManager.links.download(t,{},i,n,(e,t,i,n)=>{this._services.log("Finished downloading from external URL: "+(Date.now()-s)+"ms"),e?r(e):o({tempFilePath:t,etag:i,response:n})})})}_testURL(e,t){return new Promise(i=>{const n=Date.now();this._services.log("HEAD request of external URL: "+t),this._storageInterface.testURL(e,t,(e,t)=>{this._services.log("Finished HEAD request of external URL: "+(Date.now()-n)+"ms"),i(t)})})}}e.exports=l},function(e,t,i){const n=i(3);e.exports=class{constructor(e){this._apiRoot=e,this._collections=[],this._listenerManager=new n(["change"],e=>this._services.log(e))}get _services(){return this._apiRoot._services}getLibraryCollection(e,t){return this._collections.find(i=>i.isPrivate&&i.userId===e&&i.cloudId===t)}getPublicLibraryCollection(e){return this._collections.find(t=>t.isPublic&&t.cloudId===e)}getTeamLibraryCollection(e){return this._collections.find(t=>t.isTeam&&t.platformDirectoryId===e)}addLibraryCollection(e){this._collections.push(e),this._listenerManager.notify("change")}removeLibraryCollection(e){e._dispose();var t=this._collections.indexOf(e);-1!==t&&(this._collections.splice(t,1),this._listenerManager.notify("change"))}removeAllLibraryCollections(){this._collections.forEach(e=>e._dispose()),this._collections=[],this._listenerManager.notify("change")}getLoadedCollections(){return this._collections}addLoadedCollectionsListener(e){this._listenerManager.add("change",e)}removeLoadedCollectionsListener(e){this._listenerManager.remove("change",e)}}},function(e,t,i){const n=i(8),o="undefined"!==typeof LOCALE_ROOT,r={photoshop:"LIBS_TOOLKIT_NAME_PHOTOSHOP",photoshop_swatches:"LIBS_TOOLKIT_NAME_PHOTOSHOP_SWATCHES",photoshop_brushes:"LIBS_TOOLKIT_NAME_PHOTOSHOP_BRUSHES",photoshop_gradients:"LIBS_TOOLKIT_NAME_PHOTOSHOP_GRADIENTS",photoshop_patterns:"LIBS_TOOLKIT_NAME_PHOTOSHOP_PATTERNS",photoshop_styles:"LIBS_TOOLKIT_NAME_PHOTOSHOP_STYLES",photoshop_shapes:"LIBS_TOOLKIT_NAME_PHOTOSHOP_SHAPES"};e.exports=class{constructor(e,t){this._apiRoot=e,this._localeData={},this._services.hasFileSystem()&&o||(this._localeData={cs_CZ:i(141),da_DK:i(142),de_DE:i(143),en_US:i(144),es_ES:i(145),es_MX:i(146),fi_FI:i(147),fr_CA:i(148),fr_FR:i(149),fr_MA:i(150),hu_HU:i(151),it_IT:i(152),ja_JP:i(153),ko_KR:i(154),nb_NO:i(155),nl_NL:i(156),pl_PL:i(157),pt_BR:i(158),ru_RU:i(159),sv_SE:i(160),tr_TR:i(161),uk_UA:i(162),zh_CN:i(163),zh_TW:i(164)}),this.setLocale(t)}get _services(){return this._apiRoot._services}_getLocaleData(e){if(!this._localeData[e]&&this._services.hasFileSystem()&&o)try{this._localeData[e]=this._services.fs.readFileSync(`${LOCALE_ROOT}${e}/messages.properties`,"utf8")}catch(e){}return this._localeData[e]||""}_normaliseLocale(e){const t=(e=e.replace("-","_")).split("_");return t[0]=t[0]&&t[0].toLowerCase(),t[1]=t[1]&&t[1].toUpperCase(),t.join("_")}setLocale(e=""){e=this._normaliseLocale(e),this._getLocaleData(e)||(e="en_US"),this._locale=e,this._strings=n.parseLocalisationFile(this._getLocaleData(e))}getLocale(){return this._locale}translate(e,t){let i=this._strings[e];return i&&t&&(i=n.constructStringFromTemplate(i,t)),i||e}getToolkitName(e){return this.translate(r[e]||"LIBS_TOOLKIT_NAME_DEFAULT")}}},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,i){const n=i(26),o=i(27),r=i(54),s=i(61),a=i(62),c=i(37),l=i(1),h=i(63),d=i(166),_=i(167),p=i(10),u=i(8).promisify,m=({isTeam:e,isPublic:t,userId:i,cloudId:n,platformDirectoryId:o})=>({isTeam:e,isPublic:t,userId:i,cloudId:n,platformDirectoryId:o}),g=(e,t)=>Object.assign(m(e.collection),{[t||"id"]:e.id}),f=(e,t,i)=>Object.assign(g(e.library,i),{[t||"element"]:e.id}),E=e=>Object.assign(f(e.element),{representation:e.id}),y=["bmp","cur","gif","ico","jpeg","jpg","png","psd","tiff","tif","webp","svg","dds"];e.exports=class{constructor(e,t={}){this._apiRoot=e,this._acceptPushedBranchListeners=[],this._downloadRenditionListeners=[],this._rootListeners=[],this._baseBranches={},this._portDiagnosis="UNKNOWN",this._logIndex=0,this._connectedCallback=t.onConnected||(()=>{}),this._config.SHARED_LOCAL_STORAGE&&(this._connect(),this.fs=new _(this),this._services.hasFileSystem()||this._services.setFileSystem(this.fs))}get _collectionManager(){return this._apiRoot._collectionManager}get _services(){return this._apiRoot._services}get _config(){return this._apiRoot._config}_getBase(e){const t=this._baseBranches[e];return t&&t.base}_setBase(e,t){this._baseBranches[e]=this._baseBranches[e]||{},this._baseBranches[e].base=t}_getLogIndex(){return this._logIndex++}_getServicePort(e){const t=this._config.VULCAN_PREFIX+this._config.VULCAN_QUERY_REQUEST,i=this._config.VULCAN_PREFIX+this._config.VULCAN_QUERY_RESPONSE,n=t=>{let i;try{i=JSON.parse(t)}catch(e){}i?e(null,i):e("NO_DATA")};if(this._services.vulcanCall)this._services.vulcanCall(t,"",i,n);else if(this._services.hasCEPVulcan()){const o=this._services.getVulcanInterface(),r=this._services.getVulcanMessage();let s;const a=t=>{o.removeMessageListener(i,a),clearTimeout(s),t?n(o.getPayload(t)):e("NO_VULCAN_MESSAGE")};o.addMessageListener(i,a),s=setTimeout(a,this._config.VULCAN_QUERY_TIMEOUT);const c=new r(t);c.setPayload(""),o.dispatchMessage(c)}}_connectToPort(e,t){const i=t&&t.port,n=t&&t.token,o=t&&t.domain;if(this._portDiagnosis=t?t.portdiagnosis:"UNKNOWN",this._connectionPort=i,!this._channel){if(!i||"SIMPLE_HOSTNAME_GOING_TO_PROXY"===this._portDiagnosis)return this._onConnect(e);try{const e=e=>this._services.log(e),t=new d(i,n,o,this._config.SHARED_LOCAL_STORAGE_VERSION,e);this._channel=new h(this._apiRoot,t),this._channel.setLogCallback(e)}catch(e){return this._onConnect(e)}this._channel.addListener("environmentinfo",this._onEnvironmentInfo.bind(this)),this._channel.addListener("collectionadded",this._onCollectionAdded.bind(this)),this._channel.addListener("collectionremoved",this._onCollectionRemoved.bind(this)),this._channel.addListener("clearcollections",this._onClearCollections.bind(this)),this._channel.addListener("syncstate",this._onSyncState.bind(this)),this._channel.addListener("librarychange",this._onLibraryChange.bind(this)),this._channel.addListener("renditioncachechange",this._onRenditionCacheChange.bind(this)),this._channel.addListener("librarydeleted",this._onLibraryDeleted.bind(this)),this._channel.addListener("bookmarkschanged",this._onBookmarksChanged.bind(this)),this._channel.addListener("fontcachechanged",this._onFontCacheChanged.bind(this)),this._channel.addListener("operationschanged",this._onOperationsChanged.bind(this)),this._channel.onOpen(()=>{this._services.log("Websocket opened"),this._isConnected=!0,this._sendConfiguration(),this._onConnect()}),this._channel.onClose(()=>{this._services.log("Websocket closed"),this._onDisconnect()}),this._channel.onError(e=>{this._services.log(`Websocket error: ${e}`),this._onDisconnect()})}}_connect(){this._getServicePort(this._connectToPort.bind(this))}_onConnect(e){!this._channel||e?this._connectedCallback(new l(l.CLIENT_CONNECTION_ERROR,"Error creating message channel",e)):this._connectedCallback()}_onDisconnect(){this._channel&&(this._channel.shutdown(),this._channel=void 0),this._isConnected=!1,this._collectionManager.removeAllLibraryCollections()}_sendConfiguration(){this._channel.send("configure",{CLIENT_DESCRIPTION:this._config.CLIENT_DESCRIPTION,RENDITION_SIZES:this._config.RENDITION_SIZES,FULL_RENDITION_CONFIG:this._config.FULL_RENDITION_CONFIG,LOCAL_SETTINGS:this._config.LOCAL_SETTINGS})}_onEnvironmentInfo(e){const t=!this._serviceInfo||!this._serviceInfo.syncingEnabled;this._serviceInfo=e,e.whitelistedDomains&&(this._config.WHITELISTED_DOMAINS=e.whitelistedDomains),e.elementActionProductMap&&this._config.updateElementActionMap(this._getServiceVersion(),e.elementActionProductMap),e.deviceId&&(this._config.DEVICE_ID=e.deviceId),e.deviceDescription&&(this._config.DEVICE_DESCRIPTION=e.deviceDescription),e.maxElements&&(this._config.MAX_ELEMENTS=e.maxElements),e.maxRemovedElements&&(this._config.MAX_REMOVED_ELEMENTS=e.maxRemovedElements),e.maxComponentSize&&(this._config.MAX_COMPONENT_SIZE=e.maxComponentSize),e.localSettings&&(this._config.LOCAL_SETTINGS=e.localSettings),e.shaCache&&(this._config.SHA_CACHE=e.shaCache),e.defaultContentLocations&&(this._config.DEFAULT_CONTENT_LOCATIONS=e.defaultContentLocations),e.analyticsEnabled&&(this._config.ANALYTICS_ENABLED=e.analyticsEnabled),this._collectionManager._collections.forEach(i=>{e.syncingEnabled&&t&&(i._syncState="ok"),i._listenerManager.notify("sync")}),this._config._listenerManager.notify("change")}_onCollectionAdded(e){this._config.ROOT_DIR=e.rootDir;const t={USER_ID:e.userId,CLOUD_ID:e.cloudId,CLOUD_INFO:e.cloudInfo,TEAM:e.team,STORAGE_HOSTNAME:e.storageHost,CC_LIBRARY_SERVICE_HOSTNAME:e.cclibsHost,CC_IMAGE_HOSTNAME:e.imageHost,CC_IMAGE_X_HOSTNAME:e.imageXHost,TYPEKIT_HOSTNAME:e.typekitHost,REQUIRES_COMMUNITY_SESSION:e.requiresCommunitySession},i=this._collectionManager.getLoadedCollections().find(t=>t.isPrivate&&t.userId===e.userId);let n;n=e.isPublic?new a(this._apiRoot,t,i):e.isTeam?new s(this._apiRoot,t,i):new r(this._apiRoot,t);const o=u(this.loadExistingLibrary.bind(this));Promise.all(e.libraries.map(e=>o(n,e.id,e.path,e.manifest,e.deletedFromServer,e.renditionCache))).then(()=>this._collectionManager.addLibraryCollection(n))}_getLibraryCollection(e){return e.isPublic?this._collectionManager.getPublicLibraryCollection(e.cloudId):e.isTeam?this._collectionManager.getTeamLibraryCollection(e.platformDirectoryId):this._collectionManager.getLibraryCollection(e.userId,e.cloudId)}_onCollectionRemoved(e){const t=this._getLibraryCollection(e);t&&this._collectionManager.removeLibraryCollection(t)}_onClearCollections(){this._collectionManager.removeAllLibraryCollections()}_onSyncState(e){const t=this._getLibraryCollection(e);t&&(t._syncState=e.state,t._syncProgress=e.progress,t._syncProgressMap=e.progressMap,t._externalLinkDownloadProgressMap=e.externalLinkDownloadProgressMap||{},t._newLibraryProgress=e.newLibraryProgress,t._initialSyncInProgress=e.initialSyncInProgress,t._syncErrors=[],e.errors.forEach(e=>{t._syncErrors.push(new l(e.code,e.message,e.libraryId))}),e.libraryStates.forEach(e=>{const i=t.getLibraryById(e.id);i&&(i._syncState=e.state)}),t._listenerManager.notify("sync"))}_onLibraryChange(e){const t=this._getLibraryCollection(e);if(!t)return;const i=t.getLibraryById(e.id);i?(this._services.log("onLibraryChange: "+i.id),i._deletedFromServer!==e.deletedFromServer&&(i._deletedFromServer=e.deletedFromServer,i._notifyChange()),e.renditionCache=e.renditionCache||{},i._renditionCache.replaceCache(e.renditionCache),this.updateExistingLibrary(t,i,e.manifest,void 0,this._getBase(i.id),()=>{i._renditionCache.replaceCache(e.renditionCache)})):this.loadExistingLibrary(t,e.id,e.path,e.manifest,e.deletedFromServer,e.renditionCache)}_onRenditionCacheChange(e){const t=this._getLibraryCollection(e),i=t&&t.getLibraryById(e.id),n=i&&i.getElementById(e.elementId);n&&e.renditionCache&&(i._renditionCache.replaceElementCache(n,e.renditionCache),n._listenerManager.notify("change"))}_onOperationsChanged(e){const t=this._getLibraryCollection(e),i=e.operations,n={};i.forEach(e=>{t._updateOperation(e.id,e.type,e.data,e.progress),n[e.id]=!0}),Object.keys(t._operationIdMap).forEach(e=>{n[e]||t._delayedRemoveOperation(t._operationIdMap[e])})}_onLibraryDeleted(e){const t=this._getLibraryCollection(e),i=t&&t.getLibraryById(e.id);if(!i)return;this._services.log("deleteLibrary");const n=t._libraries.indexOf(i);-1!==n&&(t._libraries.splice(n,1),delete t._libraryIdMap[i.id]),i._markDeletedLocally(!0),t._notifyChange(!0)}_onBookmarksChanged(e){const t=this._getLibraryCollection(e);t&&e.bookmarks&&t._bookmarkManager._deserialize(e.bookmarks)}_onFontCacheChanged(e){const t=this._getLibraryCollection(e);t&&t.fontManager&&t.fontManager._clearCache()}_loadBranch(e,t,i){try{const n=new o(void 0,i).parse(t);return n._localStorage=e._localStorage,n}catch(e){}}_addLibrary(e,t,i,o,r){i=i||e._getCompositeDir(t);const s=new n(null,null,i,null,null,{preserveFileExtensions:!0}),a=this._loadBranch(s,o,!1);if(!a)return void r(new l(l.CORRUPTED_LIBRARY,"Library corrupted in local storage",t));if("pendingDelete"===a.compositeState||"pendingDiscard"===a.compositeState)return void r(null);s._current=a,this._setBase(t,o);const h=new c(e,s,e.isPublic&&t);e._libraries.push(h),e._libraryIdMap[h.id]=h,e._notifyChange(!0),r(null,h)}isConnected(){return this._isConnected}reconnect(){this._channel||this._connect()}shutdown(){this._onDisconnect()}getServiceInfo(){return this._serviceInfo?{updateRequired:this._serviceInfo.updateRequired,version:this._serviceInfo.codeVersion,buildNumber:this._serviceInfo.buildNumber,apiVersion:this._serviceInfo.version,environment:this._serviceInfo.environment,syncingEnabled:this._serviceInfo.syncingEnabled,portDiagnosis:this._portDiagnosis,connectionPort:this._connectionPort}:{portDiagnosis:this._portDiagnosis,connectionPort:this._connectionPort}}updateConfiguration(){this._config.SHARED_LOCAL_STORAGE&&this._channel&&this._isConnected&&this._sendConfiguration()}sync(e){this._channel.send("sync",m(e))}setSyncEnabled(e){this._channel.send("configuresync",{enable:e})}commitManifest(e,t){if(!this._config.SHARED_LOCAL_STORAGE)return void e._dcxLock.obtain(()=>{e._gcLocalData(()=>{e._dcxComposite.commitChanges(i=>{e._dcxLock.release(),e._renditionCache.gc(),t(i,!0)})})});const i=e._dcxBranch.localData,n=e._renditionCache.doRequestSetCache(),o=g(e);o.current=i,o.base=this._getBase(e.id),o.renditions=n.data,this._services.log("Start commit"),this._channel.call("commit",o,r=>{if(this._services.log("Finish commit: "+(r.success?"success":"fail")),r.success){if(this._services.log("Update base after commit"),this._setBase(e.id,i),r.renditions){n.complete(r.renditions).forEach(e=>e._listenerManager.notify("change"))}}else n.cancel(),e._waitForCommit(()=>{this.notifyStartWrite(e,[],()=>{e._deletedFromServer=r.deletedFromServer,this.updateExistingLibrary(e.collection,e,r.manifest,void 0,o.base,()=>{e._commit(!0,!0)})})});t(null,r.success)})}resolvePullWithBranch(e,t,i,n,o){this._services.log("resolvePullWithBranch"),this._config.SHARED_LOCAL_STORAGE?(e._dcxComposite._current=t,this._setBase(e.id,i),this._services.log("Finished resolvePullWithBranch: shared local storage"),o(),e._unblockCommits()):n?e._dcxLock.obtain(()=>{e._dcxComposite._current=t,e._dcxLock.release(),this._services.log("Finished resolvePullWithBranch: local merge"),o()}):e._dcxLock.obtain(()=>{e._dcxComposite.resolvePullWithBranch(t,(t,i)=>{e._dcxLock.release(),e._commit(!0,!0),e._waitForCommit(()=>{this._services.log("Finished resolvePullWithBranch: remote merge"),o(t,i)})})})}acceptPush(e,t){this._services.log("acceptPush"),e._dcxLock.obtain(()=>{e._dcxComposite.acceptPush(i=>{e._dcxLock.release(),this._services.log("Finished acceptPush"),this._acceptPushedBranchListeners.forEach(t=>t(e)),t(i)})})}onAcceptPushedBranch(e){this._acceptPushedBranchListeners.push(e)}removeOnAcceptPushedBranchListeners(){this._acceptPushedBranchListeners=[]}createNewLibrary(e,t,i,n=(()=>{})){this._services.log("createNewLibrary"),this._addLibrary(e,t,void 0,i,(e,t)=>{!e&&t?(t._commit(!1,!0),t._waitForCommit(n)):n(e)})}loadExistingLibrary(e,t,i,n,o,r,s=(()=>{})){this._services.log("loadExistingLibrary"),this._addLibrary(e,t,void 0,n,(e,t)=>{!e&&t?(t._deletedFromServer=o,r&&t._renditionCache.replaceCache(r),s(null,t)):s(e)})}updateExistingLibrary(e,t,i,n,o,r=(()=>{})){const s="updateExistingLibrary["+this._getLogIndex()+"]: ",a=e=>{const n=p.getManifestForComparison(t,i);return p.areManifestsEqual(n,e)};if(a(i))return this._services.log(s+"already up-to-date"),void r();const c=this._loadBranch(t._dcxComposite,i,!1);if(this._services.log(s+"changes to update (state = "+(c&&c.compositeState)+")"),!c)return void r(new l(l.CORRUPTED_LIBRARY,"Invalid manifest",t.id));const h=p.ensureBranchDataValid(c);if(this._services.log(s+"fixed branch data: "+h),"pendingDelete"===c.compositeState||"pendingDiscard"===c.compositeState)return e._doRemoveLibrary(t),void r();t._waitForCommit(()=>{if(n){if(!a(n))return this._services.log(s+"Commit aborting: something changed and it's no longer a fast-forward"),void r(!0)}else n=this._getBase(t.id);if(o&&n!==o)return this._services.log(s+"Commit aborting: base manifest changed before we got chance to update!"),void r(!0);const e=this._loadBranch(t._dcxComposite,n,!0)||c;this._services.log(s+"base "+e.changeCount+" -> updated "+c.changeCount),t._mergeAndSwitchToBranch(c,e,()=>{this._services.log(s+"finished merge"),this._config.SHARED_LOCAL_STORAGE?r(null):(t._commit(!1,!0),t._waitForCommit(r))})})}getRenditionPath(e,t,i=(()=>{}),n=0){const o=e.library._renditionCache.getCache(e,t||"full");if(o)return void i(null,o);const r=f(e);r.size=t,this._services.log("Get rendition path from CCLibrary process"),this._channel.call("getrenditionpath",r,o=>{if(!o&&n<this._config.LOCAL_RENDITION_MAX_RETRIES)return this._services.log("getrenditionpath: rendition not found"),void setTimeout(()=>this.getRenditionPath(e,t,i,n+1),this._config.LOCAL_RENDITION_RETRY_INTERVAL);i(null,o)})}notifyDownloadRendition(e){this._downloadRenditionListeners.forEach(t=>t(e)),e._listenerManager.notify("change")}onDownloadRendition(e){this._downloadRenditionListeners.push(e)}removeOnDownloadRenditionListeners(){this._downloadRenditionCacheListeners=[]}notifyStartWrite(e,t,i=(()=>{})){if(!this._config.SHARED_LOCAL_STORAGE)return void i(null);const n=g(e);n.dependencies=t.map(e=>g(e)),this._channel.call("startcomponentwrite",n,()=>i(null))}loadPublicLibrary(e,{id:t,url:i},n=(()=>{})){const o=m(e);o.id=t,o.url=i,this._channel.call("loadpubliclibrary",o,()=>n(null))}unloadPublicLibrary(e,t=(()=>{})){const i=g(e);this._channel.call("unloadpubliclibrary",i,()=>t(null))}loadTeamLibrary(e,{id:t,urn:i,teamUrn:n},o=(()=>{})){const r=m(e);r.id=t,r.urn=i,r.teamUrn=n,this._channel.call("loadteamlibrary",r,()=>o(null))}unloadTeamLibrary(e,t=(()=>{})){const i=g(e);this._channel.call("unloadteamlibrary",i,()=>t(null))}refreshTeams(e=(()=>{})){this._channel.call("refreshteams",{},()=>e(null))}downloadURL(e,t,i,n,o){if(!this._config.SHARED_LOCAL_STORAGE)return void e._syncManager.links.download(t,i,n,void 0,o);const r=m(e);r.url=t,r.headers=i,r.tempDir=n,this._channel.call("downloadfile",r,e=>{o(e.err,e.tempFilePath,e.etag,{headers:e.responseHeaders})})}testURL(e,t,i){this._config.SHARED_LOCAL_STORAGE?i(null):e._syncManager.links.test(t,i)}downloadExternalLink(e,t){this._services.log("Download external link from CCLibrary process"),this._channel.call("downloadexternallink",E(e),e=>t(e.err,e.path))}testExternalLink(e,t){this._services.log("Test external link via CCLibrary process"),this._channel.call("testexternallink",E(e),e=>t(e.err,e.success))}clearCachedExternalLink(e){this._services.log("Clear cached external link via CCLibrary process"),this._channel.send("clearcachedexternallink",E(e))}createBookmark(e,t,i,n,o,r=(()=>{})){const s=m(e);s.type=t,s.id=i,s.data=n,s.condition=o,this._channel.call("createBookmark",s,e=>{const t=e&&e.err,i=e&&e.bookmarks;r(t,i)})}removeBookmark(e,t,i=(()=>{})){const n=m(e);n.id=t.id,this._channel.call("removeBookmark",n,e=>i(e))}sendElementAction(e,t=(()=>{})){const i=f(e.element,"elementId","libraryId");i.appCode=e.appCode,i.minVersion=e.minAppVersion,i.action=e.id,this._channel.call("performElementAction",i,e=>t(e.err,e.data))}getImageDimensions(e,t){var i=this._services.fileUtils.getFileExtension(e);!i||y.includes(i)?this._config.SHARED_LOCAL_STORAGE?this._channel.call("getImageDimensions",e,e=>t(e.data)):this._services.imageSize(e,(e,i)=>t(i)):t()}importLibrary(e,t,i,n=(()=>{})){const o=m(e);o.path=t,o.operationId=i,this._channel.call("importlibrary",o,t=>{n(t.err,e.getLibraryById(t.libraryId))})}exportLibrary(e,t,i,n=(()=>{})){const o=g(e);o.path=t,o.operationId=i,this._channel.call("exportlibrary",o,e=>n(e.err))}cancelOperation(e,t){const i=m(e);i.operationId=t,this._channel.send("canceloperation",i)}moveLibrary(e,t,i=(()=>{})){const n=g(e);n.target=m(t),this._channel.call("movelibrary",n,e=>{i(e.err,e.libraryId&&t.getLibraryById(e.libraryId))})}getFontData(e,t,i=(()=>{})){const n=m(e);n.fontId=t,this._channel.call("getfontdata",n,e=>i(e.err,e.data))}isFontAvailable(e,t,i=(()=>{})){const n={fontName:e,matchFamily:t};this._channel.call("isfontavailable",n,({err:e,data:t})=>i(e,t))}getAccessToken(e,t,i,n,o=(()=>{})){const r={userId:e,clientId:t,clientSecret:i,scopes:n};this._channel.call("getaccesstoken",r,({err:e,data:t})=>o(e,t))}openInCCD(e,t=(()=>{})){const i={path:e};this._channel.call("openinccd",i,({err:e,data:i})=>t(e,i))}computeSHA(e){return this._config.SHARED_LOCAL_STORAGE?new Promise((t,i)=>{this._channel.call("computesha",{path:e},({err:e,data:n})=>e?i(e):t(n))}):this._services.fileUtils.computeSHA(e)}_getServiceVersion(){const e=this.getServiceInfo();return e&&e.apiVersion||0}supportsClearRenditionCache(){return this._getServiceVersion()>=7}supportsTestExternalLink(){return this._getServiceVersion()>=10}}},function(e,t,i){const n=i(3);e.exports=class{constructor(e,t,i,o,r){let s=i?`wss://${i}:${e}`:`ws://127.0.0.1:${e}`;s+=`/?version=${o}`,t&&(s+=`&token=${t}`),this._socket=new WebSocket(s),this._socket.onopen=()=>this._listenerManager.notify("open"),this._socket.onclose=()=>this._listenerManager.notify("close"),this._socket.onmessage=e=>this._listenerManager.notify("message",[e.data]),this._socket.onerror=e=>this._listenerManager.notify("error",[e]),this._listenerManager=new n(["open","close","message","error"],r)}send(e){this._socket.send(e)}addListener(e,t){this._listenerManager.add(e,t)}removeListener(e,t){this._listenerManager.remove(e,t)}close(){this._socket.close(),this._socket.onopen=void 0,this._socket.onclose=void 0,this._socket.onmessage=void 0,this._socket.onerror=void 0,this._listenerManager.removeAll()}}},function(e,t){e.exports=class{constructor(e){this._storageInterface=e}_fsCall(e,...t){const i="function"==typeof t[t.length-1]?t.pop():()=>{};this._storageInterface._channel.call("fscall",{method:e,args:t},e=>i.apply(null,e))}_pipeCall(e,t,i,n=(()=>{})){var o={readStream:{path:e,options:t},writeStream:i};this._storageInterface._channel.call("fspipe",o,n)}rename(...e){this._fsCall("rename",...e)}stat(...e){this._fsCall("stat",...e)}unlink(...e){this._fsCall("unlink",...e)}rmdir(...e){this._fsCall("rmdir",...e)}mkdir(...e){this._fsCall("mkdir",...e)}readdir(...e){this._fsCall("readdir",...e)}utimes(...e){this._fsCall("utimes",...e)}readFile(...e){this._fsCall("readFile",...e)}writeFile(...e){this._fsCall("writeFile",...e)}exists(...e){this._fsCall("exists",...e)}createReadStream(e){const t={on:(e,i)=>t[e]=i,pipe:(i,n)=>{this._pipeCall(e,n,i,e=>{t[e.event]&&t[e.event].apply(null,e.args)})}};return t}createWriteStream(e,t){return{path:e,options:t}}}},function(e,t){e.exports=class{constructor(e){this._apiRoot=e}get _services(){return this._apiRoot._services}generateUuid(){return this._services.uuid()}copyFile(e,t,i,n){if(i)return this._services.fileUtils.copyFile(e,t,n);const o=this._services.getFileNameFromPath(t);this._services.fileUtils.getAvailablePath(t.substring(0,t.indexOf(o)),o,(t,i)=>t?n(t):this._services.fileUtils.copyFile(e,i,n))}getFileSize(e,t){this._services.fileUtils.statFile(e,(e,i)=>t(e,i&&i.size))}}},function(e,t){e.exports=class{constructor(e){this._apiRoot=e}get _analytics(){return this._apiRoot._analytics}reportUseElement(e,t,i){this._analytics.reportUseElement(e,t,i)}reportCheckoutElement(e,t,i){this._analytics.reportCheckoutElement(e,t,i)}reportCreateLink(e,t){this._analytics.reportCreateLink(e,t)}reportShareElementLink(e){this._analytics.reportShareElementLink(e)}reportShareLibraryLink(e){this._analytics.reportShareLibraryLink(e)}}},function(e,t,i){const n=i(63);e.exports=class{constructor(e){this._apiRoot=e,this._channels=[]}newChannel(e,t){const i=new n(this._apiRoot,e,t);return this._channels.push(i),i.onClose(()=>{var e=this._channels.indexOf(i);-1!==e&&this._channels.splice(e,1),i.shutdown()}),i}numChannels(){return this._channels.length}broadcast(e,t,i){this._channels.forEach(n=>{i&&!i(n)||n.send(e,"function"==typeof t?t(n):t)})}getPendingWriteState(e,t,i,n){var o=!1;return this._channels.forEach(r=>{o=o||r.getPendingWriteState(e,t,i,r===n)}),o}}}]);